#!/usr/bin/env python3
from __future__ import annotations

import argparse
import datetime as dt
import html
import hashlib
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import webbrowser
from pathlib import Path
from typing import Any


VERSION = "2026.05.27-codeeadmin-next20-v1"
DEFAULT_ROUTE_TIMEOUT = 20
DEFAULT_API_BASE = os.getenv("CODEE_API_BASE", "https://clients.codee.chat").rstrip("/")
DEFAULT_API_FALLBACK_BASES = (
    "https://clients.codee.chat",
    "https://ai-k9-codee-digiapp-437923042920.us-central1.run.app",
)
CODEE_DOWNLOAD_URL = f"{DEFAULT_API_BASE}/assets/downloads/codee-cli.py"
CODEE_TOOL_REGISTRY_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-tool-registry.json"
CODEE_RELEASE_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-release.json"
CODEE_LAUNCH_URL = f"{DEFAULT_API_BASE}/codee-launch.html"
CODEE_LAUNCH_CHECKLIST_URL = f"{DEFAULT_API_BASE}/codee-launch-checklist.html"
CODEE_ONBOARDING_URL = f"{DEFAULT_API_BASE}/codee-onboarding.html"
CODEE_SAAS_URL = f"{DEFAULT_API_BASE}/codee-saas.html"
CODEE_PORTAL_URL = f"{DEFAULT_API_BASE}/codee-customer-portal.html"
CODEE_PROOF_WALL_URL = f"{DEFAULT_API_BASE}/codee-proof-wall.html"
CODEE_SAAS_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-saas-manifest.json"
CODEEADMIN_URL = f"{DEFAULT_API_BASE}/codeeadmin.html"
CODEEADMIN_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codeeadmin-manifest.json"
CODEEADMIN_DAILY_DIGEST_URL = f"{DEFAULT_API_BASE}/codeeadmin-daily.html"
CODEEADMIN_DAILY_DIGEST_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codeeadmin-daily-digest.json"
CODEEADMIN_STATES_URL = f"{DEFAULT_API_BASE}/codeeadmin-states.html"
CODEEADMIN_STATES_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codeeadmin-state-playbook.json"
CODEEADMIN_STATE_PACKET_URL = f"{DEFAULT_API_BASE}/codeeadmin-state.html"
CODEEADMIN_STATE_PACKET_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codeeadmin-state-packets.json"
CODEEADMIN_NEXT20_URL = f"{DEFAULT_API_BASE}/codeeadmin-next20.html"
CODEEADMIN_NEXT20_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codeeadmin-next20.json"
LANDEE_MISSION_PACKET_URL = f"{DEFAULT_API_BASE}/landee-mission-packet.html"
LANDEE_MISSION_PACKET_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/landee-mission-packet.json"
CODEE_REMOTE_URL = f"{DEFAULT_API_BASE}/codee-remote.html"
CODEE_REMOTE_VIEWER_URL = f"{DEFAULT_API_BASE}/codee-remote-viewer.html"
CODEE_REMOTE_CLI_URL = f"{DEFAULT_API_BASE}/codee-remote-cli.html"
CODEE_REMOTE_INSTALLER_URL = f"{DEFAULT_API_BASE}/codee-remote-installer.html"
CODEE_REMOTE_DEMO_URL = f"{DEFAULT_API_BASE}/codee-remote-demo.html"
CODEE_REMOTE_SECURITY_URL = f"{DEFAULT_API_BASE}/codee-remote-security.html"
CODEE_REMOTE_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-remote-manifest.json"
CODEE_REMOTE_HOST_DOWNLOAD_URL = f"{DEFAULT_API_BASE}/assets/downloads/codee-remote-host.py"
CODEE_COMPANY_ALIGNMENT_URL = f"{DEFAULT_API_BASE}/codee-company-alignment.html"
CODEE_IP_REGISTER_URL = f"{DEFAULT_API_BASE}/codee-ip-register.html"
CODEE_INVESTOR_READINESS_URL = f"{DEFAULT_API_BASE}/codee-investor-readiness.html"
CODEE_IMPACT_MODEL_URL = f"{DEFAULT_API_BASE}/codee-impact-model.html"
CODEE_BUSINESS_MISSION_URL = f"{DEFAULT_API_BASE}/codee-business-with-a-mission.html"
CODEE_IMPACT_REPORT_TEMPLATE_URL = f"{DEFAULT_API_BASE}/codee-impact-report-template.html"
CODEE_AGENT_INVESTMENT_MODEL_URL = f"{DEFAULT_API_BASE}/codee-agent-investment-model.html"
CODEE_DATA_ROOM_CHECKLIST_URL = f"{DEFAULT_API_BASE}/codee-data-room-checklist.html"
CODEE_COMPANY_ALIGNMENT_JSON_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-company-alignment.json"
CODEE_CPA_URL = f"{DEFAULT_API_BASE}/codee-cpa.html"
CODEE_CPA_WORKSPACE_URL = f"{DEFAULT_API_BASE}/codee-cpa-workspace.html"

SENSITIVE_FILE_NAMES = {
    ".env",
    ".env.local",
    ".env.production",
    ".envrc",
    "id_rsa",
    "id_dsa",
    "id_ecdsa",
    "id_ed25519",
    "credentials.json",
    "service-account.json",
    "firebase-adminsdk.json",
    "google-credentials.json",
    "stripe-secret.txt",
    "secrets.toml",
}
SENSITIVE_FILE_PATTERNS = (
    "secret",
    "private-key",
    "private_key",
    "service-account",
    "refresh-token",
    "oauth-token",
    "stripe-live",
    "stripe-secret",
    "api-key",
)
SENSITIVE_SUFFIXES = {".pem", ".key", ".p12", ".p8"}

CODEE_PLATFORM_20_MOVES = [
    "install-upgrade",
    "login-identity",
    "permission-profiles",
    "sensitive-file-guardrails",
    "lifecycle-hooks",
    "heartbeat-loop",
    "lane-contracts",
    "state-json",
    "checkpoints",
    "doctor-command",
    "lane-test-command",
    "preview-command",
    "activate-command",
    "delivery-command",
    "tool-registry",
    "connector-registry",
    "admin-status-surface",
    "eval-reports",
    "public-training-page",
    "release-discipline",
]

CODEEADMIN_US_STATES = [
    {"code": "AL", "name": "Alabama", "region": "South"},
    {"code": "AK", "name": "Alaska", "region": "West"},
    {"code": "AZ", "name": "Arizona", "region": "West"},
    {"code": "AR", "name": "Arkansas", "region": "South"},
    {"code": "CA", "name": "California", "region": "West"},
    {"code": "CO", "name": "Colorado", "region": "West"},
    {"code": "CT", "name": "Connecticut", "region": "Northeast"},
    {"code": "DE", "name": "Delaware", "region": "South"},
    {"code": "FL", "name": "Florida", "region": "South"},
    {"code": "GA", "name": "Georgia", "region": "South"},
    {"code": "HI", "name": "Hawaii", "region": "West"},
    {"code": "ID", "name": "Idaho", "region": "West"},
    {"code": "IL", "name": "Illinois", "region": "Midwest"},
    {"code": "IN", "name": "Indiana", "region": "Midwest"},
    {"code": "IA", "name": "Iowa", "region": "Midwest"},
    {"code": "KS", "name": "Kansas", "region": "Midwest"},
    {"code": "KY", "name": "Kentucky", "region": "South"},
    {"code": "LA", "name": "Louisiana", "region": "South"},
    {"code": "ME", "name": "Maine", "region": "Northeast"},
    {"code": "MD", "name": "Maryland", "region": "South"},
    {"code": "MA", "name": "Massachusetts", "region": "Northeast"},
    {"code": "MI", "name": "Michigan", "region": "Midwest"},
    {"code": "MN", "name": "Minnesota", "region": "Midwest"},
    {"code": "MS", "name": "Mississippi", "region": "South"},
    {"code": "MO", "name": "Missouri", "region": "Midwest"},
    {"code": "MT", "name": "Montana", "region": "West"},
    {"code": "NE", "name": "Nebraska", "region": "Midwest"},
    {"code": "NV", "name": "Nevada", "region": "West"},
    {"code": "NH", "name": "New Hampshire", "region": "Northeast"},
    {"code": "NJ", "name": "New Jersey", "region": "Northeast"},
    {"code": "NM", "name": "New Mexico", "region": "West"},
    {"code": "NY", "name": "New York", "region": "Northeast"},
    {"code": "NC", "name": "North Carolina", "region": "South"},
    {"code": "ND", "name": "North Dakota", "region": "Midwest"},
    {"code": "OH", "name": "Ohio", "region": "Midwest"},
    {"code": "OK", "name": "Oklahoma", "region": "South"},
    {"code": "OR", "name": "Oregon", "region": "West"},
    {"code": "PA", "name": "Pennsylvania", "region": "Northeast"},
    {"code": "RI", "name": "Rhode Island", "region": "Northeast"},
    {"code": "SC", "name": "South Carolina", "region": "South"},
    {"code": "SD", "name": "South Dakota", "region": "Midwest"},
    {"code": "TN", "name": "Tennessee", "region": "South"},
    {"code": "TX", "name": "Texas", "region": "South"},
    {"code": "UT", "name": "Utah", "region": "West"},
    {"code": "VT", "name": "Vermont", "region": "Northeast"},
    {"code": "VA", "name": "Virginia", "region": "South"},
    {"code": "WA", "name": "Washington", "region": "West"},
    {"code": "WV", "name": "West Virginia", "region": "South"},
    {"code": "WI", "name": "Wisconsin", "region": "Midwest"},
    {"code": "WY", "name": "Wyoming", "region": "West"},
    {"code": "DC", "name": "District of Columbia", "region": "South"},
]

CODEEADMIN_STATE_FOCUS_REGIONS = {
    "NY": ["New York City / Staten Island", "New York State veteran housing partners"],
    "OH": ["Carroll, Ohio", "Ohio statewide veteran housing partners", "AI K9 Kennel headquarters state"],
}

CODEEADMIN_STATE_READINESS_STAGES = [
    {"id": "queued", "label": "Queued", "score": 8, "gate": "Pick the state and create the first packet."},
    {"id": "source-links", "label": "Source Links", "score": 18, "gate": "Attach official current state, housing, land, utility, grant, and veteran source links."},
    {"id": "professional-review", "label": "Professional Review", "score": 35, "gate": "Send zoning, tax, nonprofit, grant, insurance, and real-estate questions to CODEECPA prep."},
    {"id": "partner-map", "label": "Partner Map", "score": 55, "gate": "Identify housing authority, voucher, landlord, sponsor, donor, and local operator contacts."},
    {"id": "sponsor-packet", "label": "Sponsor Packet", "score": 72, "gate": "Create a board/advisor-ready packet with mission, budget ranges, restrictions, and proof links."},
    {"id": "pilot-ready", "label": "Pilot Ready", "score": 90, "gate": "Owner, board, advisor, and licensed reviewers approve the first public ask or pilot."},
]

CODEEADMIN_STATE_ACTION_ROOMS = [
    {
        "id": "official-sources",
        "label": "Official Sources",
        "owner_agent": "Landee",
        "purpose": "Collect current government, housing, land, utility, veteran, zoning, and grant links before claims move.",
    },
    {
        "id": "professional-review",
        "label": "Professional Review",
        "owner_agent": "CODEECPA",
        "purpose": "Prepare questions for licensed legal, tax, CPA, grant, real-estate, insurance, and zoning review.",
    },
    {
        "id": "partner-outreach",
        "label": "Partner Outreach",
        "owner_agent": "Bizy",
        "purpose": "Queue sponsor, landlord, housing authority, donor, local business, and veteran-founder follow-up.",
    },
    {
        "id": "service-activation",
        "label": "Service Activation",
        "owner_agent": "Codee",
        "purpose": "Offer QR, flyer, app, card, blog, and Business Suite support for state-local businesses and veteran founders.",
    },
    {
        "id": "content-proof",
        "label": "Content Proof",
        "owner_agent": "Cappy",
        "purpose": "Create only proof-backed flyers, posts, guide pages, sponsor one-pagers, and local campaign assets.",
    },
]

CODEEADMIN_NEXT20_MOVES = [
    {"id": "active-state-source-lock", "title": "Lock active-state sources", "owner_agent": "Landee", "proof_gate": "Each active state has official source-link slots before public claims.", "output": "NY and OH source worksheet"},
    {"id": "state-packet-summary", "title": "Write state packet summaries", "owner_agent": "CodeeAdmin", "proof_gate": "Each active state has a one-screen mission summary.", "output": "owner-readable packet summary"},
    {"id": "official-link-inventory", "title": "Build official-link inventory", "owner_agent": "Landee", "proof_gate": "Every source category has a blank or verified URL field.", "output": "source inventory"},
    {"id": "housing-voucher-map", "title": "Map housing and voucher partners", "owner_agent": "Landee", "proof_gate": "Partner names remain draft until verified from official or direct sources.", "output": "partner map"},
    {"id": "sponsor-ask-builder", "title": "Draft sponsor ask builder", "owner_agent": "Bizy", "proof_gate": "Sponsor asks separate donations, service revenue, and restricted funds.", "output": "sponsor ask worksheet"},
    {"id": "board-review-queue", "title": "Create board review queue", "owner_agent": "CodeeAdmin", "proof_gate": "Land, grant, donor, and housing commitments require owner/board/advisor gate.", "output": "board queue"},
    {"id": "codeecpa-review-brief", "title": "Prepare CODEECPA review brief", "owner_agent": "CODEECPA", "proof_gate": "Questions are prepared without pretending to be legal/tax advice.", "output": "professional review brief"},
    {"id": "risk-register", "title": "Add state risk register", "owner_agent": "CODEECPA", "proof_gate": "Restricted funds, land purchase, housing promises, and tax/legal claims are flagged.", "output": "risk register"},
    {"id": "budget-bucket-map", "title": "Separate budget buckets", "owner_agent": "CodeeAdmin", "proof_gate": "Nonprofit donations, grants, sponsor funds, service revenue, and tech costs stay separate.", "output": "budget bucket worksheet"},
    {"id": "local-business-service-angle", "title": "Define local business service angle", "owner_agent": "Codee", "proof_gate": "Each state packet includes Codee service examples without outcome guarantees.", "output": "state service map"},
    {"id": "veteran-founder-training-angle", "title": "Define veteran founder training angle", "owner_agent": "Codee", "proof_gate": "Homeless and disabled veterans stay first priority for sponsored training.", "output": "training access note"},
    {"id": "content-proof-pack", "title": "Create content proof pack", "owner_agent": "Cappy", "proof_gate": "Only proof-backed claims move into posts, flyers, or sponsor pages.", "output": "content proof checklist"},
    {"id": "state-dashboard-filters", "title": "Improve state dashboard filters", "owner_agent": "CodeeAdmin", "proof_gate": "Queued, active, and review-needed states are easy to scan.", "output": "dashboard filter rules"},
    {"id": "state-packet-export", "title": "Add state packet export path", "owner_agent": "CodeeAdmin", "proof_gate": "CLI writes state JSON and active-state Markdown every run.", "output": "state export files"},
    {"id": "landee-handoff-sync", "title": "Sync Landee handoff", "owner_agent": "Landee", "proof_gate": "Landee packet references active state packets.", "output": "Landee active-state handoff"},
    {"id": "codeemail-digest-hook", "title": "Add CODEEMAIL digest hook", "owner_agent": "CodeeAdmin", "proof_gate": "Daily digest points back to active state packets.", "output": "CODEEMAIL-ready notice"},
    {"id": "route-proof-extension", "title": "Extend route proof", "owner_agent": "CodeeAdmin", "proof_gate": "Next 20 routes are checked by the 404 loop.", "output": "route-loop target"},
    {"id": "release-channel-note", "title": "Update release channel note", "owner_agent": "Codee", "proof_gate": "CLI release manifest explains the Next 20 update.", "output": "release changelog"},
    {"id": "owner-hq-entry", "title": "Add Owner HQ entry", "owner_agent": "CodeeAdmin", "proof_gate": "Owner HQ links directly to the execution board.", "output": "HQ action link"},
    {"id": "morning-loop-ready", "title": "Make it morning-loop ready", "owner_agent": "CodeeAdmin", "proof_gate": "Doctor, route loop, and state packet writes can run in the morning scan path.", "output": "morning proof checklist"},
]

CODEEADMIN_MODEL = {
    "schema": "codee.admin-operator.v1",
    "version": VERSION,
    "updated_at": "2026-05-27",
    "public_page": CODEEADMIN_URL,
    "manifest_url": CODEEADMIN_MANIFEST_URL,
    "next20_page": CODEEADMIN_NEXT20_URL,
    "next20_manifest": CODEEADMIN_NEXT20_MANIFEST_URL,
    "mission": "Let CodeeAdmin run the operating checklist, proof loops, and agent routing so Sean can focus on Invest In Vets land, housing, and mission execution.",
    "entities": [
        {
            "id": "invest-in-vets",
            "name": "Invest In Vets Foundation",
            "role": "Mission umbrella, veteran-first training, donors, sponsors, land and housing roadmap.",
            "codeeadmin_rule": "Protect nonprofit separation, board/advisor review, impact proof, and land-acquisition priorities.",
        },
        {
            "id": "ai-k9-kennel",
            "name": "AI K9 Kennel",
            "role": "Technology and service company operating Codee, service delivery, shops, hosting, and partners.",
            "codeeadmin_rule": "Turn service revenue into clean operating proof, support queues, reinvestment reports, and platform improvements.",
        },
        {
            "id": "codee",
            "name": "Codee Platform",
            "role": "CLI, chat intake, delivery rooms, proof loops, subscriptions, courses, and customer workspaces.",
            "codeeadmin_rule": "Keep lanes scanned, paid activation gated, customer delivery rooms clear, and next recommendations visible.",
        },
    ],
    "daily_operating_loop": [
        "Read owner workspace summary and CODEEMAIL receipts.",
        "Check Stripe/service/shop/donation totals and flag missing live rollups.",
        "Run route proof loops before promotion or hard selling.",
        "Review delivered sites, open support requests, and customer delivery-room status.",
        "Route nonprofit land, housing, and donor work to Landee or Invest In Vets queues.",
        "Route service growth, QR/flyer/app/card/blog/Business Suite work to Codee.",
        "Route social content and campaign checks to Codee Metricool logic.",
        "Route legal/tax/entity/investor questions to CODEECPA prep before public claims.",
        "Write the next three owner moves and one thing CodeeAdmin handled without owner attention.",
    ],
    "ai_k9_agents": [
        {"id": "codee", "status": "active", "job": "Business-output agent for digital services, CLI, intake, delivery rooms, and proof."},
        {"id": "landee", "status": "active", "job": "Housing, land, voucher, landlord, sponsor, and nonprofit mission operations."},
        {"id": "bizy", "status": "ready-next", "job": "Lead capture, follow-up, QR campaigns, and business busy-work."},
        {"id": "sporty", "status": "guarded", "job": "Sports research only with no betting automation or profit promises."},
        {"id": "tradez", "status": "guarded", "job": "Admin-only research with strict no-execution and no-nonprofit-funds rules."},
        {"id": "cappy", "status": "ready-next", "job": "Content, Canva/Adobe handoff, social assets, and visual campaign production."},
        {"id": "codeecpa", "status": "guarded", "job": "Professional-review prep for legal, tax, accounting, nonprofit, and investor questions."},
    ],
    "owner_focus_rules": [
        "Sean should see only the next three highest-value moves unless he opens deep ops.",
        "CodeeAdmin should separate mission work from paid service work before money or public claims move.",
        "No nonprofit funds are used for speculative trading, betting, or unreviewed business risks.",
        "Every public claim must tie back to proof, delivery-room evidence, advisor review, or impact reports.",
        "Other AI K9s begin only after CodeeAdmin defines their job, guardrails, proof route, and owner approval gate.",
    ],
    "focus_lock": {
        "hours": 72,
        "rule": "Do not open new public service lanes during the lock. Stabilize CodeeAdmin, Codee, Landee, CODEECPA, Cappy, and Bizy first.",
        "allowed_new_work": ["route fixes", "paid-client support", "nonprofit land/housing packet", "proof reports", "mission-critical corrections"],
        "blocked_new_work": ["new AI K9 launch", "new public paid lane", "speculative trading/betting logic", "unreviewed investor or legal claims"],
    },
    "money_lanes": [
        {"id": "services", "label": "Codee service revenue", "owner": "AI K9 Kennel", "rule": "Digital services, delivery rooms, hosting setup, support, and Business Suite work."},
        {"id": "shops", "label": "Shop revenue", "owner": "AI K9 Kennel or approved shop entity", "rule": "Merch, guidebooks, digital packets, and product downloads stay itemized by shop."},
        {"id": "donations", "label": "Donations", "owner": "Invest In Vets Foundation", "rule": "Donation, sponsor, and grant records stay separate from service revenue."},
        {"id": "grants-sponsors", "label": "Grants and sponsors", "owner": "Invest In Vets Foundation", "rule": "Use board/advisor review before public claims, restricted funds, or land commitments."},
        {"id": "hosting-subscriptions", "label": "Hosting and subscriptions", "owner": "AI K9 Kennel", "rule": "Recurring support and hosting must tie to customer, service, delivery room, and cancellation path."},
    ],
    "weekly_proof_report": [
        "services sold",
        "delivery rooms created",
        "sites scanned",
        "support requests handled",
        "shop downloads and product links checked",
        "donations, sponsor leads, and nonprofit packets reviewed",
        "mission progress toward land and housing",
    ],
    "next20_execution": {
        "public_page": CODEEADMIN_NEXT20_URL,
        "manifest": CODEEADMIN_NEXT20_MANIFEST_URL,
        "move_count": len(CODEEADMIN_NEXT20_MOVES),
        "rule": "The next 20 moves strengthen CodeeAdmin, Landee, CODEECPA, Codee, Cappy, and Bizy before opening new lanes.",
        "moves": CODEEADMIN_NEXT20_MOVES,
    },
    "landee_mission_packet": {
        "public_page": LANDEE_MISSION_PACKET_URL,
        "manifest": LANDEE_MISSION_PACKET_MANIFEST_URL,
        "first_regions": ["New York City / Staten Island", "Carroll, Ohio", "Ohio statewide"],
        "next_actions": [
            "Create one board-ready land and housing packet.",
            "List land search criteria, voucher partner criteria, solar/data center concept, and sponsor ask.",
            "Separate mission funding, land acquisition, housing operations, and technology support costs.",
            "Route legal, tax, grant, zoning, and real-estate questions to CODEECPA prep before commitments.",
        ],
    },
    "state_by_state_tool": {
        "public_page": CODEEADMIN_STATES_URL,
        "manifest": CODEEADMIN_STATES_MANIFEST_URL,
        "state_packet_page": CODEEADMIN_STATE_PACKET_URL,
        "state_packet_manifest": CODEEADMIN_STATE_PACKET_MANIFEST_URL,
        "next20_page": CODEEADMIN_NEXT20_URL,
        "next20_manifest": CODEEADMIN_NEXT20_MANIFEST_URL,
        "coverage_count": len(CODEEADMIN_US_STATES),
        "default_active_states": ["NY", "OH"],
        "rule": "Each state gets one mission packet, one opportunity scorecard, one professional-review queue, and one owner next-three list before any land or funding commitment.",
        "readiness_stages": CODEEADMIN_STATE_READINESS_STAGES,
        "action_rooms": CODEEADMIN_STATE_ACTION_ROOMS,
    },
}

CODEE_REMOTE_20_MOVES = [
    {"id": "desktop-host-skeleton", "status": "foundation-live", "proof": "codee-remote-host.py download and host command"},
    {"id": "secure-device-pairing", "status": "foundation-live", "proof": "remote pair packet with expiration and device id"},
    {"id": "device-registry-plan", "status": "foundation-live", "proof": "remote host profile and installer manifest"},
    {"id": "session-start-stop-api-plan", "status": "foundation-live", "proof": "remote session command and session packet"},
    {"id": "phone-viewer-shell", "status": "foundation-live", "proof": "codee-remote-viewer.html"},
    {"id": "desktop-consent-banner-rule", "status": "foundation-live", "proof": "remote security gate and viewer rules"},
    {"id": "emergency-stop-rule", "status": "foundation-live", "proof": "remote security gate blocks silent control"},
    {"id": "remote-cli-command-queue", "status": "foundation-live", "proof": "remote bridge command and host skeleton queue file"},
    {"id": "cli-allowlist-lock", "status": "foundation-live", "proof": "remote bridge blocked actions and host allowlist"},
    {"id": "audit-log-events", "status": "foundation-live", "proof": "remote audit command and event trail"},
    {"id": "entitlement-gate", "status": "foundation-live", "proof": "remote manifest requires pro or business-suite"},
    {"id": "portal-remote-controls-plan", "status": "foundation-live", "proof": "remote portal URLs in pairing/session packets"},
    {"id": "remote-installer-page", "status": "foundation-live", "proof": "codee-remote-installer.html"},
    {"id": "host-self-update-plan", "status": "foundation-live", "proof": "remote host download URL and stable channel note"},
    {"id": "webrtc-signaling-plan", "status": "foundation-live", "proof": "remote manifest backend components"},
    {"id": "turn-relay-plan", "status": "foundation-live", "proof": "remote manifest specialized components"},
    {"id": "playwright-proof-targets", "status": "foundation-live", "proof": "404 loop targets for remote pages"},
    {"id": "remote-readiness-scan", "status": "foundation-live", "proof": "remote readiness command"},
    {"id": "public-demo-mode", "status": "foundation-live", "proof": "codee-remote-demo.html and demo command"},
    {"id": "security-review-gate", "status": "foundation-live", "proof": "codee-remote-security.html and security command"},
]

CODEE_REMOTE_SECURITY_GATE = [
    "pairing code expiration",
    "visible desktop consent banner",
    "phone and desktop emergency stop",
    "MFA or passkey before public active control",
    "device registry with revoke",
    "session audit trail",
    "allowlisted CLI commands only",
    "no public owner credentials",
    "no unattended control by default",
    "security review before screen input ships",
]

CODEE_PUBLIC_LAUNCH_20_MOVES = [
    {"id": "public-launch-page", "title": "Lock the public launch page", "status": "foundation-live", "proof": CODEE_LAUNCH_URL, "command": "python3 codee.py launch . --write --force"},
    {"id": "start-with-one-lane", "title": "Add Start With One Lane onboarding", "status": "foundation-live", "proof": CODEE_ONBOARDING_URL, "command": "python3 codee.py starter . --preset qrcodee --force"},
    {"id": "preview-then-paywall", "title": "Create preview first, paywall at activation", "status": "foundation-live", "proof": "preview and activate commands", "command": "python3 codee.py preview . --service codeeqr --dry-run"},
    {"id": "user-ids", "title": "Attach Codee user IDs to workspaces", "status": "foundation-live", "proof": "login, account, .codee/state.json", "command": "python3 codee.py login . --email owner@example.com --write"},
    {"id": "customer-dashboard", "title": "Build the customer dashboard path", "status": "foundation-live", "proof": CODEE_PORTAL_URL, "command": "python3 codee.py portal . --service codeeqr"},
    {"id": "doctor-explainer", "title": "Explain Codee Doctor in plain language", "status": "foundation-live", "proof": "doctor and heartbeat reports", "command": "python3 codee.py doctor ."},
    {"id": "lane-demo-videos", "title": "Prepare one demo-video script per lane", "status": "packet-ready", "proof": ".codee/launch/LANE_DEMO_SCRIPTS.md", "command": "python3 codee.py launch . --write --force"},
    {"id": "veteran-accessible-courses", "title": "Make courses more visual and accessible", "status": "foundation-live", "proof": "accessibility command and trainee hub", "command": "python3 codee.py accessibility . --write --force"},
    {"id": "veteran-verification", "title": "Separate free veteran path from paid public path", "status": "packet-ready", "proof": ".codee/launch/VETERAN_ACCESS_RULES.md", "command": "python3 codee.py launch . --write --force"},
    {"id": "business-suite-flagship", "title": "Position Codee Business Suite as flagship", "status": "foundation-live", "proof": "business-suite entitlement and chat route", "command": "python3 codee.py entitlements . --plan business-suite"},
    {"id": "stripe-customer-portal", "title": "Prepare Stripe customer portal and billing history", "status": "backend-gated", "proof": "pricing, upgrade, invoice, license commands", "command": "python3 codee.py pricing ."},
    {"id": "release-channels", "title": "Use stable, beta, and owner/admin channels", "status": "foundation-live", "proof": CODEE_RELEASE_URL, "command": "python3 codee.py self-update . --write"},
    {"id": "cli-update-checking", "title": "Show upgrade checks inside the CLI", "status": "foundation-live", "proof": "self-update and release manifest", "command": "python3 codee.py self-update ."},
    {"id": "safe-remote-cli", "title": "Ship safer remote CLI before full remote control", "status": "foundation-live", "proof": CODEE_REMOTE_CLI_URL, "command": "python3 codee.py remote bridge . --write --force"},
    {"id": "investor-proof-data-room", "title": "Create investor proof data room", "status": "foundation-live", "proof": CODEE_DATA_ROOM_CHECKLIST_URL, "command": "python3 codee.py company . --packet all --write --force"},
    {"id": "policy-review", "title": "Prepare terms, privacy, refund, support, and acceptable-use review", "status": "packet-ready", "proof": ".codee/launch/POLICY_REVIEW_QUEUE.md", "command": "python3 codee.py launch . --write --force"},
    {"id": "ten-case-studies", "title": "Create ten real case-study slots", "status": "packet-ready", "proof": ".codee/launch/CASE_STUDY_SLOTS.md", "command": "python3 codee.py launch . --write --force"},
    {"id": "weekly-proof-report", "title": "Generate weekly proof reports", "status": "packet-ready", "proof": ".codee/launch/WEEKLY_PROOF_REPORT.md", "command": "python3 codee.py launch . --write --force"},
    {"id": "business-with-a-mission", "title": "Build the Business With A Mission partner page", "status": "foundation-live", "proof": CODEE_BUSINESS_MISSION_URL, "command": "python3 codee.py company . --packet impact --write --force"},
    {"id": "valuation-metrics", "title": "Track valuation and investability metrics", "status": "foundation-live", "proof": CODEE_INVESTOR_READINESS_URL, "command": "python3 codee.py launch . --write --force"},
]

CODEE_LEGAL_TAX_SOURCES = [
    {"name": "IRS Circular 230 tax professional standards", "url": "https://www.irs.gov/tax-professionals/Circular-230-Tax-Professionals", "use": "Tax practice before the IRS is governed by professional conduct rules."},
    {"name": "IRS PTIN requirements", "url": "https://www.eitc.irs.gov/tax-professionals/frequently-asked-questions-do-i-need-a-ptin", "use": "Paid federal tax return preparers generally need a PTIN."},
    {"name": "ABA AI and legal practice issues", "url": "https://www.americanbar.org/groups/centers_commissions/center-for-innovation/artificial-intelligence/issues/", "use": "AI legal tools raise confidentiality, accuracy, and unauthorized-practice risks."},
    {"name": "FTC Business Opportunity Rule guidance", "url": "https://www.ftc.gov/business-guidance/resources/selling-work-home-or-other-business-opportunity-revised-rule-may-apply-you-1", "use": "Earnings or money-making claims need proof and careful disclosures."},
]

CODEECPA_GUARDRAILS = [
    "CODEECPA is a consultation-prep, evidence-organization, and SOP tool.",
    "CODEECPA does not replace a licensed attorney, CPA, enrolled agent, board review, or insurance/risk advisor.",
    "Do not use CODEECPA to sign, file, or submit tax returns, legal filings, securities documents, nonprofit filings, or court documents.",
    "Do not claim attorney-client privilege, CPA-client privilege, or professional representation from the tool alone.",
    "Route final legal, tax, nonprofit, securities, employment, real estate, and insurance decisions to qualified professionals.",
    "Keep owner credentials, tax IDs, donor private data, bank data, customer private data, and unreconciled financials out of public packets.",
]

CODEECPA_PACKET = {
    "schema": "codee.cpa-legal-prep.v1",
    "version": VERSION,
    "updated_at": "2026-05-27",
    "public_page": CODEE_CPA_URL,
    "workspace_page": CODEE_CPA_WORKSPACE_URL,
    "positioning": "CODEECPA prepares clean legal, tax, accounting, nonprofit, and investor-review packets so licensed professionals can review faster and with less room to take advantage of a messy founder.",
    "guardrails": CODEECPA_GUARDRAILS,
    "official_sources": CODEE_LEGAL_TAX_SOURCES,
    "workflow": [
        "Identify the exact question and jurisdiction.",
        "Classify whether the issue is legal, tax, accounting, nonprofit governance, securities, employment, real estate, IP, privacy, or insurance.",
        "Collect source documents and facts without making final conclusions.",
        "Generate a professional question list and decision log.",
        "Highlight red flags, missing documents, and claims that need proof.",
        "Send the packet to a qualified attorney, CPA, enrolled agent, board member, or risk advisor.",
        "Record the professional answer, date, reviewer, and approved action.",
    ],
    "review_lanes": [
        "entity setup and ownership",
        "nonprofit and for-profit separation",
        "technology licensing to nonprofit",
        "revenue recognition and Stripe reports",
        "sales tax and digital-product tax questions",
        "payroll, contractor, and volunteer classification",
        "IP, trademark, copyright, and contributor assignments",
        "privacy, terms, refund, support, and acceptable-use policies",
        "business opportunity and earnings-claim review",
        "investor, sponsor, grant, and fundraising language",
        "real estate, housing, voucher, and land-development review",
    ],
    "red_flags": [
        "guaranteed income, investment, tax, grant, housing, voucher, or legal outcome claims",
        "mixing nonprofit and company funds without written agreements",
        "using customer, donor, veteran, or tax data in public proof",
        "filing tax/legal documents from AI output without professional review",
        "using contractors, volunteers, or contributors without written scope and IP terms",
        "charging for business-opportunity training while making unsupported earnings claims",
    ],
}

CODEE_COMPANY_ALIGNMENT = {
    "schema": "codee.company-alignment.v3",
    "version": "2026.05.27-agent-investment-v1",
    "updated_at": "2026-05-27",
    "disclaimer": "Operational draft only. Attorney, CPA, board, and investor review are still required.",
    "professional_review_required": ["attorney", "CPA", "nonprofit board", "insurance/risk advisor before remote-control release"],
    "entities": {
        "mission_umbrella": "Invest In Vets Foundation",
        "technology_company": "AI K9 Kennel",
        "platform": "Codee",
        "public_front_door": "https://codee.chat",
        "client_surfaces": DEFAULT_API_BASE,
    },
    "public_pages": {
        "launch": CODEE_LAUNCH_URL,
        "launch_checklist": CODEE_LAUNCH_CHECKLIST_URL,
        "onboarding": CODEE_ONBOARDING_URL,
        "company_alignment": CODEE_COMPANY_ALIGNMENT_URL,
        "ip_register": CODEE_IP_REGISTER_URL,
        "investor_readiness": CODEE_INVESTOR_READINESS_URL,
        "impact_model": CODEE_IMPACT_MODEL_URL,
        "business_with_a_mission": CODEE_BUSINESS_MISSION_URL,
        "impact_report_template": CODEE_IMPACT_REPORT_TEMPLATE_URL,
        "agent_investment_model": CODEE_AGENT_INVESTMENT_MODEL_URL,
        "data_room_checklist": CODEE_DATA_ROOM_CHECKLIST_URL,
        "codeecpa": CODEE_CPA_URL,
        "codeecpa_workspace": CODEE_CPA_WORKSPACE_URL,
        "proof_wall": CODEE_PROOF_WALL_URL,
        "json": CODEE_COMPANY_ALIGNMENT_JSON_URL,
    },
    "alignment": [
        "Invest In Vets Foundation is the mission umbrella.",
        "AI K9 Kennel is the technology and service company.",
        "Codee is the platform, CLI, delivery-room system, proof layer, and training surface.",
        "Open-source courses teach simple service lanes.",
        "Paid services, hosting, and support fund operations and mission progress.",
    ],
    "subscription_value_alignment": [
        "Codee should be valued like a serious paid tool: one user ID, local CLI, hosted backend activation, tiered usage, support gates, and proof reports.",
        "Codee should stay in its lane: business-output workflows, not generic chat replacement.",
        "Free or sponsored veteran access remains separate from paid public subscriptions and Business Suite packages.",
        "Usage, retention, delivery speed, support load, and impact metrics should be reported monthly.",
    ],
    "veteran_founder_path": [
        "Train a homeless or disabled veteran on one accessible open-source course first.",
        "Help that veteran create a focused Codee agent around one service lane.",
        "Generate one hosted page, one payment or contact path, one delivery room, and one scan report.",
        "Document the first customer, first delivery, support work, cost, time, and lesson learned.",
        "Package the proof as a public-safe founder case study for sponsors, mentors, advisors, and potential investors.",
    ],
    "defensibility_layers": [
        "brand and trademarks",
        "copyrighted source and training content",
        "trade-secret workflows and prompts",
        "service-lane templates",
        "proof-loop records",
        "customer delivery rooms",
        "mission-backed distribution",
        "release discipline and route scans",
    ],
    "security_rules": [
        "Do not ship owner credentials in public CLI downloads.",
        "Keep Stripe, GCloud, OAuth, and service account secrets out of support uploads.",
        "Gate hosting, payment activation, remote control, and third-party posting behind proof and permission checks.",
        "Use route scans, doctor reports, and delivery-room proof before public launch.",
    ],
    "investor_metrics": [
        "paid conversions",
        "monthly recurring revenue",
        "one-time service revenue",
        "repeat purchase rate",
        "refund rate",
        "average delivery time",
        "support time per client",
        "route-scan pass rate",
        "free veteran trainees served",
        "mission funds allocated",
        "active Codee CLI workspaces",
        "free-to-paid conversion rate",
        "subscription churn",
        "veteran founder case studies completed",
    ],
    "governance_packets": [
        "DATA_ROOM_INDEX.md",
        "GOVERNANCE_CHECKLIST.md",
        "TRADE_SECRET_REGISTER.md",
        "CONTRIBUTOR_ASSIGNMENT_CHECKLIST.md",
        "NONPROFIT_TECH_LICENSE_PREP.md",
        "MONTHLY_IMPACT_REPORT_YYYY_MM.md",
        "CASE_STUDY_TEMPLATE.md",
        "INVESTOR_SCORECARD_YYYY_MM.json",
    ],
    "data_room": {
        "folders": [
            "01-product-proof",
            "02-revenue-proof",
            "03-customer-delivery-proof",
            "04-impact-proof",
            "05-ip-and-brand-proof",
            "06-security-and-compliance-proof",
            "07-platform-architecture",
            "08-nonprofit-alignment",
            "09-investor-reports",
            "10-board-and-advisor-notes",
            "11-veteran-founder-proof",
            "12-subscription-and-retention-metrics",
        ],
        "rule": "Show proof without exposing private customer data, credentials, internal prompts, or unreconciled financials.",
    },
    "monthly_metrics": [
        "gross revenue",
        "monthly recurring revenue",
        "one-time service revenue",
        "active hosting/support customers",
        "paid services delivered",
        "average delivery time",
        "refund count",
        "support requests opened and closed",
        "route-scan pass rate",
        "veteran trainees served",
        "sponsored/free mission services",
        "housing/sponsor conversations",
        "funds allocated to mission programs",
        "active Codee CLI workspaces",
        "free-to-paid conversion rate",
        "subscription churn",
        "veteran founder case studies completed",
    ],
    "case_study_lanes": [
        "QRCodee",
        "CodeeFlyer100",
        "CodeeFlyer250",
        "CodeeApp250",
        "CodeeCard",
        "CodeeBeeper",
        "CodeeBlog",
        "Codee Business Suite",
        "Invest In Vets nonprofit shop",
        "AI K9 shop",
        "Veteran founder Codee agent",
    ],
    "next_20_moves": [
        "Create trademark filing plan.",
        "Create contributor assignment agreement.",
        "Create trade-secret access policy.",
        "Publish public terms, privacy, refund, support, and acceptable-use policy review tasks.",
        "Build investor data room.",
        "Publish monthly impact report.",
        "Draft nonprofit conflict-of-interest policy.",
        "Draft nonprofit technology license agreement.",
        "Create partner program for businesses with a mission.",
        "Keep release log and proof wall current.",
        "Make each delivery room the permanent customer source of truth.",
        "Build 10 real case studies.",
        "Add security gate before Codee Remote active control.",
        "Keep local-first memory and permission modes visible.",
        "Train owner/admin on hosting, domains, GCloud, Firebase, Stripe, storage, and delivery.",
        "Create a public business-with-a-mission guide.",
        "Create weekly scorecard reports.",
        "Keep free veteran training separate from paid public work.",
        "Track cost per service, support time, and retention.",
        "Archive source, deploy logs, scan reports, payment references, and delivery artifacts.",
    ],
}

LOCAL_PRICING = {
    "ok": True,
    "currency": "usd",
    "source": "local",
    "plans": [
        {
            "id": "pro",
            "name": "Codee CLI Pro",
            "label": "$29/mo Codee CLI Pro",
            "amount_cents": 2900,
            "mode": "subscription",
            "interval": "month",
            "invoice_allowed": False,
            "description": "Local Codee workspace, first-offer mapping, route scans, proof reports, and simple hosting command path.",
        },
        {
            "id": "partner",
            "name": "AI K9 Partner",
            "label": "$99/mo AI K9 Partner",
            "amount_cents": 9900,
            "mode": "subscription",
            "interval": "month",
            "invoice_allowed": False,
            "description": "Partner workspace structure for builders teaching or hosting Codee service lanes.",
        },
        {
            "id": "business-suite",
            "name": "Codee Business Suite",
            "label": "$2,500 Codee Business Suite",
            "amount_cents": 250000,
            "mode": "payment",
            "interval": "",
            "invoice_allowed": True,
            "description": "Codee Business Suite path with bundled assets, delivery proof, and focused launch handoff.",
        },
    ],
}

COURSE_CATALOG = {
    "core": [
        {
            "id": "qrcodee",
            "name": "QRCodee Open-Source Course",
            "lesson": "Create one QR image, connect the destination URL, customize colors, add a center logo, and prove one folder/index path scans.",
            "student_output": "A branded QR image, destination link, scan checklist, and a small proof page.",
            "paid_path": "QRCodee done-for-you image, hosted landing page, delivery room, route scans, and Codee support.",
            "activation_service": "codeeqr",
            "upload_needs": ["destination URL", "logo or mark", "brand color"],
        },
        {
            "id": "codeeflyer",
            "name": "Codee Flyer Open-Source Course",
            "lesson": "Drag in one flyer or product image, write the offer, add one CTA, add the QR image, and export the index page.",
            "student_output": "One hosted-ready flyer folder with index.html, image assets, CTA copy, and route checklist.",
            "paid_path": "Codee Flyer 100 or Codee Flyer 250 with hosting, QRCodee styling, and delivery support.",
            "activation_service": "codeeflyer",
            "upload_needs": ["flyer image or logo", "offer/event description", "CTA link", "brand color"],
        },
        {
            "id": "codeeapp",
            "name": "Codee App Open-Source Course",
            "lesson": "Turn a guidebook, PDF, checklist, or mini product into an app-style page with a cover, bullets, QR, and checkout/download path.",
            "student_output": "A guidebook app folder with cover art, buyer action, QR return path, and download/delivery instructions.",
            "paid_path": "Codee App 250 with client upload, hosted guidebook view, Stripe buyer path, and delivery room.",
            "activation_service": "codeeapp250",
            "upload_needs": ["guidebook/PDF", "cover image", "buyer or download link", "Stripe product path"],
        },
    ],
    "advanced": [
        {
            "id": "codeecard",
            "name": "Codee Card Service Course",
            "why": "A profile card is the easiest personal-brand proof lane after QR, flyer, and app.",
            "paid_path": "Done-for-you Codee Card with booking, message path, resume/profile blocks, and hosted proof.",
        },
        {
            "id": "delivery-room",
            "name": "Delivery Room + Support CLI Course",
            "why": "Clients need a permanent place to return, request edits, view products, and prove what they bought.",
            "paid_path": "Hosted delivery room, Codee support request packets, scans, and 30-day support.",
        },
        {
            "id": "folder-domain",
            "name": "Folder + Domain Readiness Course",
            "why": "Most launch failures come from messy folders, unclear routes, DNS confusion, or missing proof after hosting.",
            "paid_path": "Codee folder cleanup, hosting support, custom domain setup guidance, route scans, and delivery-room proof.",
        },
        {
            "id": "booking-room",
            "name": "Booking + Checkout Room Course",
            "why": "Many businesses need a consultation or event date flow before a full site.",
            "paid_path": "Embedded booking or Stripe-hosted payment flow connected to the client page.",
        },
        {
            "id": "business-suite",
            "name": "Codee Business Suite Course",
            "why": "This teaches how the smaller lanes combine into one client business package.",
            "paid_path": "Codee Business Suite with QRCodee, flyers, Codee App, Codee Blog, Codee Card, shell site, and support.",
        },
    ],
}

CODEE_LOOPS = [
    {
        "id": "intake-loop",
        "name": "Intake Loop",
        "purpose": "Turn a rough client idea into service, audience, assets, CTA, payment path, delivery path, and proof checklist.",
        "proof": ".codee/codee.json and quick-income-map.md",
    },
    {
        "id": "course-build-loop",
        "name": "Course Build Loop",
        "purpose": "Teach the open-source lane, scaffold the folder, export index.html, and decide whether Codee hosts it.",
        "proof": "codee-course.json and exported course folder",
    },
    {
        "id": "route-scan-loop",
        "name": "Route Scan Loop",
        "purpose": "Check public URLs before promotion, delivery, or support handoff.",
        "proof": ".codee/reports/latest-route-scan.json",
    },
    {
        "id": "heartbeat-loop",
        "name": "Public Heartbeat Loop",
        "purpose": "Give any downloaded Codee CLI user a quick pulse: identity, folder health, latest proof, live task status, and next commands.",
        "proof": ".codee/reports/latest-heartbeat.json and .codee/HEARTBEAT.md",
    },
    {
        "id": "overnight-15-loop",
        "name": "Overnight 15-Loop Watch",
        "purpose": "Run 15 sleep-safe proof cycles across public routes, video room health, CLI loop contract, and checkpoint readiness scans.",
        "proof": "prompt_inbox/.service-control/overnight-15-loop/latest-index.jsonl",
    },
    {
        "id": "delivery-room-loop",
        "name": "Delivery Room Loop",
        "purpose": "Keep the client's paid product, support room, update links, and upsells in one returnable route.",
        "proof": ".codee/reports/latest-delivery-room.json",
    },
    {
        "id": "support-request-loop",
        "name": "Support Request Loop",
        "purpose": "Let a client request edits from their CLI with route, service, message, attachments, and user ID.",
        "proof": ".codee/support-requests/ and latest-support-request.json",
    },
    {
        "id": "folder-assist-loop",
        "name": "Folder Assist Loop",
        "purpose": "Teach what belongs in a client folder, inspect what is present, and write a proof-backed folder plan before hosting.",
        "proof": ".codee/folder-plan.json and .codee/FOLDER_PLAN.md",
    },
    {
        "id": "domain-assist-loop",
        "name": "Domain Assist Loop",
        "purpose": "Teach the domain path in plain language: registrar, DNS, hosting target, SSL, route scan, and final proof.",
        "proof": ".codee/domain-plan.json and .codee/DOMAIN_PLAN.md",
    },
    {
        "id": "membership-renewal-loop",
        "name": "Membership Renewal Loop",
        "purpose": "Move finished students or hosted clients into ongoing scans, support, and updates only when value is clear.",
        "proof": "Stripe license, invoice, or membership metadata",
    },
]

FOLDER_ASSIST_STEPS = [
    "Keep the folder simple: one index.html, one assets folder, one .codee folder, and one proof report path.",
    "Name files like a client will understand them later. Avoid random export names when a page, flyer, logo, or download is final.",
    "Put images, PDFs, videos, and logos in assets/ or a clearly named child folder before asking Codee to host or update the site.",
    "Write the service purpose, CTA, payment or contact path, and delivery-room route in .codee/codee.json.",
    "Run a route scan after hosting and save the report before telling the client it is ready.",
]

DOMAIN_ASSIST_STEPS = [
    "Decide whether the client needs a full custom domain, a subdomain, or a clients.codee.chat delivery route first.",
    "Use the registrar only for ownership and DNS. Use the hosting provider for deploys, SSL, and route proof.",
    "Do not guess DNS records. Copy the exact CNAME, A, or TXT record requested by the hosting provider.",
    "Wait for SSL to become active, then test both the naked domain and www/subdomain route when used.",
    "After DNS works, run Codee route and browser scans so the client has proof instead of a verbal promise.",
]

SKILL_CATALOG = [
    {
        "id": "first-lane-qrcodee",
        "name": "QRCodee First-Lane Coach",
        "access": "public",
        "status": "built-in",
        "summary": "Keep new users focused on one teachable lane first: a folder, index.html, branded QR, scan proof, then paid hosting/support only when useful.",
        "commands": ["courses", "course-init", "folder-plan", "verify", "scan", "support"],
        "requires": ["python3"],
        "proof": "codee-course.json, index.html, .codee/folder-plan.json, and latest-route-scan.json",
    },
    {
        "id": "route-scan",
        "name": "Route Scan",
        "access": "public",
        "status": "built-in",
        "summary": "Check public URLs for 404s, redirects, and server errors before launch.",
        "commands": ["scan", "verify", "course-smoke"],
        "requires": ["python3"],
        "proof": ".codee/reports/latest-route-scan.json",
    },
    {
        "id": "course-suite",
        "name": "Open-Source Course Suite",
        "access": "public",
        "status": "built-in",
        "summary": "Create and validate QRCodee, Codee Flyer, and Codee App starter outputs.",
        "commands": ["courses", "course-init", "verify", "course-smoke"],
        "requires": ["python3"],
        "proof": "codee-course.json and .codee/reports/latest-course-suite-smoke.json",
    },
    {
        "id": "admin-training",
        "name": "Codee Admin Training",
        "access": "public",
        "status": "built-in",
        "summary": "Write and certify the platform, hosting, tier, and mission-license training playbook for Codee admins.",
        "commands": ["admin-training", "admin-certify"],
        "requires": ["python3"],
        "proof": ".codee/admin-training.json, .codee/ADMIN_TRAINING.md, and latest-admin-certification.json",
    },
    {
        "id": "business-assistant",
        "name": "Business-Type Assistant Templates",
        "access": "public",
        "status": "built-in",
        "summary": "Create a Codee assistant template around a specific business type, offer lane, intake, deliverables, support model, and proof checklist.",
        "commands": ["business-types", "business-assistant-init"],
        "requires": ["python3"],
        "proof": ".codee/business-assistant.json and BUSINESS_ASSISTANT.md",
    },
    {
        "id": "skill-policy",
        "name": "Workspace Skill Policy",
        "access": "public",
        "status": "built-in",
        "summary": "Write a per-workspace skill policy that separates safe local tools from backend and owner-gated tools.",
        "commands": ["skills", "skill-policy", "skill-check"],
        "requires": ["python3"],
        "proof": ".codee/skills.json and .codee/SKILLS.md",
    },
    {
        "id": "folder-coach",
        "name": "Folder Coach",
        "access": "public",
        "status": "built-in",
        "summary": "Inspect a service folder, explain what is missing, and write a clean folder plan before Codee hosts or supports it.",
        "commands": ["folder-plan"],
        "requires": ["python3"],
        "proof": ".codee/folder-plan.json and .codee/FOLDER_PLAN.md",
    },
    {
        "id": "domain-coach",
        "name": "Domain Coach",
        "access": "public",
        "status": "built-in",
        "summary": "Teach registrar, DNS, hosting, SSL, redirect, and route-scan steps in plain language without asking users to expose credentials.",
        "commands": ["domain-plan"],
        "requires": ["python3"],
        "proof": ".codee/domain-plan.json and .codee/DOMAIN_PLAN.md",
    },
    {
        "id": "browser-scan",
        "name": "Playwright Browser Scan",
        "access": "public-optional",
        "status": "optional-tool",
        "summary": "Open a live page with Playwright and capture a screenshot proof, when Node/npx and Playwright are available.",
        "commands": ["browser-scan"],
        "requires": ["node", "npx", "playwright"],
        "proof": ".codee/reports/latest-browser-scan.json and .codee/screenshots/",
    },
    {
        "id": "payment-stripe",
        "name": "Stripe Hosted Payment",
        "access": "backend",
        "status": "server-routed",
        "summary": "Create checkout, invoice, and license proof through Codee backend without storing card data in the CLI.",
        "commands": ["pricing", "upgrade", "invoice", "license"],
        "requires": ["Codee backend", "Stripe account"],
        "proof": ".codee/reports/latest-payment-request.json and .codee/license.json",
    },
    {
        "id": "backend-connect",
        "name": "Codee Backend Connector",
        "access": "public-plus-backend",
        "status": "server-routed",
        "summary": "Bind a local folder, generated course site, user ID, and activation packet to Codee backend before hosted payment activation.",
        "commands": ["connect", "activate", "verify", "account", "room", "workbench"],
        "requires": ["Codee backend"],
        "proof": ".codee/backend-connection.json and .codee/reports/latest-activation-request.json",
    },
    {
        "id": "support-room",
        "name": "Delivery Room Support",
        "access": "public-plus-backend",
        "status": "built-in",
        "summary": "Generate delivery-room links and support packets tied to the same user and workspace IDs.",
        "commands": ["account", "workbench", "room", "support"],
        "requires": ["python3"],
        "proof": ".codee/support-requests/ and .codee/reports/latest-support-request.json",
    },
    {
        "id": "codee-hooks",
        "name": "Codee Lifecycle Hooks",
        "access": "public",
        "status": "built-in",
        "summary": "Record safe lifecycle events like generate, verify, connect, activate, payment-required, deploy-complete, and scan-failed.",
        "commands": ["hooks", "verify", "connect", "activate"],
        "requires": ["python3"],
        "proof": ".codee/hooks.json and .codee/events.jsonl",
    },
    {
        "id": "connector-registry",
        "name": "Codee Connector Registry",
        "access": "public",
        "status": "built-in",
        "summary": "Teach which integrations are public, backend-gated, owner-gated, or planned before a user expects secrets in the CLI.",
        "commands": ["connectors", "connect", "activate"],
        "requires": ["python3"],
        "proof": ".codee/connectors.json",
    },
    {
        "id": "platform-layer",
        "name": "Codee Platform Layer",
        "access": "public",
        "status": "built-in",
        "summary": "Write tasks, run task proof, install agent profiles, memory/rules, permission policy, and MCP-style connectors into the workspace.",
        "commands": ["platform", "permissions", "agents", "memory", "mcp", "task"],
        "requires": ["python3"],
        "proof": ".codee/platform-parity.json, .codee/agents.json, .codee/permissions.json, .codee/mcp.json, .codee/tasks/, and latest-task-run.json",
    },
    {
        "id": "public-heartbeat",
        "name": "Public Heartbeat",
        "access": "public",
        "status": "built-in",
        "summary": "Give downloaded users a quick pulse of identity, folder health, task status, route proof, missing items, and next commands.",
        "commands": ["heartbeat", "doctor", "verify", "task", "scan"],
        "requires": ["python3"],
        "proof": ".codee/reports/latest-heartbeat.json and .codee/HEARTBEAT.md",
    },
    {
        "id": "governed-agent-core",
        "name": "Codee AGI Core",
        "access": "public",
        "status": "built-in",
        "summary": "Install Codee AGI as Applied Good Intelligence: science, technology, ethics, society, capital creation, mission reinvestment, and guarded agent action.",
        "commands": ["agent-core", "agi", "heartbeat", "task", "verify", "support", "accessibility"],
        "requires": ["python3"],
        "proof": ".codee/agent-core.json, .codee/AGENT_CORE.md, and .codee/UPGRADE_PATH.md",
    },
    {
        "id": "user-memory-vault",
        "name": "User Memory Vault",
        "access": "public",
        "status": "built-in",
        "summary": "Give each Codee user a local-first long-term memory vault keyed by codee_user_id with searchable notes, preferences, service history, proof, and next-step records.",
        "commands": ["memory-vault", "remember", "heartbeat", "platform", "support"],
        "requires": ["python3"],
        "proof": ".codee/user-memory.json, .codee/USER_MEMORY.md, and .codee/users/<codee_user_id>/memory/memories.jsonl",
    },
    {
        "id": "veteran-accessibility-mode",
        "name": "Veteran Accessibility Mode",
        "access": "public",
        "status": "built-in",
        "summary": "Keep Codee courses short, large, high-contrast, voice-friendly, keyboard-friendly, and proof-first for disabled veterans.",
        "commands": ["accessibility", "platform", "course-init", "heartbeat"],
        "requires": ["python3"],
        "proof": ".codee/accessibility.json and .codee/ACCESSIBILITY.md",
    },
    {
        "id": "firebase-hosting",
        "name": "Firebase Hosting Deploy",
        "access": "owner",
        "status": "owner-tool",
        "summary": "Deploy Codee-owned pages after owner authentication. Public users should not receive this credential.",
        "commands": ["owner deploy scripts"],
        "requires": ["firebase"],
        "proof": "Firebase release URL and route scan report",
    },
    {
        "id": "gcloud-run",
        "name": "Google Cloud Run Ops",
        "access": "owner",
        "status": "owner-tool",
        "summary": "Inspect and deploy backend services with owner-approved GCloud credentials.",
        "commands": ["owner backend deploy scripts"],
        "requires": ["gcloud"],
        "proof": "Cloud Run revision, health route, and backend smoke report",
    },
    {
        "id": "codeemail",
        "name": "CodeEmail / Gmail Triage",
        "access": "owner-private",
        "status": "private-connector",
        "summary": "Use private mailbox connectors for inbox triage, support notifications, and owner-only operations.",
        "commands": ["server worker", "owner inbox tools"],
        "requires": ["private OAuth or app connector"],
        "proof": "CodeEmail report or connector audit log",
    },
    {
        "id": "metricool-social",
        "name": "Metricool Social Scheduling",
        "access": "owner-private",
        "status": "private-connector",
        "summary": "Prepare and schedule approved social posts through owner-connected social accounts.",
        "commands": ["owner Metricool worker"],
        "requires": ["Metricool credentials"],
        "proof": "scheduled-post report and platform queue proof",
    },
    {
        "id": "pdf-package",
        "name": "PDF / Guidebook Packaging",
        "access": "public-optional",
        "status": "optional-workflow",
        "summary": "Package guidebooks, proof sheets, and client handoff PDFs from local files.",
        "commands": ["course-init", "support"],
        "requires": ["python3"],
        "proof": "exported folder, attachment list, and delivery-room link",
    },
]

TOOLKIT_COURSES = ("qrcodee", "codeeflyer", "codeeapp")

SERVICE_ALIASES = {
    "qr": "codeeqr",
    "qrcodee": "codeeqr",
    "codee-qr": "codeeqr",
    "codeeqr": "codeeqr",
    "flyer": "codeeflyer",
    "digiflyer": "codeeflyer",
    "codeeflyer": "codeeflyer",
    "codeeflyer100": "codeeflyer",
    "codeeflyer-100": "codeeflyer",
    "codeeflyer250": "codeeflyer250",
    "codeeflyer-250": "codeeflyer250",
    "digiapp": "codeeapp250",
    "codeeapp": "codeeapp250",
    "codeeapp250": "codeeapp250",
    "app250": "codeeapp250",
    "card": "codeecard",
    "digicard": "codeecard",
    "codeecard": "codeecard",
    "beeper": "codeebeeper",
    "vault": "codeebeeper",
    "codeevault": "codeebeeper",
    "codeebeeper": "codeebeeper",
    "mini-site": "codee-business-suite",
    "minicodeesite": "codee-business-suite",
    "business-suite": "codee-business-suite",
    "codeebusinesssuite": "codee-business-suite",
    "codee-business-suite": "codee-business-suite",
}

CODEE_SERVICE_CONTRACTS: dict[str, dict[str, Any]] = {
    "codeeqr": {
        "schema": "codee.service-contract.v1",
        "service": "codeeqr",
        "public_name": "QRCodee",
        "price_lane": "49",
        "promise": "Create one branded QR image and a hosted QR landing page that points to the client's chosen destination.",
        "required_inputs": ["business name", "client email", "destination URL", "logo or center mark", "preferred brand color"],
        "client_gets": ["custom QR image", "hosted QR landing page", "delivery room", "scan proof", "Codee support path"],
        "delivery_room_slots": ["open generated QR site", "download QR image", "pay/support status", "suggested next service"],
        "paywall_rule": "Locked preview can be generated first; final route and delivery room unlock after Stripe payment verification.",
        "accessibility_default": "Large controls, short copy, visible link buttons, and scan-test proof.",
    },
    "codeeflyer": {
        "schema": "codee.service-contract.v1",
        "service": "codeeflyer",
        "public_name": "CodeeFlyer100",
        "price_lane": "100",
        "promise": "Host one client-supplied flyer image with one CTA and a branded QR image connected to the same generated page.",
        "required_inputs": ["business name", "client email", "flyer image", "one CTA label", "one CTA URL", "logo or brand color"],
        "client_gets": ["single-image hosted flyer", "one CTA button", "custom QR image", "delivery room", "route proof"],
        "delivery_room_slots": ["open hosted flyer", "download/share QR", "CTA proof", "upgrade to CodeeFlyer250"],
        "paywall_rule": "Preview stays temporary; live hosted flyer, QR route, and delivery room stay locked until payment.",
        "accessibility_default": "Readable mobile CTA, no clutter, and proof that the button opens the intended URL.",
    },
    "codeeflyer250": {
        "schema": "codee.service-contract.v1",
        "service": "codeeflyer250",
        "public_name": "CodeeFlyer250",
        "price_lane": "250",
        "promise": "Build a custom flyer from logo plus event/offer description, add branded QR, and include up to three CTA options.",
        "required_inputs": ["business name", "client email", "logo", "event or flyer description", "up to three CTA labels", "up to three CTA URLs"],
        "client_gets": ["custom flyer request packet", "generated image prompt", "branded QR image", "hosted flyer", "72-hour delivery room", "24-hour rejection window"],
        "delivery_room_slots": ["view flyer proof", "approve or reject first proof", "open hosted flyer", "CTA proof", "revision status"],
        "paywall_rule": "Payment verifies the service request; delivery room stays the source of truth for first proof and revision timing.",
        "accessibility_default": "Short approval copy, clear approve/reject action, and no hidden delivery terms.",
    },
    "codeeapp250": {
        "schema": "codee.service-contract.v1",
        "service": "codeeapp250",
        "public_name": "CodeeApp250",
        "price_lane": "250",
        "promise": "Turn a guidebook, PDF, checklist, or digital product into an app-style hosted sales and delivery page.",
        "required_inputs": ["business name", "client email", "guidebook or PDF", "cover image", "product headline", "buyer/payment link or Stripe path"],
        "client_gets": ["hosted app-style page", "guidebook cover section", "buyer CTA", "custom QR return image", "delivery room"],
        "delivery_room_slots": ["open app page", "download or view guidebook", "buyer checkout proof", "QR proof", "support request"],
        "paywall_rule": "Service deployment and buyer delivery path unlock only after Stripe/payment verification.",
        "accessibility_default": "Large cover, short bullet text, stable buttons, and no forced long scroll.",
    },
    "codeecard": {
        "schema": "codee.service-contract.v1",
        "service": "codeecard",
        "public_name": "CodeeCard",
        "price_lane": "250",
        "promise": "Create a personal or business card site with profile, QR, booking/message path, and reusable contact proof.",
        "required_inputs": ["name or brand", "client email", "portrait or logo", "contact links", "booking or message preference"],
        "client_gets": ["CodeeCard profile", "QR/contact section", "message path", "booking room link when requested", "delivery room"],
        "delivery_room_slots": ["open card", "test message path", "test booking path", "download/share QR", "request edits"],
        "paywall_rule": "Preview can be inspected first; final card and support room unlock after payment.",
        "accessibility_default": "Tap targets stay large, contact actions stay obvious, and resume/card text stays readable.",
    },
    "codeebeeper": {
        "schema": "codee.service-contract.v1",
        "service": "codeebeeper",
        "public_name": "CodeeBeeper",
        "price_lane": "149",
        "promise": "Provide a private note and media-storage workspace with pin-gated access and simple saved threads.",
        "required_inputs": ["client email", "workspace name", "storage preference", "pin setup confirmation"],
        "client_gets": ["private beeper workspace", "note-to-self thread", "media slots", "local proof packet", "delivery room"],
        "delivery_room_slots": ["open beeper", "storage status", "pin/reset instructions", "support request"],
        "paywall_rule": "Hosted storage/support activation unlocks only after payment and owner-side storage provisioning.",
        "accessibility_default": "No-scroll tool layout where possible, simple labels, and visible save/delete state.",
    },
    "codee-business-suite": {
        "schema": "codee.service-contract.v1",
        "service": "codee-business-suite",
        "public_name": "Codee Business Suite",
        "price_lane": "2500",
        "promise": "Bundle the core Codee products into one business launch package with shell site, QR, flyers, app page, blog/card support, and monthly edit window.",
        "required_inputs": ["business name", "client email", "primary offer", "brand assets", "preferred shell type", "payment path", "launch goals"],
        "client_gets": ["multi-page shell site", "QRCodee image", "CodeeFlyer100", "CodeeFlyer250", "CodeeApp250", "CodeeCard or blog lane", "delivery room", "one video handoff"],
        "delivery_room_slots": ["open suite site", "product library", "edit requests", "video room", "WordPress/Google temporary connect if requested"],
        "paywall_rule": "Klarna/Stripe payment verification unlocks the suite work order, delivery folder, and support month.",
        "accessibility_default": "Business owner sees the site, products, edit queue, and support actions without hunting through long text.",
    },
}

SERVICE_VERIFY_RULES = {
    "codeeqr": {
        "label": "QRCodee",
        "required_uploads": ["destination URL", "logo or mark", "brand color"],
        "must_have": [
            ("index.html", "The generated landing page exists."),
            ("target_url", "A scan destination URL is present."),
            ("course_packet", "The QRCodee course packet is saved."),
            ("activation_packet", "The locked activation packet is saved."),
        ],
        "warnings": [
            ("image_asset", "Add the final logo or QR artwork before paid activation."),
            ("backend_connection", "Run codee connect before asking Codee backend to activate hosting."),
        ],
    },
    "codeeflyer": {
        "label": "CodeeFlyer100",
        "required_uploads": ["flyer image or logo", "offer/event description", "CTA link", "brand color"],
        "must_have": [
            ("index.html", "The hosted flyer page exists."),
            ("target_url", "The flyer CTA target URL is present."),
            ("course_packet", "The CodeeFlyer course packet is saved."),
            ("activation_packet", "The locked activation packet is saved."),
        ],
        "warnings": [
            ("image_asset", "Add the flyer image or logo before paid activation."),
            ("backend_connection", "Run codee connect before asking Codee backend to activate hosting."),
        ],
    },
    "codeeflyer250": {
        "label": "CodeeFlyer250",
        "required_uploads": ["logo", "event or flyer description", "two image slots", "three CTA options", "brand color"],
        "must_have": [
            ("index.html", "The premium flyer page exists."),
            ("target_url", "At least one primary CTA target is present."),
            ("activation_packet", "The locked activation packet is saved."),
        ],
        "warnings": [
            ("image_asset", "Add final flyer/logo assets before paid activation."),
            ("backend_connection", "Run codee connect before asking Codee backend to activate hosting."),
        ],
    },
    "codeeapp250": {
        "label": "CodeeApp250",
        "required_uploads": ["guidebook/PDF", "cover image", "buyer or download link", "Stripe product path"],
        "must_have": [
            ("index.html", "The guidebook app page exists."),
            ("target_url", "The buyer or download path is present."),
            ("course_packet", "The CodeeApp course packet is saved."),
            ("activation_packet", "The locked activation packet is saved."),
        ],
        "warnings": [
            ("pdf_or_image_asset", "Add the guidebook PDF/cover before paid activation."),
            ("backend_connection", "Run codee connect before asking Codee backend to activate hosting."),
        ],
    },
}

CODEE_HOOK_EVENTS = [
    {
        "event": "SessionStart",
        "purpose": "Load Codee identity, state, rules, latest proof, and service contract before a run.",
        "default_action": "log-only",
    },
    {
        "event": "PreToolUse",
        "purpose": "Check a planned local action against permission mode and sensitive-file guardrails before it runs.",
        "default_action": "policy-check",
    },
    {
        "event": "PostToolUse",
        "purpose": "Record command or file-change proof after a tool action completes.",
        "default_action": "log-only",
    },
    {
        "event": "BeforeDeploy",
        "purpose": "Create a checkpoint and require route/payment/service-contract proof before deployment.",
        "default_action": "checkpoint-and-log",
    },
    {
        "event": "AfterDeploy",
        "purpose": "Record deployed URL, revision, delivery room, and scan result after deployment.",
        "default_action": "log-only",
    },
    {
        "event": "BeforePayment",
        "purpose": "Confirm the service contract, client gets, amount, and Stripe-hosted payment path before checkout.",
        "default_action": "log-only",
    },
    {
        "event": "AfterPayment",
        "purpose": "Attach Stripe payment proof to activation, delivery room, and support state.",
        "default_action": "backend-only",
    },
    {
        "event": "PreGenerate",
        "purpose": "Record intent before Codee creates a course or client folder.",
        "default_action": "log-only",
    },
    {
        "event": "PostGenerate",
        "purpose": "Record generated files, service, and next activation steps.",
        "default_action": "log-only",
    },
    {
        "event": "PreVerify",
        "purpose": "Record readiness checks before Codee grades a folder.",
        "default_action": "log-only",
    },
    {
        "event": "PostVerify",
        "purpose": "Record pass/warn/fail status and service-specific checklist proof.",
        "default_action": "log-only",
    },
    {
        "event": "PreConnect",
        "purpose": "Record the backend connection payload fingerprint before network send.",
        "default_action": "log-only",
    },
    {
        "event": "PostConnect",
        "purpose": "Record connection ID, delivery room, workbench, and paid activation URL.",
        "default_action": "log-only",
    },
    {
        "event": "PreActivate",
        "purpose": "Record the activation request before Codee asks backend for payment-gated hosting.",
        "default_action": "log-only",
    },
    {
        "event": "PaymentRequired",
        "purpose": "Record that hosted activation remains locked until Stripe/payment and uploads are verified.",
        "default_action": "log-only",
    },
    {
        "event": "PostActivate",
        "purpose": "Record activation status and next commands.",
        "default_action": "log-only",
    },
    {
        "event": "TaskCreated",
        "purpose": "Record a Codee task thread before it is sent to the backend or worked locally.",
        "default_action": "log-only",
    },
    {
        "event": "TaskSent",
        "purpose": "Record that a task thread was handed to Codee backend for delivery-room/workbench tracking.",
        "default_action": "log-only",
    },
    {
        "event": "TaskResult",
        "purpose": "Record the local or backend result attached to the task thread.",
        "default_action": "log-only",
    },
    {
        "event": "TaskRun",
        "purpose": "Record that Codee executed local task proof checks and optionally sent the result to backend.",
        "default_action": "log-only",
    },
    {
        "event": "Heartbeat",
        "purpose": "Record a workspace pulse across identity, proof, task status, routes, and next commands.",
        "default_action": "log-only",
    },
    {
        "event": "EvalGenerated",
        "purpose": "Turn failed scans, warnings, and human feedback into a reusable improvement report.",
        "default_action": "log-only",
    },
    {
        "event": "CheckpointCreated",
        "purpose": "Record a local checkpoint before overwriting important Codee files.",
        "default_action": "log-only",
    },
    {
        "event": "AgentCoreConfigured",
        "purpose": "Record that the governed AGI-style Codee operating core was installed or refreshed.",
        "default_action": "log-only",
    },
    {
        "event": "UserMemoryUpdated",
        "purpose": "Record that a user-scoped memory vault was initialized, searched, exported, or updated.",
        "default_action": "log-only",
    },
    {
        "event": "AccessibilityConfigured",
        "purpose": "Record that veteran-first accessibility rules were installed or refreshed.",
        "default_action": "log-only",
    },
    {
        "event": "CodeeAdminConfigured",
        "purpose": "Record that the owner operating packet, entity routing, and AI K9 initiation gates were installed.",
        "default_action": "log-only",
    },
    {
        "event": "DeployComplete",
        "purpose": "Reserved for owner/backend hosted deploy proof after payment verification.",
        "default_action": "backend-only",
    },
    {
        "event": "ScanFailed",
        "purpose": "Record route or browser scan failures for repair before launch.",
        "default_action": "log-only",
    },
]

CONNECTOR_REGISTRY = [
    {
        "id": "codee-backend",
        "name": "Codee Backend",
        "status": "active",
        "public_cli": True,
        "commands": ["connect", "activate", "verify"],
        "purpose": "Bind a local folder to Codee user ID, delivery room, workbench, paid intake, and activation timeline.",
    },
    {
        "id": "stripe",
        "name": "Stripe Hosted Payments",
        "status": "backend-gated",
        "public_cli": False,
        "commands": ["pricing", "upgrade", "invoice", "license"],
        "purpose": "Keep card data outside the CLI and unlock hosted service only after payment verification.",
    },
    {
        "id": "firebase-hosting",
        "name": "Firebase Hosting",
        "status": "owner-gated",
        "public_cli": False,
        "commands": ["owner deploy scripts"],
        "purpose": "Host public static pages and delivery room shells after Codee fulfillment approves deploy.",
    },
    {
        "id": "cloud-run",
        "name": "Google Cloud Run",
        "status": "owner-gated",
        "public_cli": False,
        "commands": ["owner backend deploy scripts"],
        "purpose": "Run dynamic API, webhook, QR generation, scan, and fulfillment logic.",
    },
    {
        "id": "cloud-storage",
        "name": "Google Cloud Storage",
        "status": "backend-gated",
        "public_cli": False,
        "commands": ["support", "activate"],
        "purpose": "Store uploaded logos, guidebooks, screenshots, generated assets, and fulfillment proof.",
    },
    {
        "id": "wordpress",
        "name": "WordPress Draft Connector",
        "status": "guided-one-time-connect",
        "public_cli": True,
        "commands": ["client", "connect", "support"],
        "purpose": "Optional client-authorized connection for WordPress draft help when the client does not want a Codee-hosted MiniCodeeSite.",
        "client_needs": ["WordPress site URL", "WordPress username", "Application Password created inside WordPress", "permission to draft, not publish"],
        "guardrail": "Do not save WordPress passwords in the public CLI. Use the secure browser handoff or backend support request.",
    },
    {
        "id": "google-suite",
        "name": "Google Drive and Gmail Connect",
        "status": "guided-temporary-oauth",
        "public_cli": True,
        "commands": ["client", "connect", "support"],
        "purpose": "Temporary client-authorized Gmail/Drive help for veterans with full inboxes, cluttered Drive folders, or launch assets in Google.",
        "client_needs": ["Google account owner approval", "Drive folder or Gmail query", "cleanup goal", "temporary OAuth reconnect when needed"],
        "guardrail": "Use OAuth/browser authorization. Do not paste Gmail passwords or Google recovery codes into the CLI.",
    },
    {
        "id": "metricool",
        "name": "Metricool Social Scheduling",
        "status": "owner-private",
        "public_cli": False,
        "commands": ["owner Metricool worker"],
        "purpose": "Schedule approved campaign posts from Codee-owned social operations.",
    },
]

CODEE_PERMISSION_MODES = [
    {
        "id": "suggest",
        "label": "Suggest",
        "default": True,
        "file_reads": "allowed",
        "file_writes": "approval-required",
        "shell": "approval-required",
        "network": "backend-only",
        "payment": "stripe-hosted-only",
        "best_for": "Learning, reviewing a client folder, and safe first-lane QRCodee training.",
    },
    {
        "id": "auto-edit",
        "label": "Auto Edit",
        "default": False,
        "file_reads": "allowed",
        "file_writes": "workspace-only",
        "shell": "approval-required",
        "network": "backend-only",
        "payment": "stripe-hosted-only",
        "best_for": "Repeated local edits inside a known Codee workspace.",
    },
    {
        "id": "support-auto",
        "label": "Support Auto",
        "default": False,
        "file_reads": "allowed",
        "file_writes": "workspace-and-codee-reports",
        "shell": "scan-commands-only",
        "network": "codee-api-only",
        "payment": "stripe-hosted-only",
        "best_for": "Paid support windows where Codee can verify routes and prepare update packets.",
    },
    {
        "id": "owner-full",
        "label": "Owner Full",
        "default": False,
        "file_reads": "allowed",
        "file_writes": "owner-approved",
        "shell": "owner-approved",
        "network": "owner-approved",
        "payment": "owner-backend-only",
        "best_for": "AI K9 owner operations, deploys, scans, and backend maintenance.",
    },
]

CODEE_PERMISSION_MODES.extend(
    [
        {
            "id": "read-only",
            "label": "Read Only",
            "default": False,
            "file_reads": "allowed",
            "file_writes": "blocked-except-reports",
            "shell": "blocked",
            "network": "route-check-only",
            "payment": "blocked",
            "best_for": "A new user inspecting a folder before trusting Codee with changes.",
        },
        {
            "id": "workspace",
            "label": "Workspace",
            "default": False,
            "file_reads": "allowed",
            "file_writes": "workspace-only-with-checkpoints",
            "shell": "scan-and-proof-commands",
            "network": "codee-api-and-route-checks",
            "payment": "stripe-hosted-only",
            "best_for": "Normal client folder work where Codee can create files and proof inside the workspace.",
        },
        {
            "id": "business-deploy",
            "label": "Business Deploy",
            "default": False,
            "file_reads": "allowed",
            "file_writes": "workspace-and-delivery-artifacts",
            "shell": "approved-deploy-scripts-only",
            "network": "codee-backend-hosting-and-stripe",
            "payment": "stripe-hosted-required",
            "best_for": "Paid service activation where deploys, delivery room updates, and scans must be checkpointed.",
        },
        {
            "id": "admin",
            "label": "Admin",
            "default": False,
            "file_reads": "owner-approved",
            "file_writes": "owner-approved-with-checkpoints",
            "shell": "owner-approved",
            "network": "owner-approved",
            "payment": "owner-backend-only",
            "best_for": "AI K9 owner operations across backend, hosting, storage, Stripe, and social workflows.",
        },
    ]
)

CODEE_TOOL_REGISTRY = {
    "schema": "codee.tool-registry.v1",
    "version": VERSION,
    "updated_at": "2026-05-27",
    "purpose": "Public registry for Codee CLI tools, service lanes, connectors, permission profiles, hooks, and proof reports.",
    "install": {
        "download_url": CODEE_DOWNLOAD_URL,
        "upgrade_command": "python3 codee.py self-update . --write",
        "safe_install_rule": "Download only from clients.codee.chat or the trusted Codee release page.",
    },
    "commands": [
        {"name": "install", "kind": "local", "purpose": "Write a local launcher script and workspace install notes."},
        {"name": "self-update", "kind": "network", "purpose": "Fetch the latest public Codee CLI file and replace a local copy with a checkpoint."},
        {"name": "login", "kind": "identity", "purpose": "Bind the folder to a Codee user ID and account email without storing passwords."},
        {"name": "permissions", "kind": "policy", "purpose": "Write read-only, workspace, business-deploy, or admin permission policy."},
        {"name": "hooks", "kind": "policy", "purpose": "Write lifecycle hook events and safe event logging rules."},
        {"name": "heartbeat", "kind": "proof", "purpose": "Check folder health, routes, state, delivery room, checkout links, and next commands."},
        {"name": "checkpoint", "kind": "proof", "purpose": "Snapshot important workspace files before risky edits or deploys."},
        {"name": "doctor", "kind": "proof", "purpose": "Check local tools, sensitive files, manifests, state, and public routes."},
        {"name": "test lane", "kind": "proof", "purpose": "Run verify, route checks, and eval output for one service lane."},
        {"name": "preview", "kind": "client", "purpose": "Create or submit a locked 10-minute-style preview before payment activation."},
        {"name": "activate", "kind": "client", "purpose": "Ask backend for payment-gated hosted activation."},
        {"name": "delivery", "kind": "client", "purpose": "Open or print the returnable Codee delivery room."},
        {"name": "eval", "kind": "improvement", "purpose": "Convert failed proof reports into ranked repair recommendations."},
        {"name": "launch", "kind": "platform", "purpose": "Write the 20-move public launch, onboarding, dashboard, proof, policy, case-study, and valuation packet."},
        {"name": "saas", "kind": "platform", "purpose": "Show or write the light SaaS manifest and 20-move operating map."},
        {"name": "portal", "kind": "client", "purpose": "Open or print the customer portal URL for one Codee workspace."},
        {"name": "entitlements", "kind": "billing", "purpose": "Show what each plan unlocks before preview, activation, or support."},
        {"name": "starter", "kind": "workspace", "purpose": "Create a one-command starter workspace for a business type and service lane."},
        {"name": "remote", "kind": "pro", "purpose": "Plan viewer, CLI bridge, pairing, and status for Codee Remote workspaces."},
        {"name": "company", "kind": "alignment", "purpose": "Write company alignment, IP, investor, and impact packets for a Codee workspace."},
        {"name": "codeeadmin", "kind": "owner", "purpose": "Write the owner operating packet, entity routing, daily proof loop, and AI K9 initiation gates."},
        {"name": "codeecpa", "kind": "governance", "purpose": "Write a guarded legal/tax/CPA consultation-prep packet and professional-review SOP."},
    ],
    "service_lanes": list(CODEE_SERVICE_CONTRACTS.keys()),
    "permission_modes": [str(item["id"]) for item in CODEE_PERMISSION_MODES],
    "hook_events": [str(item["event"]) for item in CODEE_HOOK_EVENTS],
    "connectors": [str(item["id"]) for item in CONNECTOR_REGISTRY],
    "platform_moves": CODEE_PLATFORM_20_MOVES,
    "light_saas_moves": [
        "account-system",
        "release-channels",
        "upgrade-banner",
        "customer-portal",
        "delivery-dashboard",
        "service-entitlements",
        "preview-paywall",
        "business-template-library",
        "chat-cli-sync",
        "workspace-command-center",
        "lane-smoke-automation",
        "stripe-plan-layer",
        "partner-trainee-mode",
        "course-certificates",
        "public-proof-wall",
        "one-command-starter",
        "safe-connectors",
        "daily-saas-health-loop",
        "admin-training-webapp",
        "public-positioning-page",
    ],
    "public_pages": {
        "launch": CODEE_LAUNCH_URL,
        "launch_checklist": CODEE_LAUNCH_CHECKLIST_URL,
        "onboarding": CODEE_ONBOARDING_URL,
        "saas": CODEE_SAAS_URL,
        "portal": CODEE_PORTAL_URL,
        "proof_wall": CODEE_PROOF_WALL_URL,
        "codeeadmin": CODEEADMIN_URL,
        "codeeadmin_daily": CODEEADMIN_DAILY_DIGEST_URL,
        "codeeadmin_states": CODEEADMIN_STATES_URL,
        "codeeadmin_state_packet": CODEEADMIN_STATE_PACKET_URL,
        "codeeadmin_next20": CODEEADMIN_NEXT20_URL,
        "landee_mission_packet": LANDEE_MISSION_PACKET_URL,
        "remote": CODEE_REMOTE_URL,
        "remote_viewer": CODEE_REMOTE_VIEWER_URL,
        "remote_cli": CODEE_REMOTE_CLI_URL,
        "remote_installer": CODEE_REMOTE_INSTALLER_URL,
        "remote_demo": CODEE_REMOTE_DEMO_URL,
        "remote_security": CODEE_REMOTE_SECURITY_URL,
        "company_alignment": CODEE_COMPANY_ALIGNMENT_URL,
        "ip_register": CODEE_IP_REGISTER_URL,
        "investor_readiness": CODEE_INVESTOR_READINESS_URL,
        "impact_model": CODEE_IMPACT_MODEL_URL,
        "business_with_a_mission": CODEE_BUSINESS_MISSION_URL,
        "impact_report_template": CODEE_IMPACT_REPORT_TEMPLATE_URL,
        "agent_investment_model": CODEE_AGENT_INVESTMENT_MODEL_URL,
        "data_room_checklist": CODEE_DATA_ROOM_CHECKLIST_URL,
        "codeecpa": CODEE_CPA_URL,
        "codeecpa_workspace": CODEE_CPA_WORKSPACE_URL,
        "company_alignment_json": CODEE_COMPANY_ALIGNMENT_JSON_URL,
        "codeeadmin_daily_digest": CODEEADMIN_DAILY_DIGEST_MANIFEST_URL,
        "codeeadmin_state_playbook": CODEEADMIN_STATES_MANIFEST_URL,
        "codeeadmin_state_packets": CODEEADMIN_STATE_PACKET_MANIFEST_URL,
        "codeeadmin_next20_manifest": CODEEADMIN_NEXT20_MANIFEST_URL,
        "landee_mission_manifest": LANDEE_MISSION_PACKET_MANIFEST_URL,
        "cli": f"{DEFAULT_API_BASE}/codee-cli.html",
        "download": CODEE_DOWNLOAD_URL,
    },
    "saas_manifest_url": CODEE_SAAS_MANIFEST_URL,
    "codeeadmin_manifest_url": CODEEADMIN_MANIFEST_URL,
    "codeeadmin_daily_digest_url": CODEEADMIN_DAILY_DIGEST_MANIFEST_URL,
    "codeeadmin_state_playbook_url": CODEEADMIN_STATES_MANIFEST_URL,
    "codeeadmin_state_packets_url": CODEEADMIN_STATE_PACKET_MANIFEST_URL,
    "codeeadmin_next20_url": CODEEADMIN_NEXT20_MANIFEST_URL,
    "landee_mission_packet_url": LANDEE_MISSION_PACKET_MANIFEST_URL,
    "remote_manifest_url": CODEE_REMOTE_MANIFEST_URL,
    "remote_host_download_url": CODEE_REMOTE_HOST_DOWNLOAD_URL,
    "remote_moves": [str(item["id"]) for item in CODEE_REMOTE_20_MOVES],
}

CODEE_RELEASE_DISCIPLINE = {
    "schema": "codee.release.v1",
    "version": VERSION,
    "channel": "public-cli",
    "updated_at": "2026-05-27",
    "status": "light-saas-foundation",
    "channels": [
        {"id": "canary", "audience": "owner and internal AI K9 tests", "rule": "First release target for risky changes."},
        {"id": "beta", "audience": "trusted partners and training testers", "rule": "Use after canary proof passes."},
        {"id": "stable", "audience": "public customers and trainees", "rule": "Default public upgrade channel."},
    ],
    "upgrade_model": {
        "check_command": "python3 codee.py doctor .",
        "upgrade_command": "python3 codee.py self-update . --write",
        "checkpoint_rule": "Save the current CLI before replacing it.",
        "minimum_version_rule": "Only block old clients for urgent backend or safety fixes.",
    },
    "changelog": [
        "Added CodeeAdmin Next 20 execution board: public page, manifest, CLI writes, daily digest links, doctor routes, and route-loop proof targets.",
        "Added CodeeAdmin state-by-state v2: per-state packet pages, readiness stages, official-source checklists, AI K9 action rooms, and generated state-packet indexes.",
        "Turned the 20-move launch packet and CODEECPA professional-review packet into live browser workspaces with local progress, notes, exports, and proof-wall routes.",
        "Added the 20-move public launch packet and launch command: launch page, onboarding, preview paywall, user IDs, dashboard, doctor explainer, demo scripts, veteran path, Business Suite, billing portal prep, release channels, remote CLI, data room, policies, case studies, weekly proof, partner mission, and valuation metrics.",
        "Added CODEECPA as a guarded legal/tax/CPA consultation-prep packet with source links, review lanes, red flags, professional question lists, and live-CPA SOP training surfaces.",
        "Expanded Codee company admin packets with data room, governance, trade-secret, contributor, nonprofit license prep, monthly impact report, case study, and investor scorecard outputs.",
        "Added the Codee company alignment layer: public alignment page, IP register, investor readiness scorecard, impact model, JSON manifest, and CLI company command.",
        "Added the Codee Remote 20-move foundation: host skeleton, installer, demo mode, security gate, readiness, audit, session, and revoke command surfaces.",
        "Added light SaaS public page, customer portal, proof wall, SaaS manifest, entitlements, and starter workspace command.",
        "Added Codee Remote Viewer and Remote CLI bridge planning surfaces, manifests, and command packets.",
        "Added veteran founder agent investment model so Codee can show the path from training to proof-backed company packet.",
        "Added install, self-update, login, registry, checkpoint, eval, preview, and lane-test command surfaces.",
        "Added Codex/Claude-inspired permission modes, hook events, state.json, sensitive-file guardrails, and doctor checks.",
        "Kept payment, hosting, storage, and third-party credential operations behind backend or owner-gated flows.",
    ],
    "known_limits": [
        "The public CLI is not a bundled local model; it is a business workflow client connected to Codee backend when requested.",
        "Stripe payment completion still requires a real hosted checkout or invoice flow.",
        "Owner deploy, GCloud, Metricool, Gmail, and storage credentials are not shipped to public downloads.",
    ],
    "release_gate": [
        "py_compile passes",
        "doctor passes for a generated workspace",
        "lane-test passes locally",
        "launch, launch checklist, onboarding, SaaS, remote viewer, remote CLI bridge, remote installer, remote demo, remote security, customer portal, and proof wall return 200",
        "remote readiness passes for generated workspace",
        "404 loop passes public routes after deploy",
        "company alignment, IP register, investor readiness, agent investment model, impact model, and alignment JSON return 200",
        "business-with-a-mission, impact-report-template, data-room-checklist, CODEECPA, and CODEECPA workspace routes return 200",
        "CodeeAdmin Next 20 page and JSON manifest return 200 and appear in doctor, SaaS manifest, and route-loop proof",
    ],
}

CODEE_LIGHT_SAAS_20_MOVES = CODEE_PUBLIC_LAUNCH_20_MOVES

CODEE_SAAS_ENTITLEMENTS = {
    "free-trainee": {
        "name": "Mission Training Access",
        "audience": "homeless and disabled veterans first",
        "billing": "sponsored or free when approved by the mission lane",
        "unlocks": ["courses", "starter workspaces", "local proof reports", "accessibility mode", "memory vault"],
        "limits": ["local-first output", "paid hosting and done-for-you deploy stay locked until approved or sponsored"],
    },
    "pro": {
        "name": "Codee CLI Pro",
        "audience": "public creator, operator, or small business owner",
        "billing": "$29/mo optional support and hosting path",
        "unlocks": ["customer portal", "one active workspace", "route scans", "support packets", "upgrade checks", "delivery room links"],
        "limits": ["owner-gated cloud deploy credentials are not shipped", "Stripe payments stay hosted by Stripe"],
    },
    "partner": {
        "name": "AI K9 Partner",
        "audience": "builder helping multiple local businesses",
        "billing": "$99/mo partner support path",
        "unlocks": ["multi-client folders", "business-type assistants", "proof wall submissions", "support queue packets", "template starter kits"],
        "limits": ["client payment activation still requires client-specific Stripe or Codee checkout proof"],
    },
    "business-suite": {
        "name": "Codee Business Suite",
        "audience": "business buying the full launch bundle",
        "billing": "$2,500 package plus optional hosting/support",
        "unlocks": ["QRCodee", "CodeeFlyer100", "CodeeFlyer250", "CodeeApp250", "CodeeCard or CodeeBlog", "shell site", "video handoff", "30-day edit window"],
        "limits": ["suite work order starts after Stripe/Klarna payment verification and required assets"],
    },
    "owner-admin": {
        "name": "Owner Admin",
        "audience": "AI K9 / Invest In Vets operator",
        "billing": "internal",
        "unlocks": ["canary release", "admin certification", "route loop", "backend smoke proof", "deployment checklist", "public proof wall"],
        "limits": ["external posting, payments, email sends, and destructive cleanup still require owner review"],
    },
}

CODEE_STARTER_PACKS = {
    "qrcodee": {"course": "qrcodee", "service": "codeeqr", "business_type": "local-service", "first_file": "index.html"},
    "flyer": {"course": "codeeflyer", "service": "codeeflyer", "business_type": "event", "first_file": "index.html"},
    "app": {"course": "codeeapp", "service": "codeeapp250", "business_type": "creator", "first_file": "index.html"},
    "restaurant": {"course": "qrcodee", "service": "codeeqr", "business_type": "restaurant", "first_file": "index.html"},
    "contractor": {"course": "codeeflyer", "service": "codeeflyer", "business_type": "contractor", "first_file": "index.html"},
    "nonprofit": {"course": "codeeapp", "service": "codeeapp250", "business_type": "nonprofit", "first_file": "index.html"},
    "business-suite": {"course": "qrcodee", "service": "codee-business-suite", "business_type": "local-service", "first_file": "index.html"},
}

CODEE_SAAS_MANIFEST = {
    "schema": "codee.light-saas.v1",
    "version": VERSION,
    "updated_at": "2026-05-27",
    "positioning": "Codee turns one folder, one index file, and one business idea into a proof-backed offer, with paid hosting and support unlocked only when needed.",
    "public_pages": {
        "launch": CODEE_LAUNCH_URL,
        "launch_checklist": CODEE_LAUNCH_CHECKLIST_URL,
        "onboarding": CODEE_ONBOARDING_URL,
        "saas": CODEE_SAAS_URL,
        "portal": CODEE_PORTAL_URL,
        "proof_wall": CODEE_PROOF_WALL_URL,
        "codeeadmin": CODEEADMIN_URL,
        "codeeadmin_daily": CODEEADMIN_DAILY_DIGEST_URL,
        "codeeadmin_states": CODEEADMIN_STATES_URL,
        "codeeadmin_state_packet": CODEEADMIN_STATE_PACKET_URL,
        "codeeadmin_next20": CODEEADMIN_NEXT20_URL,
        "landee_mission_packet": LANDEE_MISSION_PACKET_URL,
        "remote": CODEE_REMOTE_URL,
        "remote_viewer": CODEE_REMOTE_VIEWER_URL,
        "remote_cli": CODEE_REMOTE_CLI_URL,
        "remote_installer": CODEE_REMOTE_INSTALLER_URL,
        "remote_demo": CODEE_REMOTE_DEMO_URL,
        "remote_security": CODEE_REMOTE_SECURITY_URL,
        "company_alignment": CODEE_COMPANY_ALIGNMENT_URL,
        "ip_register": CODEE_IP_REGISTER_URL,
        "investor_readiness": CODEE_INVESTOR_READINESS_URL,
        "impact_model": CODEE_IMPACT_MODEL_URL,
        "business_with_a_mission": CODEE_BUSINESS_MISSION_URL,
        "impact_report_template": CODEE_IMPACT_REPORT_TEMPLATE_URL,
        "agent_investment_model": CODEE_AGENT_INVESTMENT_MODEL_URL,
        "data_room_checklist": CODEE_DATA_ROOM_CHECKLIST_URL,
        "codeecpa": CODEE_CPA_URL,
        "codeecpa_workspace": CODEE_CPA_WORKSPACE_URL,
        "company_alignment_json": CODEE_COMPANY_ALIGNMENT_JSON_URL,
        "codeeadmin_manifest": CODEEADMIN_MANIFEST_URL,
        "codeeadmin_daily_digest": CODEEADMIN_DAILY_DIGEST_MANIFEST_URL,
        "codeeadmin_state_playbook": CODEEADMIN_STATES_MANIFEST_URL,
        "codeeadmin_state_packets": CODEEADMIN_STATE_PACKET_MANIFEST_URL,
        "codeeadmin_next20_manifest": CODEEADMIN_NEXT20_MANIFEST_URL,
        "landee_mission_manifest": LANDEE_MISSION_PACKET_MANIFEST_URL,
        "cli": f"{DEFAULT_API_BASE}/codee-cli.html",
        "download": CODEE_DOWNLOAD_URL,
    },
    "core_loop": ["intake", "starter", "preview", "proof", "paywall", "activate", "delivery_room", "support", "upgrade"],
    "admin_loop": CODEEADMIN_MODEL["daily_operating_loop"],
    "launch_loop": [str(item["id"]) for item in CODEE_PUBLIC_LAUNCH_20_MOVES],
    "governance_extension": {"name": "CODEECPA", "public_page": CODEE_CPA_URL, "workspace_page": CODEE_CPA_WORKSPACE_URL, "command": "python3 codee.py codeecpa . --write --force", "rule": "Preparation only; licensed review remains required."},
    "workspace_surfaces": {
        "launch_checklist": CODEE_LAUNCH_CHECKLIST_URL,
        "codeecpa_workspace": CODEE_CPA_WORKSPACE_URL,
        "rule": "Packets become browser-local checklists first; export JSON before investor, CPA, or data-room review.",
    },
    "company_alignment": {
        "mission_umbrella": "Invest In Vets Foundation",
        "technology_company": "AI K9 Kennel",
        "platform": "Codee",
        "rule": "Keep nonprofit mission, technology operations, customer payments, and impact reporting clear and written.",
        "veteran_founder_rule": "Each veteran founder should create one Codee agent, one service lane, one proof packet, and one advisor-reviewed growth plan before claiming investability.",
    },
    "codeeadmin": CODEEADMIN_MODEL,
    "entitlements": CODEE_SAAS_ENTITLEMENTS,
    "starter_packs": CODEE_STARTER_PACKS,
    "platform_moves": CODEE_LIGHT_SAAS_20_MOVES,
    "release": {"channels": ["canary", "beta", "stable"], "upgrade_command": "python3 codee.py self-update . --write"},
    "remote": {
        "public_page": CODEE_REMOTE_URL,
        "viewer_page": CODEE_REMOTE_VIEWER_URL,
        "cli_bridge_page": CODEE_REMOTE_CLI_URL,
        "installer_page": CODEE_REMOTE_INSTALLER_URL,
        "demo_page": CODEE_REMOTE_DEMO_URL,
        "security_page": CODEE_REMOTE_SECURITY_URL,
        "manifest": CODEE_REMOTE_MANIFEST_URL,
        "host_download": CODEE_REMOTE_HOST_DOWNLOAD_URL,
        "first_phase": "desktop-viewer-mvp",
        "parallel_phase": "remote-cli-bridge",
    },
}

CODEE_REMOTE_ARCHITECTURE = {
    "schema": "codee.remote.v1",
    "version": VERSION,
    "updated_at": "2026-05-27",
    "positioning": "Codee Remote has two tracks: a phone-to-desktop viewer for seeing and controlling the user's own computer, and a Remote CLI bridge for sending safe Codee commands without screen control.",
    "public_page": CODEE_REMOTE_URL,
    "viewer_page": CODEE_REMOTE_VIEWER_URL,
    "cli_bridge_page": CODEE_REMOTE_CLI_URL,
    "installer_page": CODEE_REMOTE_INSTALLER_URL,
    "demo_page": CODEE_REMOTE_DEMO_URL,
    "security_page": CODEE_REMOTE_SECURITY_URL,
    "manifest_url": CODEE_REMOTE_MANIFEST_URL,
    "host_download_url": CODEE_REMOTE_HOST_DOWNLOAD_URL,
    "entitlement_required": ["pro", "partner", "business-suite", "owner-admin"],
    "moves": CODEE_REMOTE_20_MOVES,
    "phases": [
        {
            "id": "desktop-viewer-mvp",
            "status": "foundation",
            "summary": "Phone opens a viewer page, pairs with the user's own desktop host, and receives a user-approved screen stream.",
            "components": ["PWA viewer", "desktop host agent", "pairing code", "WebRTC signaling", "TURN relay", "visible consent banner", "session revoke"],
        },
        {
            "id": "remote-cli-bridge",
            "status": "foundation",
            "summary": "Phone or browser sends allowlisted Codee CLI jobs to the paired desktop agent. Output returns to the portal.",
            "components": ["PWA command panel", "Codee backend command queue", "desktop host agent", "allowlisted CLI runner", "audit log"],
        },
        {
            "id": "desktop-remote",
            "status": "future-pro",
            "summary": "Chrome Remote Desktop style full remote control for trusted pro workspaces after code signing, MFA, and audit controls.",
            "components": ["native host", "mobile web client", "device registry", "MFA/passkey", "policy engine", "emergency lock"],
        },
    ],
    "gcloud_components": ["Cloud Run API", "Firestore or Cloud SQL session store", "Pub/Sub command queue", "Cloud Storage proof artifacts", "Secret Manager", "Firebase Hosting PWA"],
    "specialized_components": ["TURN relay on Compute Engine or managed TURN", "native host app for macOS/Windows", "code signing and notarization"],
    "viewer_capabilities": ["phone browser viewer", "pairing code", "visible consent", "screen stream", "touch/mouse input after approval", "emergency stop"],
    "cli_bridge_capabilities": ["doctor", "heartbeat", "scan", "portal", "support", "test lane", "preview dry-run"],
    "security_gate": CODEE_REMOTE_SECURITY_GATE,
    "security_rules": [
        "No unattended full desktop control until the device owner explicitly enables it.",
        "The viewer requires visible consent, a live session banner, and a user-controlled stop button.",
        "Remote CLI bridge starts with allowlisted Codee commands only.",
        "Pairing codes expire quickly and can be revoked from the portal.",
        "Every command writes an audit event and proof report.",
        "No Stripe secret keys, OAuth refresh tokens, or owner deploy credentials are shipped to public clients.",
        "Full remote desktop requires MFA/passkey, visible session indicator, and emergency stop.",
    ],
    "first_commands": [
        "python3 codee.py remote plan . --write --force",
        "python3 codee.py remote installer . --write --force",
        "python3 codee.py remote host . --write --force",
        "python3 codee.py remote viewer . --write --force",
        "python3 codee.py remote bridge . --write --force",
        "python3 codee.py remote pair . --device-name \"Mac Studio\" --write",
        "python3 codee.py remote security . --write --force",
        "python3 codee.py remote readiness . --write --force",
        "python3 codee.py portal . --service codeeqr --plan pro",
    ],
}

CODEE_AGENT_PROFILES = [
    {
        "id": "explorer",
        "name": "Codee Explorer",
        "description": "Read-heavy folder and lane exploration before edits.",
        "permission_mode": "suggest",
        "tools": ["folder_inventory", "routes", "skills", "connectors", "memory"],
        "outputs": [".codee/reports/latest-explore.json", ".codee/tasks/"],
    },
    {
        "id": "builder",
        "name": "Codee Builder",
        "description": "Create or update QRCodee, CodeeFlyer, CodeeApp, and business-suite files inside the workspace.",
        "permission_mode": "auto-edit",
        "tools": ["course-init", "folder-plan", "verify", "hooks", "connectors"],
        "outputs": ["index.html", "assets/", ".codee/reports/latest-codee-verify.json"],
    },
    {
        "id": "auditor",
        "name": "Codee Auditor",
        "description": "Run route, browser, payment-gate, and delivery-room checks before launch.",
        "permission_mode": "support-auto",
        "tools": ["verify", "scan", "browser-scan", "course-smoke", "license"],
        "outputs": [".codee/reports/", ".codee/screenshots/"],
    },
    {
        "id": "launch-operator",
        "name": "Codee Launch Operator",
        "description": "Package the offer, support request, delivery room, and paid activation path.",
        "permission_mode": "support-auto",
        "tools": ["money-map", "connect", "activate", "support", "room", "workbench"],
        "outputs": [".codee/backend-connection.json", ".codee/support-requests/"],
    },
    {
        "id": "owner-ops",
        "name": "Codee Owner Ops",
        "description": "Owner-only backend, deploy, storage, Metricool, and fulfillment operations.",
        "permission_mode": "owner-full",
        "tools": ["owner-deploy", "stripe-webhooks", "gcloud-storage", "metricool", "firestore"],
        "outputs": ["Cloud Run revision", "Firebase release", "owner proof report"],
    },
]

CODEE_AGENT_CORE_LOOP = [
    {
        "step": "observe",
        "purpose": "Read the folder, manifest, service lane, task thread, latest reports, and route status before giving advice.",
        "commands": ["heartbeat", "doctor", "account", "memory-vault search", "scan"],
    },
    {
        "step": "understand_goal",
        "purpose": "Translate the user request into one business outcome, one service lane, and one acceptance checklist.",
        "commands": ["money-map", "task create", "folder-plan"],
    },
    {
        "step": "plan",
        "purpose": "Pick the next smallest shippable action and name the required tools, files, approvals, and proof.",
        "commands": ["platform", "agents", "permissions", "memory"],
    },
    {
        "step": "act",
        "purpose": "Create or update files only inside the intended workspace and keep payment/deploy work behind backend gates.",
        "commands": ["course-init", "task run", "support"],
    },
    {
        "step": "verify",
        "purpose": "Check that the folder, route, CTA, delivery room, and backend proof match what the client paid for.",
        "commands": ["verify", "scan", "browser-scan", "course-smoke"],
    },
    {
        "step": "report",
        "purpose": "Write a reusable report so the next person or AI can resume without guessing.",
        "commands": ["heartbeat", "task result", "memory-vault add", "room", "workbench"],
    },
    {
        "step": "recommend",
        "purpose": "Give the user the next best command instead of leaving them stuck after a download.",
        "commands": ["heartbeat", "support", "upgrade", "pricing"],
    },
]

CODEE_AGENT_CORE_TOOLS = [
    {
        "tool": "heartbeat",
        "why": "Gives the user a fast pulse of identity, folder health, routes, tasks, proof, and next commands.",
        "public": True,
    },
    {
        "tool": "task",
        "why": "Turns every request into a traceable thread with acceptance criteria and backend result proof.",
        "public": True,
    },
    {
        "tool": "verify",
        "why": "Stops Codee from calling a lane ready until the expected service files and route proof exist.",
        "public": True,
    },
    {
        "tool": "scan and browser-scan",
        "why": "Catches 404s and route failures before a client or trainee sees them.",
        "public": True,
    },
    {
        "tool": "money-map",
        "why": "Connects the folder to audience, offer, CTA, payment, delivery, and proof.",
        "public": True,
    },
    {
        "tool": "platform",
        "why": "Installs agents, memory, permission policy, hooks, connector maps, and task folders.",
        "public": True,
    },
    {
        "tool": "memory-vault",
        "why": "Stores each user's preferences, lane history, tasks, proof, support notes, and next steps in a searchable local vault.",
        "public": True,
    },
    {
        "tool": "support",
        "why": "Creates a clear update packet instead of making the user explain the whole folder again.",
        "public": True,
    },
    {
        "tool": "connect and activate",
        "why": "Lets the public CLI connect to Codee backend while paid hosting stays locked behind verified payment.",
        "public": True,
    },
    {
        "tool": "upgrade, invoice, license",
        "why": "Moves paid support into Stripe-hosted checkout or invoice flows without storing card data in the CLI.",
        "public": True,
    },
    {
        "tool": "owner loops",
        "why": "Keeps Cloud Run, Firebase, GCS, Stripe webhooks, Metricool, and fulfillment under owner-approved access.",
        "public": False,
    },
]

CODEE_AGI_DOCTRINE = {
    "label": "Codee AGI",
    "meaning": "Applied Good Intelligence",
    "plain_language": "Codee AGI is the mission operating system: use science, technology, ethics, and society to help undercapitalized people create useful business tools, then reinvest the gains into Invest In Vets.",
    "domains": [
        "science: measure what works, run proof checks, and improve from evidence",
        "technology: turn folders, QR paths, flyers, apps, blogs, cards, payments, and delivery rooms into working tools",
        "ethics: protect users, avoid false promises, keep payment and credential gates safe",
        "society: prioritize homeless and disabled veterans, small businesses, and people blocked by access barriers",
        "capital: help people create income lanes and route mission profit back into Invest In Vets",
    ],
    "mission_rule": "Capital created by Codee should support the operator, the client, and the Invest In Vets mission instead of becoming extraction-only technology.",
    "public_claim": "Codee AGI means Applied Good Intelligence. It does not claim unrestricted human-level artificial general intelligence.",
}

CODEE_ACCESSIBILITY_DEFAULTS = {
    "schema": "codee.accessibility-defaults.v1",
    "principle": "Short text, big controls, proof-first steps, and voice-friendly wording for disabled veteran learners.",
    "course_rules": [
        "Keep each course screen focused on one action.",
        "Use short sentences and bullet lists instead of dense paragraphs.",
        "Prefer 3 or 4 steps per lesson.",
        "Make buttons at least 44px tall.",
        "Use high contrast and avoid tiny text.",
        "Make every proof step readable aloud.",
        "Do not hide the paid option, but teach the free veteran path first.",
    ],
    "default_copy": {
        "hero": "Pick one lane. Build it. Prove it. Then decide whether to host it.",
        "mission": "Veterans first. Public clients fund the mission.",
        "proof": "A lesson is complete when the route opens, the action works, and the proof is saved.",
    },
}

CODEE_MCP_BLUEPRINTS = [
    {
        "id": "codee-backend-http",
        "name": "Codee Backend HTTP",
        "transport": "streamable-http",
        "url": f"{DEFAULT_API_BASE}/api/codee/cli",
        "auth": "codee-user-id plus backend activation token when available",
        "public_cli": True,
        "tools": ["connect", "activate", "timeline", "connectors", "tasks"],
    },
    {
        "id": "playwright-local",
        "name": "Playwright Local Browser",
        "transport": "local-command",
        "url": "",
        "auth": "none",
        "public_cli": True,
        "tools": ["browser-scan", "screenshot", "mobile-proof"],
    },
    {
        "id": "stripe-backend",
        "name": "Stripe Hosted Payments",
        "transport": "backend-only",
        "url": f"{DEFAULT_API_BASE}/api/stripe/codee-cli",
        "auth": "server-side Stripe secret only",
        "public_cli": False,
        "tools": ["pricing", "checkout", "invoice", "license"],
    },
    {
        "id": "gcloud-owner",
        "name": "GCloud Owner Deploy",
        "transport": "owner-command",
        "url": "",
        "auth": "owner gcloud account",
        "public_cli": False,
        "tools": ["cloud-run", "cloud-storage", "firebase-hosting"],
    },
]

CODEE_PLATFORM_GAPS = [
    {
        "feature": "Task threads",
        "inspiration": "Codex cloud tasks and Claude subagent task events.",
        "codee_status": "built-in-local-plus-backend",
        "command": "python3 codee.py task create . --title \"Make my QRCodee live\" --service codeeqr",
    },
    {
        "feature": "Agent profiles",
        "inspiration": "Codex/Claude custom agents with focused tools and instructions.",
        "codee_status": "built-in-local",
        "command": "python3 codee.py agents . --write",
    },
    {
        "feature": "Permission modes",
        "inspiration": "Suggest, auto edit, sandbox, and approval controls.",
        "codee_status": "built-in-local-policy",
        "command": "python3 codee.py permissions . --mode suggest --write",
    },
    {
        "feature": "Project memory and rules",
        "inspiration": "CLAUDE.md, AGENTS.md, project rules, and startup context.",
        "codee_status": "built-in-local",
        "command": "python3 codee.py memory . --write",
    },
    {
        "feature": "Per-user long-term memory",
        "inspiration": "Persistent user/workspace context with searchable recall.",
        "codee_status": "built-in-local-user-vault",
        "command": "python3 codee.py memory-vault init . --business \"My Business\" --service codeeqr --force",
    },
    {
        "feature": "MCP-style connector map",
        "inspiration": "MCP servers for browser, docs, GitHub, Figma, and platform tools.",
        "codee_status": "built-in-local-plus-backend",
        "command": "python3 codee.py mcp . --write",
    },
    {
        "feature": "Reusable skills",
        "inspiration": "Codex skills and plugin distribution.",
        "codee_status": "already-built",
        "command": "python3 codee.py skills --access all",
    },
    {
        "feature": "Lifecycle hooks",
        "inspiration": "PreToolUse, PostToolUse, TaskCreated, TaskCompleted, Stop, and session hooks.",
        "codee_status": "already-built-safe-log-only",
        "command": "python3 codee.py hooks . --write",
    },
]

TOOLKIT_STACK = {
    "id": "codee-open-source-toolkit",
    "name": "Codee Open-Source Toolkit",
    "version": "2026.05.25-toolkit-v2",
    "purpose": "Give students, operators, and builders one local workspace for the core open-source course tools.",
    "core_courses": list(TOOLKIT_COURSES),
    "core_skills": ["first-lane-qrcodee", "route-scan", "course-suite", "admin-training", "business-assistant", "skill-policy", "folder-coach", "domain-coach", "browser-scan", "backend-connect", "support-room", "codee-hooks", "connector-registry", "platform-layer"],
    "public_pages": [
        "/codee-toolkit.html",
        "/codee-admin-training.html",
        "/codee-folder-domain.html",
        "/codee-business-types.html",
        "/codee-skills.html",
        "/codee-workbench.html",
        "/index2income/",
        "/index2income/qrcodee/",
        "/index2income/codeeflyer/",
        "/index2income/codeeapp/",
    ],
}

ADMIN_TRAINING = {
    "id": "codee-admin-training",
    "name": "Codee Admin Training",
    "version": "2026.05.25-admin-training-v2",
    "purpose": "Train the owner/admin to explain, operate, and teach the Codee platform stack without confusing open-source courses, done-for-you lanes, and recurring support.",
    "governance_model": [
        {
            "lane": "Mission umbrella",
            "entity": "INVEST IN VETS Foundation",
            "role": "Owns the public mission, veteran-first training priority, nonprofit programs, and philanthropic story.",
        },
        {
            "lane": "Technology company",
            "entity": "AI K9 Kennel",
            "role": "Builds and operates Codee services, templates, hosting, scans, client delivery rooms, and partner workflows.",
        },
        {
            "lane": "Platform",
            "entity": "Codee",
            "role": "The CLI, toolkit, delivery-room logic, support packets, scans, and business workflow layer.",
        },
        {
            "lane": "Licensing path",
            "entity": "Mission license",
            "role": "Prepare a clean legal pathway where AI K9 Kennel can license selected Codee technology to the nonprofit for training and mission use.",
        },
    ],
    "platform_stack": [
        {
            "platform": "GoDaddy",
            "role": "Domain registrar and DNS control.",
            "admin_training": "Teach A, CNAME, TXT, and domain verification records before promising a domain is connected.",
            "proof": "DNS record screenshot plus live route check.",
        },
        {
            "platform": "Firebase Hosting",
            "role": "Fast public static pages for Codee, courses, demos, delivery pages, and training pages.",
            "admin_training": "Teach how a folder deploys into a public HTTPS route.",
            "proof": "firebase deploy output plus 200 route scan.",
        },
        {
            "platform": "Google Cloud Run",
            "role": "Backend API for dynamic logic, Stripe webhooks, QR generation, admin endpoints, and service fulfillment.",
            "admin_training": "Teach that Cloud Run is where server code runs; redirects are user experience, webhooks are fulfillment truth.",
            "proof": "Cloud Run health check plus route smoke report.",
        },
        {
            "platform": "Google Cloud Storage",
            "role": "Object storage for uploaded images, PDFs, guidebooks, generated assets, and smoke proof artifacts.",
            "admin_training": "Teach bucket purpose, file naming, public/private access, and lifecycle cleanup.",
            "proof": "Bucket object URL or signed/backend-served asset proof.",
        },
        {
            "platform": "Stripe",
            "role": "Hosted checkout, invoices, payment state, and webhook events.",
            "admin_training": "Teach that the client can redirect to a delivery room, but the webhook confirms payment and unlocks delivery.",
            "proof": "Checkout/invoice id, webhook event, and delivery-room route.",
        },
        {
            "platform": "CodeEmail and optional Brevo",
            "role": "Notifications and transactional email when email is needed.",
            "admin_training": "Teach email as a notification layer, not the only delivery system. Codee delivery rooms remain the returnable source.",
            "proof": "Message id plus backend send verification when used.",
        },
        {
            "platform": "Codee CLI and Playwright",
            "role": "Admin proof system for route scans, browser screenshots, skill policy, and support packets.",
            "admin_training": "Teach every build to end with a saved report, not only a visual check.",
            "proof": ".codee/reports and .codee/screenshots artifacts.",
        },
    ],
    "tier_ladder": [
        {
            "tier": "Open-source course",
            "payment_model": "Free for mission priority; public course can be paid if packaged as training.",
            "what_unlocks": "Lessons, local folders, starter index files, QR/Flyer/App labs, and proof habits.",
            "recurring": "No recurring charge required.",
        },
        {
            "tier": "Done-for-you single lane",
            "payment_model": "One-time service purchase.",
            "what_unlocks": "Codee builds the specific tool: QRCodee, Codee Flyer, Codee App, Codee Card, or Codee Blog.",
            "recurring": "No recurring charge unless the client chooses hosting or support.",
        },
        {
            "tier": "Managed hosting",
            "payment_model": "Recurring hosting/support subscription or defined hosting term.",
            "what_unlocks": "Live hosting, storage, route scans, basic support, and delivery-room continuity.",
            "recurring": "Yes, because Codee is actively keeping the asset live and checked.",
        },
        {
            "tier": "Business Suite",
            "payment_model": "Higher-ticket package with included assets and a support window.",
            "what_unlocks": "Bundle of QRCodee, Flyer 100, Flyer 250, App 250, Blog, Card, shell site, delivery room, and admin handoff.",
            "recurring": "Optional monthly support after the included support period.",
        },
    ],
    "admin_lessons": [
        "Teach the difference between a static site, backend API, storage bucket, domain DNS, payment webhook, redirect, and email notification.",
        "Show that open source teaches the lane; done-for-you sells execution; recurring sells hosting, scans, storage, and support.",
        "Use Stripe webhooks as the payment source of truth and delivery-room redirects as the client experience.",
        "Use Codee CLI scans and Playwright screenshots as proof before launch.",
        "Keep legal and accounting separation clean before saying the nonprofit owns or licenses any technology.",
    ],
    "certification_checks": [
        {
            "id": "stack-map",
            "label": "Platform stack explained",
            "proof": ".codee/admin-training.json exists and lists domains, hosting, backend, storage, payments, delivery, email, and proof tooling.",
        },
        {
            "id": "tier-map",
            "label": "Tier ladder understood",
            "proof": "Admin can explain open source, done-for-you, hosting/support, and Business Suite without mixing one-time and recurring value.",
        },
        {
            "id": "route-proof",
            "label": "Live routes scanned",
            "proof": "latest-route-scan.json or admin-certify route checks show 200 responses for public training and toolkit pages.",
        },
        {
            "id": "browser-proof",
            "label": "Browser screenshot saved",
            "proof": "latest-browser-scan.json includes a screenshot path for codee-admin-training.html or another launch page.",
        },
        {
            "id": "support-proof",
            "label": "Support path prepared",
            "proof": "Delivery-room URL or support request packet exists for the workspace.",
        },
    ],
}

ADMIN_GUIDEBOOK_PAGES = [
    {
        "number": 1,
        "title": "The Codee Operating Model",
        "tag": "Foundation",
        "lesson": "Separate the mission umbrella, the builder company, the Codee platform, and the licensing path.",
        "proof": "Admin can explain mission, builder, platform, and license path in under two minutes.",
    },
    {
        "number": 2,
        "title": "What To Learn From AI Platforms",
        "tag": "Inspiration",
        "lesson": "Use chat plus tools plus files plus proof. Do not copy another platform; translate the pattern into Codee's income-lane workflow.",
        "proof": "Every Codee run leaves a file, route, screenshot, report, or delivery-room link.",
    },
    {
        "number": 3,
        "title": "The Page-Based Guidebook Standard",
        "tag": "Guidebook",
        "lesson": "Render guidebooks as responsive pages with readable text, links, print/save support, and structured content.",
        "proof": "Guidebook text is selectable and readable, not trapped inside a flat image.",
    },
    {
        "number": 4,
        "title": "The Codee Platform Stack",
        "tag": "Stack",
        "lesson": "Teach the job of GoDaddy, Firebase Hosting, Cloud Run, Cloud Storage, Stripe, CodeEmail, and Playwright.",
        "proof": "Admin can map one sale from domain to hosted asset to webhook to delivery room.",
    },
    {
        "number": 5,
        "title": "Open Source Course To Paid Lane",
        "tag": "Offer Ladder",
        "lesson": "Open source teaches the method, done-for-you sells execution, and recurring charges attach only to ongoing value.",
        "proof": "A client can understand exactly what they bought and why a monthly charge exists.",
    },
    {
        "number": 6,
        "title": "Business-Type Assistants",
        "tag": "Templates",
        "lesson": "Every business type gets its own assistant, intake, first offer, deliverables, and proof checks.",
        "proof": "business-assistant-init creates a workspace with assistant, routes, markdown, and reports.",
    },
    {
        "number": 7,
        "title": "The Codee CLI Workspace",
        "tag": "CLI",
        "lesson": "The CLI writes .codee manifests, scans routes, captures screenshots, prepares support packets, and certifies admin workspaces.",
        "proof": ".codee/reports contains the latest scan, browser proof, support packet, or certification.",
    },
    {
        "number": 8,
        "title": "Payment, Delivery, And CodeEmail",
        "tag": "Fulfillment",
        "lesson": "Stripe confirms payment, the delivery room gives the client a returnable home, and CodeEmail keeps owner notices traceable.",
        "proof": "Completed purchase has a delivery-room route, owner notice, and scanable public asset.",
    },
    {
        "number": 9,
        "title": "Admin Scans And Launch Proof",
        "tag": "Quality",
        "lesson": "A page is ready when route scans, 404 loops, screenshots, QR checks, and delivery checks pass.",
        "proof": "404 loop shows zero missing routes and browser-scan saves a screenshot.",
    },
    {
        "number": 10,
        "title": "The Mission Scale Path",
        "tag": "Growth",
        "lesson": "Use Codee to teach income lanes, serve local businesses, train veterans first, and fund the land and housing mission with transparent proof.",
        "proof": "A beginner can open the course, build a first folder, see the paid option, and understand the mission.",
    },
]

BUSINESS_ASSISTANT_TYPES = [
    {
        "id": "restaurant",
        "name": "Restaurant / Food Truck Assistant",
        "assistant_name": "Codee Table",
        "audience": "restaurants, food trucks, caterers, and pop-up food brands",
        "first_offer": "menu QR page with hours, ordering CTA, location, specials, and social proof",
        "core_lanes": ["QRCodee", "Codee Flyer 100", "Codee App 250", "Codee Blog"],
        "intake_questions": [
            "What food or menu items should customers see first?",
            "Do customers order online, call, book catering, or visit in person?",
            "What hours, location, parking, delivery, or event details matter?",
            "What photos, menu PDFs, or specials are ready now?",
            "What action should the customer take after scanning?",
        ],
        "deliverables": ["menu QR page", "specials flyer", "ordering CTA", "photo gallery", "delivery room with assets"],
        "recurring_support": "menu updates, seasonal specials, scan checks, hosted images, and event flyers",
        "proof_checks": ["menu link opens", "CTA works", "phone/email/order link works", "QR scans", "mobile text is readable"],
    },
    {
        "id": "barber-beauty",
        "name": "Barber / Beauty Assistant",
        "assistant_name": "Codee Chair",
        "audience": "barbers, salons, braiders, estheticians, nail techs, and beauty studios",
        "first_offer": "booking QR card with service list, best photos, prices, availability, and deposit or booking CTA",
        "core_lanes": ["QRCodee", "Codee Card", "Codee Flyer 100", "Codee Blog"],
        "intake_questions": [
            "What services should be bookable first?",
            "Which photos best prove the quality of work?",
            "What booking, deposit, or consultation link should be used?",
            "What policies should clients know before booking?",
            "What location or travel-service details should be shown?",
        ],
        "deliverables": ["booking QR card", "service menu", "portfolio section", "policy block", "review or testimonial section"],
        "recurring_support": "service updates, new portfolio photos, promo flyers, monthly booking route checks",
        "proof_checks": ["booking CTA works", "portfolio images load", "policy text is visible", "QR scans", "mobile layout is no-scroll where possible"],
    },
    {
        "id": "home-service",
        "name": "Home Service / Contractor Assistant",
        "assistant_name": "Codee Crew",
        "audience": "contractors, cleaners, landscapers, repair pros, movers, painters, and local service crews",
        "first_offer": "quote-request landing page with service area, proof photos, emergency CTA, and estimate form",
        "core_lanes": ["QRCodee", "Codee Flyer 250", "Codee App 250", "Codee Business Suite"],
        "intake_questions": [
            "What service should generate the first qualified lead?",
            "What ZIP codes, cities, or service areas are covered?",
            "What before-and-after photos or proof can be used?",
            "Should the CTA be call, text, quote form, or booking?",
            "What license, insurance, warranty, or safety statements are verified?",
        ],
        "deliverables": ["quote page", "service-area block", "proof gallery", "lead CTA", "inspection checklist app"],
        "recurring_support": "seasonal campaigns, lead-page updates, new gallery photos, monthly route and form checks",
        "proof_checks": ["lead CTA works", "service area is clear", "claims are verified", "images load", "form route works"],
    },
    {
        "id": "nonprofit",
        "name": "Nonprofit / Mission Assistant",
        "assistant_name": "Codee Mission",
        "audience": "nonprofits, community groups, veteran programs, ministries, and local cause campaigns",
        "first_offer": "mission action page with donation CTA, volunteer CTA, impact story, transparency link, and resource guide",
        "core_lanes": ["QRCodee", "Codee Flyer 250", "Codee App 250", "Codee Blog"],
        "intake_questions": [
            "What mission problem should visitors understand first?",
            "What action matters most: donate, volunteer, request help, sponsor, or share?",
            "What proof, transparency, or impact records are ready?",
            "What resources should be downloadable or hosted?",
            "What language must avoid promises, guarantees, or unverified claims?",
        ],
        "deliverables": ["mission page", "donation QR flyer", "resource guide app", "impact blog post", "sponsor CTA"],
        "recurring_support": "campaign updates, donor landing pages, guidebook storage, route scans, report proof",
        "proof_checks": ["donation route opens", "resource route opens", "claims are safe", "contact route works", "impact section is clear"],
    },
    {
        "id": "fitness-coach",
        "name": "Fitness / Coach Assistant",
        "assistant_name": "Codee Coach",
        "audience": "trainers, gyms, coaches, wellness instructors, teams, and online programs",
        "first_offer": "program signup page with transformation proof, class schedule, consultation CTA, and starter guide",
        "core_lanes": ["QRCodee", "Codee App 250", "Codee Flyer 100", "Codee Card"],
        "intake_questions": [
            "What program or result should be promoted first?",
            "Is the CTA a consultation, class signup, membership, or guide purchase?",
            "What schedule, location, or online access details matter?",
            "What proof can be shown without unsafe health claims?",
            "What starter guide or checklist should be delivered?",
        ],
        "deliverables": ["program landing page", "signup QR", "starter guide app", "coach card", "class flyer"],
        "recurring_support": "class schedule updates, monthly challenge pages, hosted guidebooks, scan checks",
        "proof_checks": ["signup CTA works", "claims are safe", "schedule is current", "guide link opens", "QR scans"],
    },
    {
        "id": "retail-product",
        "name": "Retail / Product Shop Assistant",
        "assistant_name": "Codee Cart",
        "audience": "small product brands, merch shops, makers, skincare brands, and local retail sellers",
        "first_offer": "product launch page with photos, benefits, QR route, checkout CTA, and buyer delivery path",
        "core_lanes": ["QRCodee", "Codee Flyer 250", "Codee App 250", "Codee Blog"],
        "intake_questions": [
            "What product should be launched first?",
            "What photos, mockups, labels, or ingredients are verified?",
            "What checkout, cart, or payment link should be used?",
            "What delivery, shipping, download, or pickup flow applies?",
            "What product claims must stay safe and accurate?",
        ],
        "deliverables": ["product launch page", "QR product flyer", "benefit bullets", "checkout CTA", "buyer delivery room"],
        "recurring_support": "new product drops, image updates, checkout route checks, hosted guide or care pages",
        "proof_checks": ["checkout opens", "product images load", "claims are safe", "delivery path is clear", "QR scans"],
    },
    {
        "id": "professional-service",
        "name": "Professional Service Assistant",
        "assistant_name": "Codee Desk",
        "audience": "consultants, accountants, attorneys, insurance agents, recruiters, notaries, and business advisors",
        "first_offer": "trust-building consultation page with service scope, booking CTA, proof points, and intake form",
        "core_lanes": ["Codee Card", "QRCodee", "Codee Blog", "Codee Business Suite"],
        "intake_questions": [
            "What service should a new client ask about first?",
            "What qualifications, licenses, or experience can be stated accurately?",
            "What booking, intake, or consultation route should be used?",
            "What client questions need to be answered before a call?",
            "What disclaimers or jurisdiction limits are required?",
        ],
        "deliverables": ["consultation page", "professional card", "FAQ blog", "intake form path", "booking room"],
        "recurring_support": "service copy updates, FAQ posts, appointment route checks, new offer pages",
        "proof_checks": ["booking CTA works", "disclaimers are visible", "service scope is clear", "intake route works", "mobile page reads cleanly"],
    },
    {
        "id": "real-estate",
        "name": "Real Estate / Property Assistant",
        "assistant_name": "Codee Key",
        "audience": "agents, property managers, landlords, short-term rental hosts, and property investors",
        "first_offer": "property or service page with photos, inquiry CTA, neighborhood details, and lead capture",
        "core_lanes": ["QRCodee", "Codee Flyer 250", "Codee App 250", "Codee Blog"],
        "intake_questions": [
            "Is this for a listing, rental, property service, or investor lead?",
            "What photos, address level, and neighborhood details are approved?",
            "What inquiry, booking, or application route should be used?",
            "What compliance, fair housing, or availability language must be respected?",
            "What downloadable guide or buyer/renter checklist should be hosted?",
        ],
        "deliverables": ["property QR page", "listing flyer", "inquiry CTA", "guidebook app", "neighborhood info section"],
        "recurring_support": "listing changes, availability updates, guidebook storage, lead route scans",
        "proof_checks": ["inquiry CTA works", "availability is clear", "compliance language is safe", "images load", "QR scans"],
    },
    {
        "id": "pet-service",
        "name": "Pet / Animal Service Assistant",
        "assistant_name": "Codee Kennel",
        "audience": "trainers, groomers, boarders, rescues, walkers, breeders, and pet service providers",
        "first_offer": "service booking page with care standards, booking CTA, service menu, photos, and guide download",
        "core_lanes": ["QRCodee", "Codee Card", "Codee App 250", "Codee Flyer 100"],
        "intake_questions": [
            "What pet service should be booked first?",
            "What animal types, sizes, or requirements apply?",
            "What safety, vaccination, temperament, or care policies must be shown?",
            "What booking or inquiry route should clients use?",
            "What guide, checklist, or preparation PDF should be delivered?",
        ],
        "deliverables": ["service booking page", "care policy block", "guidebook app", "QR flyer", "photo proof section"],
        "recurring_support": "policy updates, new photos, guidebook storage, appointment route checks",
        "proof_checks": ["booking route works", "policy text is visible", "guide opens", "photos load", "QR scans"],
    },
    {
        "id": "event-creator",
        "name": "Event / Creator Assistant",
        "assistant_name": "Codee Stage",
        "audience": "event hosts, speakers, musicians, creators, workshops, classes, and local pop-ups",
        "first_offer": "event landing page with date, ticket or RSVP CTA, flyer, QR route, speaker/host info, and follow-up room",
        "core_lanes": ["QRCodee", "Codee Flyer 250", "Codee Card", "Codee Blog"],
        "intake_questions": [
            "What is the event title, date, time, and location?",
            "Is the CTA ticket purchase, RSVP, booking, donation, or waitlist?",
            "What flyer, host image, speaker details, or sponsor assets are ready?",
            "What should attendees receive after signing up?",
            "What reminders, updates, or after-event links should be hosted?",
        ],
        "deliverables": ["event page", "QR event flyer", "host card", "RSVP or ticket CTA", "attendee delivery room"],
        "recurring_support": "event updates, new flyers, ticket route checks, recap pages, repeat-event templates",
        "proof_checks": ["date is visible", "ticket/RSVP CTA works", "flyer loads", "attendee link is clear", "QR scans"],
    },
]



def _now() -> str:
    return dt.datetime.now(dt.timezone.utc).isoformat()


def _slugify(value: str) -> str:
    out = []
    prev_dash = False
    for char in value.strip().lower():
        if char.isalnum():
            out.append(char)
            prev_dash = False
        elif not prev_dash:
            out.append("-")
            prev_dash = True
    return "".join(out).strip("-") or "codee-client"


def _codee_user_id(email: str = "", seed: str = "") -> str:
    basis = str(email or "").strip().lower() or str(seed or "").strip().lower() or "codee-user"
    digest = hashlib.sha256(basis.encode("utf-8")).hexdigest()[:18]
    return f"cusr_{digest}"


def _workspace_root_for_path(path: Path) -> Path:
    try:
        resolved = path.expanduser().resolve()
    except Exception:
        resolved = path.expanduser()
    if ".codee" in resolved.parts:
        parts = list(resolved.parts)
        try:
            index = parts.index(".codee")
            return Path(*parts[:index]) if index > 0 else resolved.parent
        except ValueError:
            pass
    for parent in [resolved.parent, *resolved.parents]:
        if (parent / ".codee").exists():
            return parent
    return resolved.parent


def _checkpoint_existing_path(path: Path, *, reason: str = "overwrite") -> str:
    if not path.exists() or path.is_dir():
        return ""
    if ".codee" in path.parts and "checkpoints" in path.parts:
        return ""
    try:
        if path.stat().st_size > 8 * 1024 * 1024:
            return ""
    except Exception:
        return ""
    root = _workspace_root_for_path(path)
    rel = path.resolve().relative_to(root.resolve()) if str(path.resolve()).startswith(str(root.resolve())) else Path(path.name)
    safe_rel = "__".join(part for part in rel.parts if part not in {"", "."})
    checkpoint_dir = root / ".codee" / "checkpoints" / _safe_time_slug()
    checkpoint_dir.mkdir(parents=True, exist_ok=True)
    target = checkpoint_dir / (safe_rel or path.name)
    try:
        shutil.copy2(path, target)
    except Exception:
        return ""
    event_path = root / ".codee" / "events.jsonl"
    event_path.parent.mkdir(parents=True, exist_ok=True)
    event = {
        "schema": "codee.cli.event.v1",
        "created_at": _now(),
        "event": "CheckpointCreated",
        "cli_version": VERSION,
        "workspace": root.name,
        "payload": {"source": str(path), "checkpoint": str(target), "reason": reason},
    }
    with event_path.open("a", encoding="utf-8") as handle:
        handle.write(json.dumps(event, sort_keys=True) + "\n")
    return str(target)


def _write_json(path: Path, payload: dict[str, Any] | list[Any], *, force: bool) -> bool:
    if path.exists() and not force:
        return False
    if path.exists() and force:
        _checkpoint_existing_path(path, reason="json-overwrite")
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
    return True


def _write_text(path: Path, text: str, *, force: bool) -> bool:
    if path.exists() and not force:
        return False
    if path.exists() and force:
        _checkpoint_existing_path(path, reason="text-overwrite")
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")
    return True


def _api_url(api_base: str, path: str, query: dict[str, str] | None = None) -> str:
    base = str(api_base or DEFAULT_API_BASE).strip().rstrip("/")
    clean_path = "/" + path.strip("/")
    url = f"{base}{clean_path}"
    if query:
        url = f"{url}?{urllib.parse.urlencode(query)}"
    return url


def _curl_fetch(method: str, url: str, payload: dict[str, Any] | None = None, *, timeout: float = 30) -> dict[str, Any]:
    curl = shutil.which("curl")
    if not curl:
        return {"ok": False, "error": "curl_not_available", "status": 0, "body": "", "final_url": url}
    body_payload = json.dumps(payload) if payload is not None else ""
    command = [
        curl,
        "-L",
        "-sS",
        "--retry",
        "2",
        "--retry-delay",
        "1",
        "--connect-timeout",
        str(max(2, min(10, int(float(timeout))))),
        "--max-time",
        str(max(1, int(float(timeout)))),
        "-w",
        "\n__CODEE_STATUS__:%{http_code}\n__CODEE_EFFECTIVE__:%{url_effective}\n",
        "-X",
        method.upper(),
        "-H",
        f"User-Agent: CodeeCLI/{VERSION}",
    ]
    if payload is not None:
        command.extend(["-H", "Content-Type: application/json", "--data-binary", body_payload])
    command.append(url)
    try:
        proc = subprocess.run(command, text=False, capture_output=True, timeout=float(timeout) + 5)
    except Exception as exc:
        return {"ok": False, "error": f"curl_failed:{type(exc).__name__}: {str(exc)[:160]}", "status": 0, "body": "", "final_url": url}
    raw = proc.stdout.decode("utf-8", errors="replace")
    stderr = proc.stderr.decode("utf-8", errors="replace").strip()
    body = raw
    status = 0
    final_url = url
    if "\n__CODEE_STATUS__:" in raw:
        body, meta = raw.rsplit("\n__CODEE_STATUS__:", 1)
        lines = meta.splitlines()
        try:
            status = int((lines[0] if lines else "0").strip() or "0")
        except ValueError:
            status = 0
        for line in lines[1:]:
            if line.startswith("__CODEE_EFFECTIVE__:"):
                final_url = line.split(":", 1)[1].strip() or url
                break
    return {
        "ok": bool(proc.returncode == 0 and status > 0),
        "returncode": proc.returncode,
        "status": status,
        "body": body,
        "final_url": final_url,
        "error": stderr if proc.returncode else "",
    }


def _request_json(method: str, url: str, payload: dict[str, Any] | None = None, *, timeout: float = 30) -> dict[str, Any]:
    data = None
    headers = {"User-Agent": f"CodeeCLI/{VERSION}", "Accept": "application/json"}
    if payload is not None:
        data = json.dumps(payload).encode("utf-8")
        headers["Content-Type"] = "application/json"
    req = urllib.request.Request(url, data=data, method=method.upper(), headers=headers)
    try:
        with urllib.request.urlopen(req, timeout=timeout) as res:
            raw = res.read().decode("utf-8", errors="replace")
            parsed = json.loads(raw) if raw.strip() else {}
            if isinstance(parsed, dict):
                parsed.setdefault("http_status", int(res.status))
                return parsed
            return {"ok": False, "error": "json_response_not_object", "response": parsed, "http_status": int(res.status)}
    except urllib.error.HTTPError as exc:
        raw = exc.read().decode("utf-8", errors="replace")
        try:
            parsed = json.loads(raw) if raw.strip() else {}
        except Exception:
            parsed = {"raw": raw[:500]}
        if isinstance(parsed, dict):
            parsed.setdefault("ok", False)
            parsed.setdefault("http_status", int(exc.code))
            return parsed
        return {"ok": False, "error": f"http_{exc.code}", "response": parsed, "http_status": int(exc.code)}
    except Exception as exc:
        fallback = _curl_fetch(method, url, payload, timeout=timeout)
        if fallback.get("ok"):
            raw = str(fallback.get("body") or "")
            try:
                parsed = json.loads(raw) if raw.strip() else {}
            except Exception as parse_exc:
                return {
                    "ok": False,
                    "error": f"curl_json_parse_failed:{type(parse_exc).__name__}",
                    "http_status": int(fallback.get("status") or 0),
                    "transport": "curl-fallback",
                    "urllib_error": f"{type(exc).__name__}: {str(exc)[:160]}",
                    "raw": raw[:500],
                }
            if isinstance(parsed, dict):
                parsed.setdefault("http_status", int(fallback.get("status") or 0))
                parsed.setdefault("transport", "curl-fallback")
                parsed.setdefault("urllib_error", f"{type(exc).__name__}: {str(exc)[:160]}")
                return parsed
            return {
                "ok": False,
                "error": "curl_json_response_not_object",
                "response": parsed,
                "http_status": int(fallback.get("status") or 0),
                "transport": "curl-fallback",
            }
        return {
            "ok": False,
            "error": f"{type(exc).__name__}: {str(exc)[:180]}",
            "http_status": 0,
            "fallback_error": str(fallback.get("error") or "")[:180],
        }


def _api_base_candidates(primary: str | None, extras: list[str] | None = None) -> list[str]:
    values: list[str] = []
    for item in [primary, DEFAULT_API_BASE, *(extras or []), os.getenv("CODEE_API_FALLBACK_BASES"), *DEFAULT_API_FALLBACK_BASES]:
        if not item:
            continue
        for raw in re.split(r"[\s,]+", str(item)):
            base = raw.strip().rstrip("/")
            if base.startswith(("http://", "https://")) and base not in values:
                values.append(base)
    return values or [DEFAULT_API_BASE]


def _should_try_next_api_base(result: dict[str, Any]) -> bool:
    try:
        status = int(result.get("http_status") or result.get("status") or 0)
    except Exception:
        status = 0
    if status in {502, 503, 504}:
        return True
    if status == 0:
        return True
    return False


def _request_json_with_api_fallbacks(
    method: str,
    api_base: str,
    path: str,
    payload: dict[str, Any] | None = None,
    *,
    timeout: float = 30,
    fallback_bases: list[str] | None = None,
) -> dict[str, Any]:
    attempts: list[dict[str, Any]] = []
    last_result: dict[str, Any] = {"ok": False, "error": "no_api_attempts", "http_status": 0}
    for base in _api_base_candidates(api_base, fallback_bases):
        url = _api_url(base, path)
        result = _request_json(method, url, payload, timeout=timeout)
        attempts.append(
            {
                "api_base": base,
                "url": url,
                "ok": bool(result.get("ok")),
                "http_status": int(result.get("http_status") or result.get("status") or 0),
                "transport": str(result.get("transport") or "urllib"),
                "error": str(result.get("error") or result.get("fallback_error") or "")[:220],
            }
        )
        result["api_base_used"] = base
        result["transport_attempts"] = attempts
        last_result = result
        if result.get("ok") or not _should_try_next_api_base(result):
            return result
    last_result["transport_attempts"] = attempts
    return last_result


def _curl_submit_script(*, api_base: str, path: str, payload_path: Path, timeout: float) -> str:
    url = _api_url(api_base, path)
    return "\n".join(
        [
            "#!/usr/bin/env bash",
            "set -euo pipefail",
            "curl -sS \\",
            "  -X POST \\",
            "  -H 'Content-Type: application/json' \\",
            f"  -H 'User-Agent: CodeeCLI/{VERSION}-shell-fallback' \\",
            f"  --max-time {shlex.quote(str(max(1, int(float(timeout)))))} \\",
            f"  --data-binary @{shlex.quote(str(payload_path))} \\",
            f"  {shlex.quote(url)}",
            "",
        ]
    )


def _write_report(root: Path, name: str, payload: dict[str, Any]) -> Path:
    report_dir = root / ".codee" / "reports"
    report_dir.mkdir(parents=True, exist_ok=True)
    path = report_dir / name
    path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
    return path


def _state_path(root: Path) -> Path:
    return root / ".codee" / "state.json"


def _load_state(root: Path) -> dict[str, Any]:
    path = _state_path(root)
    if not path.exists():
        return {
            "schema": "codee.state.v1",
            "created_at": _now(),
            "updated_at": _now(),
            "cli_version": VERSION,
            "workspace": root.name,
            "history": [],
        }
    state = _read_json_if_exists(path)
    if state.get("schema") != "codee.state.v1":
        state["schema"] = "codee.state.v1"
    state.setdefault("created_at", _now())
    state.setdefault("history", [])
    return state


def _write_state(root: Path, state: dict[str, Any]) -> Path:
    path = _state_path(root)
    state["updated_at"] = _now()
    state["cli_version"] = VERSION
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
    return path


def _record_command_state(args: argparse.Namespace, exit_code: int) -> None:
    path_value = getattr(args, "path", ".") or "."
    try:
        root = Path(str(path_value)).expanduser().resolve()
    except Exception:
        return
    command = str(getattr(args, "command", "") or "")
    if not command:
        return
    try:
        state = _load_state(root)
        service = _normalize_service(str(getattr(args, "service", "") or state.get("service") or "codee-support"))
        state["workspace"] = root.name
        state["service"] = service
        state["last_command"] = command
        state["last_exit_code"] = int(exit_code)
        state["last_status"] = "ok" if int(exit_code) == 0 else "needs_attention"
        state["last_run_at"] = _now()
        state["delivery_room_url"] = str(state.get("delivery_room_url") or "")
        state["tool_registry_url"] = CODEE_TOOL_REGISTRY_URL
        state["release_url"] = CODEE_RELEASE_URL
        history = state.get("history") if isinstance(state.get("history"), list) else []
        history.append(
            {
                "at": _now(),
                "command": command,
                "service": service,
                "exit_code": int(exit_code),
                "path": str(root),
            }
        )
        state["history"] = history[-200:]
        _write_state(root, state)
    except Exception:
        return


def _is_sensitive_path(path: Path) -> bool:
    name = path.name.lower()
    rel = path.as_posix().lower()
    if rel.endswith(".codee/company/trade_secret_register.md"):
        return False
    if name in SENSITIVE_FILE_NAMES:
        return True
    if path.suffix.lower() in SENSITIVE_SUFFIXES:
        return True
    return any(pattern in rel for pattern in SENSITIVE_FILE_PATTERNS)


def _scan_sensitive_files(root: Path, *, limit: int = 50) -> list[dict[str, Any]]:
    if not root.exists():
        return []
    skip_dirs = {".git", "node_modules", ".venv", "venv", "__pycache__", ".next", "dist", "build", "checkpoints"}
    hits: list[dict[str, Any]] = []
    for path in root.rglob("*"):
        if len(hits) >= limit:
            break
        try:
            rel = path.relative_to(root)
        except Exception:
            rel = path
        if any(part in skip_dirs for part in rel.parts):
            continue
        if path.is_file() and _is_sensitive_path(path):
            hits.append({"path": rel.as_posix(), "kind": path.suffix.lower() or path.name, "action": "do-not-upload-or-submit"})
    return hits


def _default_route_urls_from_reports(root: Path) -> list[str]:
    urls: list[str] = []
    for path in [
        root / ".codee" / "reports" / "latest-backend-connect.json",
        root / ".codee" / "reports" / "latest-activation-request.json",
        root / ".codee" / "reports" / "latest-client-intake.json",
        root / ".codee" / "reports" / "latest-delivery-room.json",
        root / ".codee" / "backend-connection.json",
    ]:
        payload = _read_json_if_exists(path)
        for key in ("delivery_room_url", "workbench_url", "paid_intake_url", "activate_url", "hosted_url", "delivery_url", "url"):
            value = str(payload.get(key) or "").strip()
            if value.startswith(("http://", "https://")) and value not in urls:
                urls.append(value)
        next_obj = payload.get("next") if isinstance(payload.get("next"), dict) else {}
        for key in ("checkout_url", "start_checkout_url"):
            value = str(next_obj.get(key) or "").strip()
            if value.startswith(("http://", "https://")) and value not in urls:
                urls.append(value)
        preview = payload.get("preview") if isinstance(payload.get("preview"), dict) else {}
        value = str(preview.get("preview_url") or "").strip()
        if value.startswith(("http://", "https://")) and value not in urls:
            urls.append(value)
    return urls


def _normalize_service(value: str) -> str:
    clean = str(value or "").strip().lower().replace(" ", "-")
    return SERVICE_ALIASES.get(clean, clean or "codee-cli")


def _service_contract(service: str) -> dict[str, Any]:
    clean = _normalize_service(service or "codeeqr")
    base = CODEE_SERVICE_CONTRACTS.get(clean) or CODEE_SERVICE_CONTRACTS["codeeqr"]
    return json.loads(json.dumps(base))


def _append_event(root: Path, event: str, payload: dict[str, Any] | None = None) -> Path:
    codee_dir = root / ".codee"
    codee_dir.mkdir(parents=True, exist_ok=True)
    event_payload = {
        "schema": "codee.cli.event.v1",
        "created_at": _now(),
        "event": event,
        "cli_version": VERSION,
        "workspace": root.name,
        "payload": payload or {},
    }
    path = codee_dir / "events.jsonl"
    with path.open("a", encoding="utf-8") as handle:
        handle.write(json.dumps(event_payload, sort_keys=True) + "\n")
    return path


def _hook_manifest() -> dict[str, Any]:
    return {
        "schema": "codee.hooks.v1",
        "version": VERSION,
        "mode": "safe-log-only",
        "description": "Codee hooks record lifecycle events. Public downloads do not execute arbitrary shell hooks.",
        "events": CODEE_HOOK_EVENTS,
        "event_log": ".codee/events.jsonl",
        "guardrails": [
            "Hooks are log-only in public CLI workspaces.",
            "Backend-only hooks require Codee owner infrastructure.",
            "Do not store API keys, Stripe secrets, OAuth tokens, or private files in hook logs.",
        ],
    }


def _connector_manifest() -> dict[str, Any]:
    return {
        "schema": "codee.connectors.v1",
        "version": VERSION,
        "created_at": _now(),
        "connectors": CONNECTOR_REGISTRY,
        "public_rule": "A public CLI can request backend actions, but payment, hosting, storage, and third-party credentials stay backend/owner gated.",
    }


def _permission_mode(mode: str) -> dict[str, Any]:
    clean = str(mode or "").strip().lower() or "suggest"
    for item in CODEE_PERMISSION_MODES:
        if item["id"] == clean:
            return item
    valid = ", ".join(str(item["id"]) for item in CODEE_PERMISSION_MODES)
    raise SystemExit(f"Unknown permission mode '{mode}'. Use one of: {valid}")


def _permissions_manifest(mode: str = "suggest") -> dict[str, Any]:
    selected = _permission_mode(mode)
    return {
        "schema": "codee.permissions.v1",
        "version": VERSION,
        "created_at": _now(),
        "selected_mode": selected["id"],
        "modes": CODEE_PERMISSION_MODES,
        "rules": [
            "Public Codee CLI workspaces never store Stripe secret keys, OAuth refresh tokens, or owner deploy credentials.",
            "Workspace writes stay inside the selected folder unless owner approval is explicit.",
            "Network work should go through Codee backend endpoints or owner-approved integrations.",
            "Payment collection must stay on Stripe-hosted pages or verified backend flows.",
            "Any generated client claim must be reviewed against the actual service contract before launch.",
            "Sensitive files such as .env, private keys, OAuth tokens, service accounts, and Stripe secrets are blocked from support attachments and flagged by doctor/heartbeat.",
            "Overwrites made by Codee write helpers create local checkpoints under .codee/checkpoints when --force is used.",
        ],
        "sensitive_file_policy": {
            "blocked_names": sorted(SENSITIVE_FILE_NAMES),
            "blocked_suffixes": sorted(SENSITIVE_SUFFIXES),
            "blocked_patterns": list(SENSITIVE_FILE_PATTERNS),
        },
    }


def _permissions_markdown(payload: dict[str, Any]) -> str:
    selected = str(payload.get("selected_mode") or "suggest")
    lines = [
        "# Codee Permission Policy",
        "",
        f"Selected mode: {selected}",
        "",
        "## Modes",
        "",
    ]
    for item in payload.get("modes") or []:
        lines.append(f"- {item.get('id')}: {item.get('label')} - {item.get('best_for')}")
    lines.extend(["", "## Rules", ""])
    for rule in payload.get("rules") or []:
        lines.append(f"- {rule}")
    lines.append("")
    return "\n".join(lines)


def _agents_manifest(permission_mode: str = "suggest") -> dict[str, Any]:
    _permission_mode(permission_mode)
    agents: list[dict[str, Any]] = []
    for agent in CODEE_AGENT_PROFILES:
        item = dict(agent)
        if item.get("permission_mode") not in {mode["id"] for mode in CODEE_PERMISSION_MODES}:
            item["permission_mode"] = permission_mode
        agents.append(item)
    return {
        "schema": "codee.agents.v1",
        "version": VERSION,
        "created_at": _now(),
        "default_permission_mode": permission_mode,
        "agents": agents,
        "routing_rule": "Use one focused agent at a time, then verify before handing the folder to paid hosting or public launch.",
    }


def _agent_profile_markdown(agent: dict[str, Any]) -> str:
    tools = ", ".join(str(item) for item in agent.get("tools") or [])
    outputs = "\n".join(f"- {item}" for item in agent.get("outputs") or [])
    return f"""---
name: {agent.get('id')}
description: {agent.get('description')}
permission_mode: {agent.get('permission_mode')}
---

# {agent.get('name')}

Purpose: {agent.get('description')}

Tools: {tools}

## Required Outputs

{outputs}

## Operating Rule

Stay inside the Codee folder, write proof files, and run `python3 codee.py verify . --service SERVICE` before launch.
"""


def _agents_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee Agent Profiles",
        "",
        f"Default permission mode: {payload.get('default_permission_mode')}",
        "",
        "These profiles make Codee feel like an agent platform while keeping the business lane focused.",
        "",
    ]
    for item in payload.get("agents") or []:
        lines.append(f"## {item.get('name')}")
        lines.append("")
        lines.append(str(item.get("description") or ""))
        lines.append("")
        lines.append(f"Permission mode: {item.get('permission_mode')}")
        lines.append(f"Tools: {', '.join(str(tool) for tool in item.get('tools') or [])}")
        lines.append("")
    return "\n".join(lines)


def _mcp_manifest(api_base: str = DEFAULT_API_BASE, *, public_only: bool = False) -> dict[str, Any]:
    blueprints: list[dict[str, Any]] = []
    for item in CODEE_MCP_BLUEPRINTS:
        if public_only and not item.get("public_cli"):
            continue
        clean = dict(item)
        if clean.get("id") in {"codee-backend-http", "stripe-backend"}:
            clean["url"] = str(clean.get("url") or "").replace(DEFAULT_API_BASE, str(api_base or DEFAULT_API_BASE).rstrip("/"))
        blueprints.append(clean)
    return {
        "schema": "codee.mcp-blueprint.v1",
        "version": VERSION,
        "created_at": _now(),
        "note": "This is a Codee connector blueprint. Public CLI users do not receive owner credentials.",
        "servers": blueprints,
    }


def _mcp_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee MCP-Style Connector Blueprint",
        "",
        "Codee should feel familiar to users who know MCP, Codex, or Claude Code, but it stays business-service focused.",
        "",
    ]
    for item in payload.get("servers") or []:
        lines.append(f"## {item.get('name')}")
        lines.append("")
        lines.append(f"- id: {item.get('id')}")
        lines.append(f"- transport: {item.get('transport')}")
        if item.get("url"):
            lines.append(f"- url: {item.get('url')}")
        lines.append(f"- auth: {item.get('auth')}")
        lines.append(f"- public_cli: {bool(item.get('public_cli'))}")
        lines.append(f"- tools: {', '.join(str(tool) for tool in item.get('tools') or [])}")
        lines.append("")
    return "\n".join(lines)


def _memory_manifest(root: Path, *, business: str = "", service: str = "") -> dict[str, Any]:
    manifest = _load_manifest(root)
    business_name = str(business or manifest.get("business") or "Codee Client").strip()
    service_name = str(service or manifest.get("service") or "codee-service").strip()
    return {
        "schema": "codee.project-memory.v1",
        "version": VERSION,
        "created_at": _now(),
        "business": business_name,
        "service": service_name,
        "memory_files": ["CODEE.md", "AGENTS.md", ".codee/rules/service-lane.md", ".codee/memory.json", ".codee/user-memory.json", ".codee/users/<codee_user_id>/memory/memories.jsonl"],
        "rules": [
            "The folder is the business surface: index.html, assets, and .codee proof files.",
            "Start with one sellable lane before adding a full platform.",
            "Keep all payments on hosted Stripe or verified backend payment routes.",
            "Every client delivery needs a returnable delivery room, support path, and scan proof.",
            "Disabled and homeless veteran training gets the open-source course priority lane.",
            "Each user gets a local-first memory vault keyed by codee_user_id for preferences, service history, proof, and next steps.",
        ],
        "startup_context": [
            f"Business: {business_name}",
            f"Service: {service_name}",
            "Default first lane: QRCodee unless the intake clearly asks for another service.",
            "Before public launch: run verify, scan, support packet, and route proof.",
            "Before repeating questions: run memory-vault search for the user's saved preferences and history.",
        ],
    }


def _memory_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee Project Memory",
        "",
        f"Business: {payload.get('business')}",
        f"Service: {payload.get('service')}",
        "",
        "## Startup Context",
        "",
    ]
    for item in payload.get("startup_context") or []:
        lines.append(f"- {item}")
    lines.extend(["", "## Rules", ""])
    for item in payload.get("rules") or []:
        lines.append(f"- {item}")
    lines.extend(
        [
            "",
            "## Next Best Commands",
            "",
            "```bash",
            "python3 codee.py platform . --write --force",
            "python3 codee.py task create . --title \"Launch the first QRCodee lane\" --service codeeqr --prompt \"Create, verify, and connect the first QRCodee folder.\"",
            "python3 codee.py verify . --service codeeqr",
            "```",
            "",
        ]
    )
    return "\n".join(lines)


def _safe_user_id(value: str) -> str:
    clean = []
    for char in str(value or "").strip():
        if char.isalnum() or char in {"_", "-"}:
            clean.append(char)
        else:
            clean.append("-")
    return "".join(clean).strip("-") or "cusr_local"


def _user_memory_paths(root: Path, *, user_id: str = "") -> dict[str, Path]:
    manifest = _load_manifest(root)
    clean_user_id = _safe_user_id(user_id or str(manifest.get("codee_user_id") or "") or _codee_user_id(seed=str(root)))
    base = root / ".codee" / "users" / clean_user_id / "memory"
    return {
        "base": base,
        "vault": base / "vault.json",
        "journal": base / "memories.jsonl",
        "index": base / "index.json",
        "markdown": base / "USER_MEMORY.md",
        "export_dir": base / "exports",
        "pointer": root / ".codee" / "user-memory.json",
        "root_markdown": root / ".codee" / "USER_MEMORY.md",
    }


def _read_jsonl(path: Path) -> list[dict[str, Any]]:
    if not path.exists():
        return []
    records: list[dict[str, Any]] = []
    for line in path.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if not line:
            continue
        try:
            item = json.loads(line)
        except Exception:
            continue
        if isinstance(item, dict):
            records.append(item)
    return records


def _write_jsonl_append(path: Path, record: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("a", encoding="utf-8") as handle:
        handle.write(json.dumps(record, sort_keys=True) + "\n")


def _memory_token_set(value: str) -> set[str]:
    return {item for item in re.split(r"[^a-z0-9]+", str(value or "").lower()) if len(item) >= 2}


def _memory_score(record: dict[str, Any], query: str) -> int:
    query_tokens = _memory_token_set(query)
    if not query_tokens:
        return 0
    haystack = " ".join(
        [
            str(record.get("text") or ""),
            str(record.get("kind") or ""),
            str(record.get("service") or ""),
            str(record.get("business") or ""),
            " ".join(str(tag) for tag in record.get("tags") or []),
        ]
    )
    record_tokens = _memory_token_set(haystack)
    score = len(query_tokens & record_tokens) * 10
    lowered = haystack.lower()
    if str(query or "").strip().lower() in lowered:
        score += 25
    if str(record.get("importance") or "").lower() in {"high", "critical"}:
        score += 3
    return score


def _user_memory_index(records: list[dict[str, Any]]) -> dict[str, Any]:
    kinds: dict[str, int] = {}
    services: dict[str, int] = {}
    tags: dict[str, int] = {}
    for item in records:
        kind = str(item.get("kind") or "note")
        service = str(item.get("service") or "general")
        kinds[kind] = kinds.get(kind, 0) + 1
        services[service] = services.get(service, 0) + 1
        for tag in item.get("tags") or []:
            tag_key = str(tag or "").strip().lower()
            if tag_key:
                tags[tag_key] = tags.get(tag_key, 0) + 1
    return {
        "schema": "codee.user-memory-index.v1",
        "version": VERSION,
        "updated_at": _now(),
        "record_count": len(records),
        "kinds": kinds,
        "services": services,
        "top_tags": sorted(tags.items(), key=lambda item: item[1], reverse=True)[:25],
        "latest_memory_id": records[-1].get("memory_id") if records else "",
    }


def _user_memory_markdown(vault: dict[str, Any], index: dict[str, Any], records: list[dict[str, Any]]) -> str:
    lines = [
        "# Codee User Memory Vault",
        "",
        f"User: {vault.get('codee_user_id')}",
        f"Business: {vault.get('business')}",
        f"Service: {vault.get('service')}",
        f"Records: {index.get('record_count', 0)}",
        "",
        "## Capacity",
        "",
    ]
    for item in vault.get("capacity_policy") or []:
        lines.append(f"- {item}")
    lines.extend(["", "## Memory Types", ""])
    for item in vault.get("memory_types") or []:
        lines.append(f"- {item}")
    lines.extend(["", "## Recent Memories", ""])
    for item in records[-10:][::-1]:
        tags = ", ".join(str(tag) for tag in item.get("tags") or [])
        suffix = f" Tags: {tags}" if tags else ""
        lines.append(f"- {item.get('created_at')} {item.get('kind')}: {item.get('text')}{suffix}")
    lines.extend(["", "## Commands", ""])
    for item in vault.get("commands") or []:
        lines.append(f"```bash\n{item}\n```")
    return "\n".join(lines) + "\n"


def _user_memory_vault(
    root: Path,
    *,
    business: str = "",
    owner: str = "",
    email: str = "",
    service: str = "codee-service",
) -> dict[str, Any]:
    manifest = _load_manifest(root)
    business_name = str(business or manifest.get("business") or "Codee Client").strip()
    owner_name = str(owner or manifest.get("owner") or "Business Owner").strip()
    owner_email = str(email or manifest.get("owner_email") or "").strip().lower()
    codee_user_id = str(manifest.get("codee_user_id") or _codee_user_id(owner_email, f"{owner_name}:{business_name}:{root}"))
    service_name = _normalize_service(str(service or manifest.get("service") or "codee-service"))
    paths = _user_memory_paths(root, user_id=codee_user_id)
    return {
        "schema": "codee.user-memory-vault.v1",
        "version": VERSION,
        "created_at": _now(),
        "codee_user_id": codee_user_id,
        "client_id": str(manifest.get("client_id") or _slugify(business_name)),
        "business": business_name,
        "owner": owner_name,
        "owner_email": owner_email,
        "service": service_name,
        "storage": {
            "mode": "local-first-jsonl",
            "vault": str(paths["vault"]),
            "journal": str(paths["journal"]),
            "index": str(paths["index"]),
            "export_dir": str(paths["export_dir"]),
            "backend_sync": "available only after codee connect/support backend flow; public CLI does not upload private memories by default",
        },
        "capacity_policy": [
            "File-backed JSONL memory can grow with the user's disk instead of a tiny chat window.",
            "Recommended working vault: up to 100000 memory records or 500 MB per workspace before archive/export.",
            "Search is local keyword recall in this public CLI; vector/semantic recall can be added through a backend-gated upgrade later.",
            "Each workspace is keyed by codee_user_id so one user can carry preferences, service history, proof, and support notes forward.",
        ],
        "memory_types": [
            "identity",
            "preference",
            "business_fact",
            "service_history",
            "task_result",
            "proof",
            "support_note",
            "payment_note",
            "next_step",
        ],
        "privacy_rules": [
            "Do not store passwords, private keys, Stripe secrets, OAuth refresh tokens, or card numbers.",
            "Use summaries for sensitive context instead of raw documents when possible.",
            "The public CLI keeps memory local unless the user intentionally sends a support/connect packet.",
        ],
        "commands": [
            f"python3 codee.py memory-vault add {root} --kind preference --text \"Remember my preferred colors, tone, and service lane.\" --tag intake",
            f"python3 codee.py memory-vault search {root} --query \"preferred colors service lane\"",
            f"python3 codee.py heartbeat {root} --service {service_name}",
        ],
    }


def _ensure_user_memory_vault(
    root: Path,
    *,
    business: str = "",
    owner: str = "",
    email: str = "",
    service: str = "codee-service",
    force: bool = False,
) -> dict[str, Any]:
    root.mkdir(parents=True, exist_ok=True)
    codee_dir = root / ".codee"
    codee_dir.mkdir(parents=True, exist_ok=True)
    manifest_path = codee_dir / "codee.json"
    manifest = _load_manifest(root)
    business_name = str(business or manifest.get("business") or "Codee Client").strip()
    owner_name = str(owner or manifest.get("owner") or "Business Owner").strip()
    owner_email = str(email or manifest.get("owner_email") or "").strip().lower()
    if not manifest_path.exists() or (owner_email and not str(manifest.get("owner_email") or "").strip()):
        manifest = {
            **manifest,
            "schema": str(manifest.get("schema") or "codee.platform.v0"),
            "version": str(manifest.get("version") or VERSION),
            "updated_at": _now(),
            "business": business_name,
            "owner": owner_name,
            "owner_email": owner_email,
            "client_id": str(manifest.get("client_id") or _slugify(business_name)),
            "codee_user_id": str(manifest.get("codee_user_id") or _codee_user_id(owner_email, f"{owner_name}:{business_name}:{root}")),
        }
        _write_json(manifest_path, manifest, force=True)
    vault = _user_memory_vault(root, business=business_name, owner=owner_name, email=owner_email, service=service)
    paths = _user_memory_paths(root, user_id=str(vault.get("codee_user_id") or ""))
    existing_vault = _read_json_if_exists(paths["vault"])
    if existing_vault.get("schema") == "codee.user-memory-vault.v1" and not force:
        vault = existing_vault
        paths = _user_memory_paths(root, user_id=str(vault.get("codee_user_id") or ""))
    records = _read_jsonl(paths["journal"])
    index = _user_memory_index(records)
    paths["journal"].parent.mkdir(parents=True, exist_ok=True)
    if not paths["journal"].exists():
        paths["journal"].write_text("", encoding="utf-8")
    writes = {
        "vault": _write_json(paths["vault"], vault, force=True if force else not paths["vault"].exists()),
        "index": _write_json(paths["index"], index, force=True),
        "pointer": _write_json(paths["pointer"], {"schema": "codee.user-memory-pointer.v1", "version": VERSION, "updated_at": _now(), "codee_user_id": vault["codee_user_id"], "vault": str(paths["vault"]), "journal": str(paths["journal"]), "index": str(paths["index"])}, force=True),
        "markdown": _write_text(paths["markdown"], _user_memory_markdown(vault, index, records), force=True),
        "root_markdown": _write_text(paths["root_markdown"], _user_memory_markdown(vault, index, records), force=True),
    }
    return {"vault": vault, "index": index, "records": records, "paths": {key: str(value) for key, value in paths.items()}, "writes": writes}


def _accessibility_manifest(root: Path, *, business: str = "", service: str = "codee-service") -> dict[str, Any]:
    manifest = _load_manifest(root)
    return {
        **CODEE_ACCESSIBILITY_DEFAULTS,
        "version": VERSION,
        "created_at": _now(),
        "root": str(root),
        "business": str(business or manifest.get("business") or "Codee Client").strip(),
        "service": _normalize_service(str(service or manifest.get("service") or "codee-service")),
        "proof_files": [".codee/accessibility.json", ".codee/ACCESSIBILITY.md"],
        "next_commands": [
            f"python3 codee.py heartbeat {root} --service {_normalize_service(str(service or 'codee-service'))}",
            f"python3 codee.py course-init {root}/qrcodee-course --course qrcodee --business \"{str(business or manifest.get('business') or 'My Business').strip()}\" --target-url https://example.com --force",
        ],
    }


def _accessibility_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee Accessibility Rules",
        "",
        str(payload.get("principle") or ""),
        "",
        f"Business: {payload.get('business')}",
        f"Service: {payload.get('service')}",
        "",
        "## Course Rules",
        "",
    ]
    for item in payload.get("course_rules") or []:
        lines.append(f"- {item}")
    lines.extend(["", "## Default Copy", ""])
    for key, value in (payload.get("default_copy") or {}).items():
        lines.append(f"- {key}: {value}")
    lines.extend(["", "## Next Commands", ""])
    for command in payload.get("next_commands") or []:
        lines.append(f"```bash\n{command}\n```")
    return "\n".join(lines) + "\n"


def _platform_manifest(root: Path, *, permission_mode: str = "suggest", api_base: str = DEFAULT_API_BASE) -> dict[str, Any]:
    return {
        "schema": "codee.platform-parity.v1",
        "version": VERSION,
        "created_at": _now(),
        "root": str(root),
        "summary": "Codee now has the local pieces that make Codex and Claude Code feel like platforms while staying mission-first: Codee AGI doctrine, tasks, agents, project memory, per-user memory vault, accessibility rules, permissions, connectors, skills, hooks, scans, backend connect, and paid activation.",
        "gaps_closed": CODEE_PLATFORM_GAPS,
        "permissions": _permissions_manifest(permission_mode),
        "agents": _agents_manifest(permission_mode),
        "mcp": _mcp_manifest(api_base),
        "next_commands": [
            f"python3 codee.py task create {root} --title \"Make my first Codee lane live\" --service codeeqr --prompt \"Create, verify, connect, and prepare hosted activation for the first QRCodee lane.\"",
            f"python3 codee.py verify {root} --service codeeqr",
            f"python3 codee.py connect {root} --service codeeqr --email owner@example.com",
            f"python3 codee.py activate {root} --service codeeqr",
        ],
    }


def _platform_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee Platform Parity Report",
        "",
        str(payload.get("summary") or ""),
        "",
        "## Gaps Closed",
        "",
    ]
    for item in payload.get("gaps_closed") or []:
        lines.append(f"- {item.get('feature')}: {item.get('codee_status')} - `{item.get('command')}`")
    lines.extend(["", "## Next Commands", ""])
    for item in payload.get("next_commands") or []:
        lines.append(f"```bash\n{item}\n```")
    lines.append("")
    return "\n".join(lines)


def _agent_core_manifest(
    root: Path,
    *,
    business: str = "",
    service: str = "codee-service",
    mode: str = "suggest",
    api_base: str = DEFAULT_API_BASE,
) -> dict[str, Any]:
    manifest = _load_manifest(root)
    business_name = str(business or manifest.get("business") or "Codee Client").strip()
    service_name = _normalize_service(str(service or manifest.get("service") or "codee-service"))
    return {
        "schema": "codee.agent-core.v1",
        "version": VERSION,
        "created_at": _now(),
        "root": str(root),
        "business": business_name,
        "service": service_name,
        "permission_mode": mode,
        "api_base": str(api_base or DEFAULT_API_BASE).rstrip("/"),
        "codee_agi": CODEE_AGI_DOCTRINE,
        "accessibility_defaults": CODEE_ACCESSIBILITY_DEFAULTS,
        "capability_statement": "Codee AGI means Applied Good Intelligence: a governed business agent core that uses science, technology, ethics, society, capital creation, proof, and mission reinvestment to help users build useful income lanes.",
        "agi_claim_policy": [
            "When using AGI in Codee public copy, define it as Applied Good Intelligence.",
            "Do not claim Codee is unrestricted human-level artificial general intelligence.",
            "Describe the technical side as an agent operating loop: goals, memory, tools, feedback, verification, and guarded action.",
            "Keep every payment, deployment, private credential, and owner operation behind explicit permission or backend gates.",
            "If the user asks for impossible or unsafe autonomy, downgrade to a safe plan, support packet, or human approval step.",
        ],
        "operating_loop": CODEE_AGENT_CORE_LOOP,
        "tools": CODEE_AGENT_CORE_TOOLS,
        "guardrails": [
            "Never store card numbers or Stripe secret keys in the downloaded CLI.",
            "Never promise revenue, legal outcomes, medical outcomes, or guaranteed platform behavior.",
            "Never edit outside the chosen workspace without owner approval.",
            "Never deploy, purge, or bill without an approved backend or owner flow.",
            "Always write proof reports after scans, tasks, support packets, and heartbeat checks.",
        ],
        "upgrade_experience": [
            "After download, the user runs `codee heartbeat` to see what is alive and what is missing.",
            "If identity or platform files are missing, Codee recommends `init` and `platform --write`.",
            "If the folder has no sellable lane, Codee recommends QRCodee first.",
            "If the route is broken, Codee recommends scan repair before promotion.",
            "If the user needs hosting or done-for-you help, Codee offers Stripe-hosted upgrade, invoice, delivery room, and support.",
        ],
        "limits": [
            "No local large language model is bundled in the CLI.",
            "No self-improvement outside the installed code and backend release cycle.",
            "No unrestricted shell, cloud, payment, social, or email access for public downloads.",
            "No guarantee that a business will make money without offer quality, traffic, trust, and follow-through.",
        ],
        "next_commands": [
            f"python3 codee.py heartbeat {root} --service {service_name}",
            f"python3 codee.py platform {root} --business \"{business_name}\" --service {service_name} --write --force",
            f"python3 codee.py task create {root} --title \"Make {business_name} live\" --service {service_name} --prompt \"Create, verify, connect, and prepare the first business lane.\"",
            f"python3 codee.py verify {root} --service {service_name}",
        ],
    }


def _agent_core_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee AGI Core",
        "",
        str(payload.get("capability_statement") or ""),
        "",
        f"Business: {payload.get('business')}",
        f"Service: {payload.get('service')}",
        f"Permission mode: {payload.get('permission_mode')}",
        "",
        "## Applied Good Intelligence",
        "",
    ]
    agi = payload.get("codee_agi") if isinstance(payload.get("codee_agi"), dict) else {}
    if agi:
        lines.append(f"Meaning: {agi.get('meaning')}")
        lines.append("")
        lines.append(str(agi.get("plain_language") or ""))
        lines.append("")
        for item in agi.get("domains") or []:
            lines.append(f"- {item}")
        lines.append("")
        lines.append(str(agi.get("mission_rule") or ""))
    lines.extend([
        "",
        "## AGI Claim Policy",
        "",
    ])
    for item in payload.get("agi_claim_policy") or []:
        lines.append(f"- {item}")
    lines.extend(["", "## Operating Loop", ""])
    for item in payload.get("operating_loop") or []:
        commands = ", ".join(str(command) for command in item.get("commands") or [])
        lines.append(f"- {item.get('step')}: {item.get('purpose')} Commands: {commands}")
    lines.extend(["", "## Hardcoded Tools", ""])
    for item in payload.get("tools") or []:
        visibility = "public" if item.get("public") else "owner-gated"
        lines.append(f"- {item.get('tool')} ({visibility}): {item.get('why')}")
    lines.extend(["", "## Guardrails", ""])
    for item in payload.get("guardrails") or []:
        lines.append(f"- {item}")
    lines.extend(["", "## Limits", ""])
    for item in payload.get("limits") or []:
        lines.append(f"- {item}")
    lines.extend(["", "## Next Commands", ""])
    for command in payload.get("next_commands") or []:
        lines.append(f"```bash\n{command}\n```")
    return "\n".join(lines) + "\n"


def _agent_core_upgrade_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee User Upgrade Path",
        "",
        "This is the public download path that lets a user feel supported without exposing owner systems.",
        "",
    ]
    for item in payload.get("upgrade_experience") or []:
        lines.append(f"- {item}")
    lines.extend(
        [
            "",
            "## Paid Unlocks",
            "",
            "- Hosted activation through Codee backend after Stripe payment proof.",
            "- Delivery room and workbench tied to the same Codee user/workspace IDs.",
            "- Six-hour scans, support packets, route proof, and done-for-you repair when included in the plan.",
            "- Owner-gated deploy, storage, Stripe webhook, and social posting systems stay private.",
            "",
        ]
    )
    return "\n".join(lines)


def _task_id(title: str, service: str, root: Path) -> str:
    return "ctask_" + hashlib.sha256(f"{title}:{service}:{root}:{time.time_ns()}".encode("utf-8")).hexdigest()[:20]


def _tasks_dir(root: Path) -> Path:
    return root / ".codee" / "tasks"


def _task_path(root: Path, task_id: str) -> Path:
    return _tasks_dir(root) / f"{task_id}.json"


def _read_task(root: Path, task_id: str) -> dict[str, Any]:
    path = _task_path(root, task_id)
    if not path.exists():
        return {}
    return _read_json_if_exists(path)


def _list_tasks(root: Path) -> list[dict[str, Any]]:
    tasks = []
    task_dir = _tasks_dir(root)
    if not task_dir.exists():
        return []
    for path in sorted(task_dir.glob("ctask_*.json"), key=lambda item: item.stat().st_mtime, reverse=True):
        payload = _read_json_if_exists(path)
        if payload:
            payload.setdefault("path", str(path))
            tasks.append(payload)
    return tasks


def _task_markdown(payload: dict[str, Any]) -> str:
    lines = [
        f"# Codee Task: {payload.get('title')}",
        "",
        f"Task ID: {payload.get('task_id')}",
        f"Status: {payload.get('status')}",
        f"Service: {payload.get('service')}",
        f"Agent: {payload.get('agent')}",
        "",
        "## Prompt",
        "",
        str(payload.get("prompt") or ""),
        "",
        "## Acceptance Criteria",
        "",
    ]
    for item in payload.get("acceptance") or []:
        lines.append(f"- {item}")
    lines.extend(["", "## Result", "", str(payload.get("result") or "Pending."), ""])
    return "\n".join(lines)


def _write_platform_layer(
    root: Path,
    *,
    mode: str = "suggest",
    business: str = "",
    service: str = "codee-service",
    api_base: str = DEFAULT_API_BASE,
    force: bool = False,
) -> dict[str, Any]:
    root.mkdir(parents=True, exist_ok=True)
    payload = _platform_manifest(root, permission_mode=mode, api_base=api_base)
    memory = _memory_manifest(root, business=business, service=service)
    agent_core = _agent_core_manifest(root, business=business, service=service, mode=mode, api_base=api_base)
    user_memory = _ensure_user_memory_vault(root, business=business, service=service, force=force)
    accessibility = _accessibility_manifest(root, business=business, service=service)
    writes: dict[str, bool] = {
        "platform_parity": _write_json(root / ".codee" / "platform-parity.json", payload, force=force),
        "platform_markdown": _write_text(root / ".codee" / "PLATFORM_PARITY.md", _platform_markdown(payload), force=force),
        "permissions": _write_json(root / ".codee" / "permissions.json", payload["permissions"], force=force),
        "permissions_markdown": _write_text(root / ".codee" / "PERMISSIONS.md", _permissions_markdown(payload["permissions"]), force=force),
        "agents": _write_json(root / ".codee" / "agents.json", payload["agents"], force=force),
        "agents_markdown": _write_text(root / ".codee" / "AGENTS.md", _agents_markdown(payload["agents"]), force=force),
        "mcp": _write_json(root / ".codee" / "mcp.json", payload["mcp"], force=force),
        "mcp_markdown": _write_text(root / ".codee" / "MCP.md", _mcp_markdown(payload["mcp"]), force=force),
        "memory": _write_json(root / ".codee" / "memory.json", memory, force=force),
        "codee_markdown": _write_text(root / "CODEE.md", _memory_markdown(memory), force=force),
        "root_agents_markdown": _write_text(root / "AGENTS.md", _agents_markdown(payload["agents"]), force=force),
        "hooks": _write_json(root / ".codee" / "hooks.json", _hook_manifest(), force=force),
        "connectors": _write_json(root / ".codee" / "connectors.json", _connector_manifest(), force=force),
        "agent_core": _write_json(root / ".codee" / "agent-core.json", agent_core, force=force),
        "agent_core_markdown": _write_text(root / ".codee" / "AGENT_CORE.md", _agent_core_markdown(agent_core), force=force),
        "upgrade_path": _write_text(root / ".codee" / "UPGRADE_PATH.md", _agent_core_upgrade_markdown(agent_core), force=force),
        "user_memory": True,
        "accessibility": _write_json(root / ".codee" / "accessibility.json", accessibility, force=force),
        "accessibility_markdown": _write_text(root / ".codee" / "ACCESSIBILITY.md", _accessibility_markdown(accessibility), force=force),
    }
    agents_dir = root / ".codee" / "agents"
    for agent in payload["agents"].get("agents") or []:
        key = f"agent_{agent.get('id')}"
        writes[key] = _write_text(agents_dir / f"{agent.get('id')}.md", _agent_profile_markdown(agent), force=force)
    return {"payload": payload, "memory": memory, "agent_core": agent_core, "user_memory": user_memory, "accessibility": accessibility, "writes": writes}


def _task_run_markdown(report: dict[str, Any]) -> str:
    lines = [
        "# Codee Task Run Proof",
        "",
        f"Task ID: {report.get('task_id')}",
        f"Status: {report.get('status')}",
        f"Service: {report.get('service')}",
        f"Agent: {report.get('agent')}",
        f"Result: {report.get('result')}",
        "",
        "## Checks",
        "",
    ]
    for item in report.get("checks") or []:
        marker = "PASS" if item.get("ok") else str(item.get("severity") or "warn").upper()
        proof = f" Proof: {item.get('proof')}" if item.get("proof") else ""
        lines.append(f"- {marker}: {item.get('label')} - {item.get('copy')}{proof}")
    routes = report.get("route_results") if isinstance(report.get("route_results"), list) else []
    if routes:
        lines.extend(["", "## Route Proof", ""])
        for item in routes:
            marker = "PASS" if item.get("ok") else "FAIL"
            lines.append(f"- {marker}: {item.get('url')} status={item.get('status')} transport={item.get('transport')}")
    lines.extend(["", "## Next Commands", ""])
    for command in report.get("next_commands") or []:
        lines.append(f"```bash\n{command}\n```")
    return "\n".join(lines) + "\n"


def _task_run_report(
    root: Path,
    task: dict[str, Any],
    args: argparse.Namespace,
    *,
    platform_result: dict[str, Any] | None = None,
) -> tuple[dict[str, Any], Path]:
    service = _normalize_service(str(task.get("service") or getattr(args, "service", "") or "codee-cli"))
    inventory = _folder_inventory(root)
    latest_verify = _read_json_if_exists(root / ".codee" / "reports" / "latest-codee-verify.json")
    latest_scan = _read_json_if_exists(root / ".codee" / "reports" / "latest-route-scan.json")
    platform_files = {
        "platform": root / ".codee" / "platform-parity.json",
        "permissions": root / ".codee" / "permissions.json",
        "agents": root / ".codee" / "agents.json",
        "mcp": root / ".codee" / "mcp.json",
        "hooks": root / ".codee" / "hooks.json",
        "connectors": root / ".codee" / "connectors.json",
        "memory": root / ".codee" / "memory.json",
        "agent_core": root / ".codee" / "agent-core.json",
        "user_memory": root / ".codee" / "user-memory.json",
        "accessibility": root / ".codee" / "accessibility.json",
        "codee_md": root / "CODEE.md",
        "agents_md": root / "AGENTS.md",
    }
    checks: list[dict[str, Any]] = []

    def add_check(key: str, label: str, ok: bool, copy: str, *, severity: str = "fail", proof: str = "") -> None:
        checks.append({"id": key, "label": label, "ok": bool(ok), "severity": severity, "copy": copy, "proof": proof})

    add_check("task-file", "Task file exists", bool(task.get("task_id")), "The request has a stable task ID for local and backend tracking.", proof=str(_task_path(root, str(task.get("task_id") or ""))))
    add_check("folder", "Folder exists", bool(inventory.get("exists")), "The workspace can be inspected by Codee.", proof=str(root))
    add_check("index", "index.html exists", bool(inventory.get("has_index")), "The folder has a public entry file.")
    add_check("service", "Service lane selected", bool(service), f"Task is assigned to {service}.")
    missing_platform = [name for name, path in platform_files.items() if not path.exists()]
    add_check("platform-layer", "Platform layer installed", not missing_platform, "Tasks, agents, memory, MCP-style connectors, hooks, and permissions are present.", severity="warn", proof=", ".join(missing_platform[:5]))
    add_check("agents", "Agent profiles installed", (root / ".codee" / "agents.json").exists() and bool(list((root / ".codee" / "agents").glob("*.md"))), "Focused agent files can guide explorer, builder, auditor, launch, and owner workflows.", severity="warn")
    add_check("memory", "Project memory installed", (root / "CODEE.md").exists() and (root / "AGENTS.md").exists(), "The folder carries reusable rules instead of relying on one chat session.", severity="warn")
    add_check("user-memory", "User memory vault installed", (root / ".codee" / "user-memory.json").exists(), "The user has a long-term local memory vault keyed by Codee user ID.", severity="warn")
    add_check("accessibility", "Accessibility rules installed", (root / ".codee" / "accessibility.json").exists(), "Veteran-first course and interface rules are installed.", severity="warn")
    add_check("connectors", "Connector map installed", (root / ".codee" / "mcp.json").exists() and (root / ".codee" / "connectors.json").exists(), "Backend, Stripe, hosting, storage, WordPress, and Metricool boundaries are explicit.", severity="warn")
    if latest_verify:
        add_check("latest-verify", "Latest verify report exists", bool(latest_verify.get("ok")), f"Verify report has {latest_verify.get('fail_count', 0)} fails and {latest_verify.get('warn_count', 0)} warnings.", severity="warn", proof=str(root / ".codee" / "reports" / "latest-codee-verify.json"))
    else:
        add_check("latest-verify", "Latest verify report exists", False, "Run `codee verify` or use `codee task run --verify` before launch.", severity="warn")
    if latest_scan:
        add_check("latest-scan", "Latest route scan exists", bool(latest_scan.get("ok")), f"Route scan checked {len(latest_scan.get('checks') or [])} targets.", severity="warn", proof=str(root / ".codee" / "reports" / "latest-route-scan.json"))

    target_urls = [str(item).strip() for item in (getattr(args, "url", None) or []) if str(item).strip()]
    target_url = str(getattr(args, "target_url", "") or task.get("target_url") or "").strip()
    if target_url:
        target_urls.append(target_url)
    course_packet = _read_json_if_exists(root / "codee-course.json")
    if course_packet.get("target_url"):
        target_urls.append(str(course_packet.get("target_url")))
    route_results: list[dict[str, Any]] = []
    if bool(getattr(args, "route_check", False)):
        seen: set[str] = set()
        for url in target_urls:
            if not url.startswith(("http://", "https://")) or url in seen:
                continue
            seen.add(url)
            route_results.append(_route_check({"name": "task-target", "url": url, "expected": [200, 301, 302, 307, 308]}, float(getattr(args, "timeout", 30) or 30)))
        if route_results:
            add_check("route-check", "Route check passed", all(item.get("ok") for item in route_results), "Public target URLs open without 404 or 500 status.", proof=", ".join(str(item.get("status")) for item in route_results))
        else:
            add_check("route-check", "Route check passed", False, "No HTTP target URL was available for task route proof.", severity="warn")

    fail_count = sum(1 for item in checks if not item.get("ok") and item.get("severity") == "fail")
    warn_count = sum(1 for item in checks if not item.get("ok") and item.get("severity") != "fail")
    ok = fail_count == 0 and (warn_count == 0 if bool(getattr(args, "strict", False)) else True)
    status = "completed" if ok else "needs_work"
    result = "Codee task runner completed folder, platform, and proof checks." if ok else "Codee task runner found launch blockers."
    report = {
        "ok": ok,
        "schema": "codee.task_run.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "task_id": task.get("task_id"),
        "title": task.get("title"),
        "status": status,
        "result": result,
        "service": service,
        "agent": task.get("agent") or "builder",
        "permission_mode": task.get("permission_mode") or "suggest",
        "workspace_id": task.get("workspace_id") or root.name,
        "codee_user_id": task.get("codee_user_id") or "",
        "folder_inventory": inventory,
        "workspace_fingerprint": _workspace_fingerprint(root, inventory),
        "checks": checks,
        "fail_count": fail_count,
        "warn_count": warn_count,
        "route_results": route_results,
        "latest_verify_report": latest_verify,
        "platform_write": platform_result or {},
        "artifacts": {
            "task": str(_task_path(root, str(task.get("task_id") or ""))),
            "report": str(root / ".codee" / "reports" / "latest-task-run.json"),
            "markdown": str(root / ".codee" / "TASK_RUN.md"),
            "verify": str(root / ".codee" / "reports" / "latest-codee-verify.json"),
        },
        "next_commands": [
            f"python3 codee.py task status {root} --task-id {task.get('task_id')} --live",
            f"python3 codee.py verify {root} --service {service} --route-check",
            f"python3 codee.py task run {root} --task-id {task.get('task_id')} --send-result",
            f"python3 codee.py support {root} --service {service} --message \"Review task {task.get('task_id')} proof and prepare the next activation step.\" --submit",
        ],
    }
    report_path = _write_report(root, "latest-task-run.json", report)
    _write_text(root / ".codee" / "TASK_RUN.md", _task_run_markdown(report), force=True)
    return report | {"report": str(report_path)}, report_path


def _activation_timeline(
    *,
    status: str,
    payment_verified: bool = False,
    has_assets: bool = False,
    hosted_url: str = "",
    backend_connected: bool | None = None,
) -> list[dict[str, Any]]:
    clean_status = str(status or "").strip().lower()
    paid = bool(payment_verified or clean_status in {"paid", "ready", "delivered", "activated"})
    connected = bool(backend_connected) if backend_connected is not None else clean_status not in {"", "local_only"}
    uploaded = bool(has_assets or clean_status in {"assets_received", "pending_payment_verification", "ready", "delivered", "activated"})
    ready = bool(hosted_url or clean_status in {"ready", "delivered", "activated"})
    return [
        {
            "id": "folder-generated",
            "label": "Folder generated",
            "status": "complete",
            "copy": "The local Codee folder has an index file and course packet.",
        },
        {
            "id": "backend-connected",
            "label": "Backend connected",
            "status": "complete" if connected else "pending",
            "copy": "Codee backend has the workspace ID, user ID, service lane, and activation packet.",
        },
        {
            "id": "assets-uploaded",
            "label": "Assets uploaded",
            "status": "complete" if uploaded else "pending",
            "copy": "Logo, flyer, guidebook, CTA, or brand assets are ready for fulfillment.",
        },
        {
            "id": "payment-verified",
            "label": "Payment verified",
            "status": "complete" if paid else "locked",
            "copy": "Stripe/payment verification unlocks hosted activation.",
        },
        {
            "id": "hosted-link",
            "label": "Hosted link created",
            "status": "complete" if ready else "locked",
            "copy": "The public client link stays locked until assets and payment are verified.",
        },
        {
            "id": "scan-passed",
            "label": "Scan passed",
            "status": "complete" if ready else "pending",
            "copy": "Codee scan proof confirms no 404s before the client calls it ready.",
        },
    ]


def _timeline_markdown(timeline: list[dict[str, Any]]) -> str:
    lines = ["# Codee Activation Timeline", ""]
    for item in timeline:
        lines.append(f"- {item.get('label')}: {item.get('status')} - {item.get('copy')}")
    lines.append("")
    return "\n".join(lines)


def _course_by_id(course_id: str) -> dict[str, Any]:
    clean = str(course_id or "").strip().lower()
    for group in COURSE_CATALOG.values():
        for item in group:
            if str(item.get("id") or "").lower() == clean:
                return item
    raise SystemExit(f"Unknown course '{course_id}'. Use: qrcodee, codeeflyer, codeeapp.")


def _html(value: object) -> str:
    return html.escape(str(value or ""), quote=True)


def _course_service_id(course: dict[str, Any]) -> str:
    return str(course.get("activation_service") or course.get("id") or "codee-service").strip().lower()


def _course_paid_intake_url(course: dict[str, Any], *, business: str, target_url: str, source: str = "codee-cli-course") -> str:
    service = _course_service_id(course)
    query = {
        "service": service,
        "autostart": "1",
        "source": source,
        "business": business or "Codee Client",
        "target_url": target_url or "https://codee.chat",
    }
    if service == "codeeflyer":
        query["tier"] = "100"
    if service == "codeeapp250":
        query["tier"] = "250"
    return f"{DEFAULT_API_BASE}/codee-chat.html?{urllib.parse.urlencode(query)}"


def _course_upload_needs(course: dict[str, Any]) -> list[str]:
    needs = course.get("upload_needs")
    if isinstance(needs, list) and needs:
        return [str(item) for item in needs if str(item).strip()]
    return ["business name", "target URL", "logo or image", "CTA"]


def _course_starter_html(course: dict[str, Any], *, business: str, target_url: str) -> str:
    name = str(course.get("name") or "Codee Course")
    lesson = str(course.get("lesson") or course.get("why") or "")
    target = target_url or "https://codee.chat"
    business_name = business or "My Business"
    course_id = str(course.get("id") or "codee").strip().lower()
    service_id = _course_service_id(course)
    activate_url = _course_paid_intake_url(course, business=business_name, target_url=target)
    needs = "".join(f"<li>{_html(item)}</li>" for item in _course_upload_needs(course))
    action_label = {
        "qrcodee": "Open target route",
        "codeeflyer": "Open flyer CTA",
        "codeeapp": "Open buyer or download path",
    }.get(course_id, "Open target route")
    hero_kicker = {
        "qrcodee": "Custom QR image lab",
        "codeeflyer": "Hosted flyer lab",
        "codeeapp": "Guidebook app lab",
    }.get(course_id, "Course lab")
    visual = ""
    if course_id == "qrcodee":
        visual = """
      <div class="qr-stage" aria-label="QRCodee preview">
        <div class="qr-card">
          <div class="qr-grid"></div>
          <div class="qr-logo">C</div>
        </div>
      </div>
"""
    elif course_id == "codeeflyer":
        visual = f"""
      <div class="flyer-stage" aria-label="Codee Flyer preview">
        <div class="flyer-card">
          <span>CodeeFlyer</span>
          <h2>{_html(business_name)}</h2>
          <p>One offer. One CTA. One QR path.</p>
          <div class="mini-qr"></div>
        </div>
      </div>
"""
    elif course_id == "codeeapp":
        visual = f"""
      <div class="app-stage" aria-label="Codee App preview">
        <div class="book-cover">
          <span>CodeeApp 250</span>
          <strong>{_html(business_name)}</strong>
        </div>
        <div class="app-qr"></div>
      </div>
"""
    else:
        visual = """
      <div class="qr-stage" aria-label="Codee preview"><div class="qr-card"><div class="qr-grid"></div><div class="qr-logo">C</div></div></div>
"""
    return f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>{_html(name)} Starter | {_html(business_name)}</title>
  <style>
    * {{ box-sizing: border-box; }}
    :root {{ color-scheme: dark; --gold:#d7b36a; --green:#8fd6aa; --ink:#071018; --panel:rgba(10,16,24,.76); --line:rgba(255,255,255,.16); }}
    body {{
      margin: 0; min-height: 100vh; font-family: Arial, sans-serif; color: #f8fafc;
      background:
        radial-gradient(circle at 70% 18%, rgba(143,214,170,.22), transparent 32rem),
        radial-gradient(circle at 20% 80%, rgba(215,179,106,.18), transparent 30rem),
        linear-gradient(135deg, #06090f 0%, #101827 52%, #070a0f 100%);
    }}
    main {{ width: min(1080px, calc(100% - 24px)); margin: 0 auto; min-height: 100vh; padding: 28px 0; display: grid; align-content: center; gap: 16px; }}
    .hero {{ border: 1px solid var(--line); border-radius: 28px; padding: clamp(20px, 4vw, 36px); background: linear-gradient(180deg, rgba(18,28,40,.86), rgba(8,12,18,.9)); box-shadow: 0 28px 90px rgba(0,0,0,.38); display: grid; grid-template-columns: minmax(0,1.05fr) minmax(280px,.95fr); gap: 24px; align-items: center; }}
    .panel {{ border: 1px solid var(--line); border-radius: 20px; padding: 18px; background: rgba(255,255,255,.055); }}
    .eyebrow {{ color: var(--gold); font-weight: 900; letter-spacing: .12em; text-transform: uppercase; font-size: .75rem; }}
    h1 {{ margin: 8px 0 12px; font-size: clamp(2.5rem, 7vw, 5.5rem); line-height: .88; letter-spacing: 0; }}
    h2 {{ margin: 0 0 10px; }}
    p, li {{ color: #d3dde8; line-height: 1.42; font-weight: 760; font-size: clamp(1.05rem, 2.2vw, 1.22rem); max-width: 62ch; }}
    ul {{ padding-left: 1.1rem; margin: 10px 0 0; }}
    .actions {{ display: flex; flex-wrap: wrap; gap: 10px; margin-top: 20px; }}
    .btn {{ min-height: 50px; display: inline-flex; align-items: center; justify-content: center; padding: 0 18px; border-radius: 999px; color: var(--ink); background: linear-gradient(135deg,var(--gold),var(--green)); text-decoration: none; font-weight: 900; border: 1px solid rgba(255,255,255,.28); }}
    .btn.ghost {{ color: #f8fafc; background: rgba(255,255,255,.08); backdrop-filter: blur(16px); }}
    .meta {{ display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }}
    .meta div {{ min-height: 76px; border: 1px solid var(--line); border-radius: 16px; padding: 12px; background: rgba(255,255,255,.05); }}
    .meta span, .flyer-card span, .book-cover span {{ display:block; color: var(--gold); font-size:.74rem; font-weight:900; text-transform:uppercase; letter-spacing:.1em; }}
    .meta strong {{ display:block; margin-top:6px; }}
    .qr-stage, .flyer-stage, .app-stage {{ min-height: 440px; display:flex; align-items:center; justify-content:center; border-radius: 28px; background: radial-gradient(circle, rgba(255,255,255,.12), rgba(255,255,255,.025)); border: 1px solid var(--line); overflow:hidden; }}
    .qr-card {{ width: min(74vw, 360px); aspect-ratio: 1; border-radius: 32px; position: relative; background: rgba(255,255,255,.94); padding: 22px; box-shadow: 0 0 70px rgba(143,214,170,.22); }}
    .qr-grid {{ width:100%; height:100%; border-radius: 18px; background:
      linear-gradient(90deg, #131820 14px, transparent 14px) 0 0/38px 38px,
      linear-gradient(#131820 14px, transparent 14px) 0 0/38px 38px,
      radial-gradient(circle at 20% 20%, #131820 0 46px, transparent 48px),
      radial-gradient(circle at 80% 20%, #131820 0 46px, transparent 48px),
      radial-gradient(circle at 20% 80%, #131820 0 46px, transparent 48px),
      #f8fafc; }}
    .qr-logo {{ position:absolute; inset:50% auto auto 50%; transform:translate(-50%,-50%); width:92px; aspect-ratio:1; border-radius:28px; display:grid; place-items:center; background:linear-gradient(135deg,#101827,#2a2012); color:var(--gold); font-size:3rem; font-weight:900; box-shadow:0 0 0 10px #f8fafc; }}
    .flyer-card {{ width:min(74vw, 380px); min-height: 500px; border-radius: 28px; padding: 26px; background: linear-gradient(160deg, rgba(10,16,24,.98), rgba(38,30,15,.94)); border:1px solid rgba(215,179,106,.45); display:grid; align-content:end; gap:12px; box-shadow:0 28px 80px rgba(0,0,0,.38); }}
    .flyer-card h2 {{ font-size: clamp(2.2rem, 6vw, 4rem); line-height:.9; }}
    .mini-qr, .app-qr {{ width: 94px; aspect-ratio:1; border-radius: 18px; background: repeating-linear-gradient(45deg,#111827 0 8px,#f8fafc 8px 16px); border:8px solid #f8fafc; justify-self:start; }}
    .app-stage {{ gap:22px; flex-wrap:wrap; }}
    .book-cover {{ width:min(60vw, 300px); min-height: 420px; border-radius: 24px; padding: 24px; display:grid; align-content:space-between; background: linear-gradient(150deg,#2b1f12,#111827 58%,#1b3d32); border:1px solid rgba(215,179,106,.45); box-shadow:0 0 70px rgba(215,179,106,.18); }}
    .book-cover strong {{ font-size: clamp(2rem, 5vw, 3.4rem); line-height:.9; }}
    @media (max-width: 800px) {{ .hero {{ grid-template-columns:1fr; }} .meta {{ grid-template-columns:1fr; }} .qr-stage, .flyer-stage, .app-stage {{ min-height:360px; }} }}
  </style>
</head>
<body data-codee-course="{_html(course_id)}" data-codee-service="{_html(service_id)}">
  <main>
    <section class="hero">
      <div>
        <p class="eyebrow">{_html(hero_kicker)}</p>
        <h1>{_html(business_name)}</h1>
        <p><strong>{_html(name)}</strong></p>
        <p>Learn one action. Build one folder. Save proof.</p>
        <div class="actions">
          <a class="btn" href="{_html(target)}">{_html(action_label)}</a>
          <a class="btn ghost" href="{_html(activate_url)}">Pay and activate hosted link</a>
        </div>
      </div>
{visual}
    </section>
    <section class="panel">
      <div class="meta">
        <div><span>Status</span><strong>Local course site generated</strong></div>
        <div><span>Activation</span><strong>Locked until payment and upload are ready</strong></div>
        <div><span>Backend</span><strong>Run codee connect, then codee activate</strong></div>
      </div>
    </section>
    <section class="panel">
      <p class="eyebrow">Upload needed</p>
      <ul>{needs}</ul>
    </section>
  </main>
</body>
</html>
"""


def _delivery_room_url(manifest: dict[str, Any], *, service: str = "") -> str:
    query = {
        "client_id": str(manifest.get("client_id") or "codee-client"),
        "workspace_id": str(manifest.get("client_id") or "codee-client"),
        "codee_user_id": str(manifest.get("codee_user_id") or ""),
        "service": str(service or "codee-support"),
        "source": "codee-cli",
    }
    return f"{DEFAULT_API_BASE}/codee-delivery.html?{urllib.parse.urlencode(query)}"


def _workbench_url(manifest: dict[str, Any], *, service: str = "") -> str:
    query = {
        "client_id": str(manifest.get("client_id") or "codee-client"),
        "workspace_id": str(manifest.get("client_id") or "codee-client"),
        "codee_user_id": str(manifest.get("codee_user_id") or ""),
        "business": str(manifest.get("business") or ""),
        "service": str(service or "codee-support"),
        "source": "codee-cli",
    }
    return f"{DEFAULT_API_BASE}/codee-workbench.html?{urllib.parse.urlencode(query)}"


def _read_json_if_exists(path: Path) -> dict[str, Any]:
    if not path.exists():
        return {}
    try:
        parsed = json.loads(path.read_text(encoding="utf-8"))
    except Exception as exc:
        return {"ok": False, "error": f"{type(exc).__name__}: {str(exc)[:160]}", "path": str(path)}
    return parsed if isinstance(parsed, dict) else {"ok": False, "error": "json_not_object", "path": str(path)}


def _safe_time_slug() -> str:
    return dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")


def _run_check(command: list[str], *, timeout: float = 12) -> dict[str, Any]:
    try:
        proc = subprocess.run(command, text=True, capture_output=True, timeout=timeout)
    except FileNotFoundError:
        return {"ok": False, "error": "not_found", "command": command}
    except Exception as exc:
        return {"ok": False, "error": f"{type(exc).__name__}: {str(exc)[:160]}", "command": command}
    output = (proc.stdout or proc.stderr or "").strip()
    return {
        "ok": proc.returncode == 0,
        "returncode": proc.returncode,
        "command": command,
        "output": output[:400],
        "error": (proc.stderr or "").strip()[:400] if proc.returncode else "",
    }


def _skill_by_id(skill_id: str) -> dict[str, Any]:
    clean = str(skill_id or "").strip().lower()
    for item in SKILL_CATALOG:
        if str(item.get("id") or "").lower() == clean:
            return item
    raise SystemExit(f"Unknown skill '{skill_id}'. Run `codee skills` to list available skills.")


def _requirement_status(name: str) -> dict[str, Any]:
    clean = str(name or "").strip()
    lower = clean.lower()
    if lower in {"codee backend", "stripe account", "private oauth or app connector", "metricool credentials"}:
        return {"name": clean, "ok": False, "kind": "credential", "note": "Handled by Codee owner/backend, not bundled in the public CLI."}
    if lower == "playwright":
        npx_path = shutil.which("npx")
        if not npx_path:
            return {"name": clean, "ok": False, "kind": "npx-package", "note": "Install Node.js/npm first."}
        check = _run_check([npx_path, "--no-install", "playwright", "--version"])
        check["name"] = clean
        check["kind"] = "npx-package"
        if not check["ok"]:
            check["install_hint"] = "Run `npm install -D playwright` in the workspace, then `npx playwright install chromium` if browsers are missing."
        return check
    command_map = {
        "python3": ["python3", "--version"],
        "node": ["node", "--version"],
        "npx": ["npx", "--version"],
        "firebase": ["firebase", "--version"],
        "gcloud": ["gcloud", "--version"],
    }
    command = command_map.get(lower)
    if command:
        found = shutil.which(command[0])
        if not found:
            return {"name": clean, "ok": False, "kind": "command", "command": command, "error": "not_found"}
        check = _run_check(command)
        check["name"] = clean
        check["kind"] = "command"
        check["path"] = found
        return check
    return {"name": clean, "ok": True, "kind": "logical", "note": "No local binary check required."}


def _skill_status(skill: dict[str, Any]) -> dict[str, Any]:
    checks = [_requirement_status(item) for item in (skill.get("requires") or [])]
    credential_gated = any(item.get("kind") == "credential" for item in checks)
    return {
        "id": skill.get("id"),
        "name": skill.get("name"),
        "access": skill.get("access"),
        "status": skill.get("status"),
        "available": bool(checks and all(item.get("ok") for item in checks)) if not credential_gated else False,
        "credential_gated": credential_gated,
        "checks": checks,
    }


def _build_skill_policy(*, preset: str, enabled_extra: list[str] | None = None, disabled: list[str] | None = None) -> dict[str, Any]:
    clean_preset = str(preset or "public").strip().lower()
    enabled_extra = [str(item).strip().lower() for item in (enabled_extra or []) if str(item).strip()]
    disabled_set = {str(item).strip().lower() for item in (disabled or []) if str(item).strip()}
    built_in_public = [
        str(item["id"])
        for item in SKILL_CATALOG
        if str(item.get("access") or "") == "public" and str(item.get("status") or "") == "built-in"
    ]
    optional_public = [
        str(item["id"])
        for item in SKILL_CATALOG
        if str(item.get("access") or "").startswith("public-") and str(item.get("status") or "").startswith("optional")
    ]
    backend_gated = [
        str(item["id"])
        for item in SKILL_CATALOG
        if str(item.get("access") or "") in {"backend", "public-plus-backend"}
    ]
    owner_gated = [
        str(item["id"])
        for item in SKILL_CATALOG
        if str(item.get("access") or "").startswith("owner")
    ]
    enabled = list(built_in_public)
    if clean_preset in {"operator", "owner"}:
        enabled.extend(optional_public)
        enabled.append("backend-connect")
        enabled.append("support-room")
    if clean_preset == "owner":
        enabled.extend(["payment-stripe"])
    enabled.extend(enabled_extra)
    enabled = [item for item in dict.fromkeys(enabled) if item not in disabled_set]
    unknown = [item for item in enabled if not any(str(skill.get("id") or "") == item for skill in SKILL_CATALOG)]
    if unknown:
        raise SystemExit(f"Unknown skill(s): {', '.join(unknown)}. Run `codee skills --access all`.")
    return {
        "schema": "codee.skills.policy.v1",
        "version": VERSION,
        "created_at": _now(),
        "preset": clean_preset,
        "enabled": enabled,
        "disabled": sorted(disabled_set),
        "built_in_public": built_in_public,
        "optional_public": optional_public,
        "backend_gated": backend_gated,
        "owner_gated": owner_gated,
        "guardrails": [
            "Public skills may run without private credentials.",
            "Optional public skills must be detected before use.",
            "Backend skills must call Codee backend or Stripe-hosted pages instead of storing secrets locally.",
            "Owner/private skills require explicit owner authentication and must not be bundled into public downloads.",
            "Every skill run must leave proof under .codee/reports or .codee/screenshots.",
        ],
        "proof_files": {
            "skill_check": ".codee/reports/latest-skill-check.json",
            "browser_scan": ".codee/reports/latest-browser-scan.json",
            "route_scan": ".codee/reports/latest-route-scan.json",
            "support_request": ".codee/reports/latest-support-request.json",
        },
    }


def _skill_policy_markdown(policy: dict[str, Any]) -> str:
    enabled = "\n".join(f"- {item}" for item in (policy.get("enabled") or [])) or "- none"
    backend = "\n".join(f"- {item}" for item in (policy.get("backend_gated") or [])) or "- none"
    owner = "\n".join(f"- {item}" for item in (policy.get("owner_gated") or [])) or "- none"
    guardrails = "\n".join(f"- {item}" for item in (policy.get("guardrails") or []))
    return f"""# Codee Skill Policy

Preset: {policy.get("preset")}
Version: {policy.get("version")}

## Enabled Skills

{enabled}

## Backend-Gated Skills

{backend}

## Owner/Private Skills

{owner}

## Guardrails

{guardrails}
"""


def _toolkit_target_url(base_url: str, course_id: str) -> str:
    base = str(base_url or f"{DEFAULT_API_BASE}/index2income").strip().rstrip("/")
    return f"{base}/{course_id}/"


def _write_course_workspace(root: Path, *, course_id: str, business: str, target_url: str, force: bool) -> dict[str, Any]:
    course = _course_by_id(course_id)
    packet = {
        "course_id": course_id,
        "course_name": course.get("name"),
        "business": business,
        "target_url": target_url,
        "lesson": course.get("lesson") or course.get("why"),
        "student_output": course.get("student_output", ""),
        "paid_path": course.get("paid_path", ""),
        "created_at": _now(),
        "source": "codee-toolkit-init",
    }
    readme = f"""# {course.get('name')}

Business: {business}

Target route: {target_url}

## Lesson

{course.get('lesson') or course.get('why')}

## Student Output

{course.get('student_output') or 'A hosted-ready course folder with proof files.'}

## Paid Codee Path

{course.get('paid_path')}

## Proof Checklist

- The target route opens.
- The index file explains the offer clearly.
- The folder includes a `codee-course.json` packet.
- The student can choose self-hosting, Codee hosting, or Codee support.
"""
    wrote = {
        "readme": _write_text(root / "README.md", readme, force=force),
        "index": _write_text(root / "index.html", _course_starter_html(course, business=business, target_url=target_url), force=force),
        "packet": _write_json(root / "codee-course.json", packet, force=force),
        "activation": _write_json(root / ".codee" / "course-activation.json", _course_activation_packet(course=course, business=business, target_url=target_url, root=root), force=force),
    }
    return {"ok": True, "course": packet, "root": str(root), "wrote": wrote}


def _folder_inventory(root: Path) -> dict[str, Any]:
    skip_dirs = {".git", ".codee", "node_modules", ".venv", "venv", "__pycache__", ".next", "dist", "build"}
    suffix_groups = {
        "html": {".html", ".htm"},
        "css": {".css"},
        "js": {".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx"},
        "images": {".png", ".jpg", ".jpeg", ".webp", ".gif", ".svg", ".avif"},
        "pdfs": {".pdf"},
        "videos": {".mp4", ".mov", ".webm", ".m4v"},
    }
    counts = {key: 0 for key in suffix_groups}
    top_files: list[str] = []
    asset_dirs: list[str] = []
    total_files = 0
    if not root.exists():
        return {
            "exists": False,
            "has_index": False,
            "has_assets": False,
            "total_files": 0,
            "counts": counts,
            "top_files": [],
            "asset_dirs": [],
        }
    for path in root.rglob("*"):
        rel_parts = set(path.relative_to(root).parts)
        if rel_parts & skip_dirs:
            continue
        if path.is_dir():
            if path.name.lower() in {"assets", "asset", "images", "img", "media", "downloads"}:
                asset_dirs.append(path.relative_to(root).as_posix())
            continue
        total_files += 1
        if len(top_files) < 18:
            top_files.append(path.relative_to(root).as_posix())
        suffix = path.suffix.lower()
        for group, suffixes in suffix_groups.items():
            if suffix in suffixes:
                counts[group] += 1
                break
    return {
        "exists": True,
        "has_index": (root / "index.html").exists(),
        "has_assets": bool(asset_dirs or (root / "assets").exists()),
        "total_files": total_files,
        "counts": counts,
        "top_files": top_files,
        "asset_dirs": sorted(asset_dirs)[:12],
    }


def _workspace_fingerprint(root: Path, inventory: dict[str, Any] | None = None) -> str:
    inventory = inventory or _folder_inventory(root)
    basis = {
        "root_name": root.name,
        "has_index": inventory.get("has_index"),
        "counts": inventory.get("counts"),
        "top_files": inventory.get("top_files"),
        "course": _read_json_if_exists(root / "codee-course.json"),
        "manifest": _read_json_if_exists(root / ".codee" / "codee.json"),
    }
    return hashlib.sha256(json.dumps(basis, sort_keys=True, default=str).encode("utf-8")).hexdigest()


def _course_activation_packet(*, course: dict[str, Any], business: str, target_url: str, root: Path) -> dict[str, Any]:
    service_id = _course_service_id(course)
    return {
        "schema": "codee.course.activation.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "course_id": str(course.get("id") or ""),
        "course_name": str(course.get("name") or ""),
        "service": service_id,
        "business": business,
        "target_url": target_url,
        "local_site": str(root / "index.html"),
        "activation_status": "local_generated_payment_required",
        "requires_payment": True,
        "requires_uploads": _course_upload_needs(course),
        "paid_intake_url": _course_paid_intake_url(course, business=business, target_url=target_url),
        "next_commands": [
            f"python3 codee.py connect {root} --service {service_id}",
            f"python3 codee.py activate {root} --service {service_id}",
            f"python3 codee.py support {root} --service {service_id} --message \"Review my generated course site and help activate the hosted link.\" --submit",
        ],
    }


def _connection_payload(root: Path, args: argparse.Namespace, *, action: str = "connect") -> dict[str, Any]:
    has_manifest = (root / ".codee" / "codee.json").exists()
    manifest = _load_manifest(root)
    course_packet = _read_json_if_exists(root / "codee-course.json")
    activation_packet = _read_json_if_exists(root / ".codee" / "course-activation.json")
    inventory = _folder_inventory(root)
    email = str(getattr(args, "email", "") or manifest.get("owner_email") or "").strip().lower()
    service = _normalize_service(str(getattr(args, "service", "") or activation_packet.get("service") or course_packet.get("course_id") or "codee-cli"))
    workspace_id = str((manifest.get("client_id") if has_manifest else "") or root.name).strip() or root.name
    codee_user_id = str(manifest.get("codee_user_id") or "").strip() or _codee_user_id(email, workspace_id)
    business = str(getattr(args, "business", "") or (manifest.get("business") if has_manifest else "") or course_packet.get("business") or activation_packet.get("business") or "Codee Client").strip()
    owner = str(getattr(args, "owner", "") or (manifest.get("owner") if has_manifest else "") or "Business Owner").strip()
    target_url = str(getattr(args, "target_url", "") or course_packet.get("target_url") or activation_packet.get("target_url") or "").strip()
    connector_plan = _client_connector_plan(args, workspace_id=workspace_id, codee_user_id=codee_user_id, service=service)
    return {
        "schema": "codee.cli.connection.request.v1",
        "created_at": _now(),
        "action": action,
        "cli_version": VERSION,
        "source_surface": "codee-cli",
        "workspace_root_name": root.name,
        "workspace_id": workspace_id,
        "client_id": workspace_id,
        "codee_user_id": codee_user_id,
        "user_id": codee_user_id,
        "account_email": email,
        "business": business,
        "owner": owner,
        "service": service,
        "course_id": str(course_packet.get("course_id") or activation_packet.get("course_id") or "").strip(),
        "target_url": target_url,
        "paywall": {
            "status": "preview_local_payment_required",
            "rule": "Local generation and locked preview can happen before payment; public hosting, true deploy, managed scan, and delivery room unlock require Stripe/payment verification.",
            "payment_required_for": ["hosted_activation", "public_deploy", "managed_scan", "delivery_room_unlock"],
        },
        "external_connector_plan": connector_plan,
        "folder_inventory": inventory,
        "workspace_fingerprint": _workspace_fingerprint(root, inventory),
        "course_packet": course_packet if course_packet else {},
        "activation_packet": activation_packet if activation_packet else {},
        "hooks": {
            "events_supported": [str(item.get("event") or "") for item in CODEE_HOOK_EVENTS],
            "event_log": ".codee/events.jsonl",
        },
        "connectors": [str(item.get("id") or "") for item in CONNECTOR_REGISTRY],
        "local_files": {
            "index": str(root / "index.html"),
            "codee_course": str(root / "codee-course.json") if (root / "codee-course.json").exists() else "",
            "manifest": str(root / ".codee" / "codee.json") if (root / ".codee" / "codee.json").exists() else "",
        },
    }


def _cli_prompt(label: str, current: str = "") -> str:
    if current:
        return current
    try:
        value = input(f"{label}: ").strip()
    except EOFError:
        value = ""
    return value


def _client_connector_plan(args: argparse.Namespace, *, workspace_id: str, codee_user_id: str, service: str) -> dict[str, Any]:
    public_base = str(getattr(args, "api_base", "") or DEFAULT_API_BASE).strip().rstrip("/")
    wordpress_site = str(getattr(args, "wordpress_site", "") or "").strip()
    drive_folder = str(getattr(args, "drive_folder", "") or "").strip()
    gmail_query = str(getattr(args, "gmail_query", "") or "").strip()
    wants_wordpress = bool(getattr(args, "connect_wordpress", False) or wordpress_site)
    wants_google = bool(getattr(args, "connect_google", False) or drive_folder or gmail_query)
    dashboard_base = f"{public_base}/api/dashboard/{urllib.parse.quote(workspace_id, safe='')}"
    workspace_base = f"{public_base}/api/workspace/{urllib.parse.quote(workspace_id, safe='')}"
    browser_base = f"{public_base}"
    plan: dict[str, Any] = {
        "workspace_id": workspace_id,
        "codee_user_id": codee_user_id,
        "service": service,
        "requests": [],
        "guardrails": [
            "Codee CLI does not store WordPress, Gmail, or Drive passwords.",
            "WordPress uses a browser/backend handoff for Application Password or plugin auth.",
            "Google Drive and Gmail use OAuth/browser authorization and can be reconnected only when needed.",
            "Draft edits and cleanup plans should be reviewed before publish, delete, or permanent changes.",
        ],
    }
    if wants_wordpress:
        plan["requests"].append(
            {
                "id": "wordpress",
                "status": "needs_client_authorization",
                "site_url": wordpress_site,
                "needs": [
                    "WordPress site URL",
                    "WordPress username",
                    "Application Password created inside the WordPress user profile",
                    "permission for Codee to create drafts, not publish without approval",
                ],
                "assistant_url": f"{browser_base}/wordpress-assistant.html?{urllib.parse.urlencode({'client_id': workspace_id, 'source': 'codee-cli', 'service': service})}",
                "probe_endpoint": f"{dashboard_base}/wordpress-probe",
                "connect_endpoint": f"{dashboard_base}/wordpress-connect",
                "test_endpoint": f"{dashboard_base}/wordpress-test",
            }
        )
    if wants_google:
        return_to = f"{browser_base}/codee-workbench.html?{urllib.parse.urlencode({'client_id': workspace_id, 'codee_user_id': codee_user_id, 'service': service, 'source': 'codee-cli-google-connect'})}"
        google_query = {"platform": "google_suite", "redirect": "1", "return_to": return_to}
        plan["requests"].append(
            {
                "id": "google-suite",
                "status": "needs_temporary_oauth",
                "drive_folder_url": drive_folder,
                "gmail_query": gmail_query or "newer_than:30d",
                "needs": [
                    "Google browser authorization from the account owner",
                    "Drive folder URL when assets need organization",
                    "Gmail search query when inbox help is needed",
                    "approval before delete, archive, or permanent cleanup",
                ],
                "connect_url": f"{dashboard_base}/oauth/start?{urllib.parse.urlencode(google_query)}",
                "drive_scan_endpoint": f"{workspace_base}/drive-scan",
                "email_scan_endpoint": f"{workspace_base}/email-scan",
            }
        )
    return plan


def _client_service_to_chat_payload(service: str, *, business: str, email: str, target_url: str, goal: str) -> dict[str, Any]:
    clean = _normalize_service(service or "codeeqr")
    contract = _service_contract(clean)
    payload: dict[str, Any] = {
        "client_brand": business or "Codee Client",
        "client_email": email or "",
        "desired_outcome": goal or "Generate the client preview, lock true deployment behind Stripe, and deliver through Codee room.",
        "service_outcome": goal or "Generate the client preview, lock true deployment behind Stripe, and deliver through Codee room.",
        "source": "codee-cli-client",
        "traffic_source": "codee-cli",
        "service_contract_version": "codee.service-contracts.v1",
        "service_contract": contract,
        "contract_required_inputs": contract.get("required_inputs") or [],
        "contract_client_gets": contract.get("client_gets") or [],
        "contract_paywall_rule": contract.get("paywall_rule") or "",
    }
    if clean in {"codeeqr", "qrcodee", "qr"}:
        payload.update(
            {
                "product_type": "codeeqr",
                "codeeqr_target_link": target_url or "https://codee.chat",
                "codeeqr_target_type": "link",
                "codeeqr_business_type": "client business",
                "codeeqr_terms_agreed": "yes",
            }
        )
    elif clean in {"codeeflyer250", "codeeflyer-250"}:
        payload.update(
            {
                "product_type": "digiflyer",
                "service_tier": "250",
                "tier_requested": "250",
                "digiflyer_target_link": target_url,
                "digiflyer_design_brief": goal,
                "digiflyer_generated_image_mode": "logo_event_description_composer",
            }
        )
    elif clean in {"codeeflyer", "codeeflyer100", "codeeflyer-100"}:
        payload.update(
            {
                "product_type": "digiflyer",
                "service_tier": "100",
                "tier_requested": "100",
                "digiflyer_target_link": target_url,
                "digiflyer_design_brief": goal,
            }
        )
    elif clean in {"codeeapp", "codeeapp250"}:
        payload.update(
            {
                "product_type": "digiapp",
                "service_tier": "codeeapp_v4_250",
                "tier_requested": "250",
                "codeeapp_lane": "codeeapp_v4_250",
                "ebook_headline": business or "Codee App",
                "ebook_benefits": ["Clear paid product page", "Stripe-ready buyer path", "Delivery room handoff"],
            }
        )
    elif clean in {"codeecard", "digicard"}:
        payload.update({"product_type": "digicard", "tier_requested": "250"})
    elif clean in {"codeebeeper", "codeevault"}:
        payload.update({"product_type": "codeevault", "tier_requested": "149"})
    elif clean in {"minicodeesite", "business-suite", "codee-business-suite"}:
        payload.update({"product_type": "minicodeesite", "tier_requested": "2500", "service_tier": "minicodeesite_supported_2500"})
    else:
        payload.update({"product_type": "digiapp", "tier_requested": "250", "service_tier": "codeeapp_v4_250"})
    return payload


def _client_intake_markdown(packet: dict[str, Any]) -> str:
    lines = [
        "# Codee Client Intake Packet",
        "",
        f"Business: {packet.get('business')}",
        f"Service: {packet.get('service')}",
        f"Client email: {packet.get('account_email') or 'not provided'}",
        f"Target URL: {packet.get('target_url') or 'not provided'}",
        "",
        "## Service Contract",
        "",
    ]
    contract = packet.get("service_contract") if isinstance(packet.get("service_contract"), dict) else {}
    if contract:
        lines.append(f"- Promise: {contract.get('promise')}")
        lines.append("- Client gets:")
        for item in contract.get("client_gets") or []:
            lines.append(f"  - {item}")
        lines.append("- Required inputs:")
        for item in contract.get("required_inputs") or []:
            lines.append(f"  - {item}")
    else:
        lines.append("- No service contract attached.")
    lines.extend([
        "",
        "## Paywall Rule",
        "",
        "- Codee may create a locked preview first.",
        "- True deploy, hosted route, delivery room unlock, managed scan, and support handoff wait for Stripe/payment verification.",
        "- The client can review the preview, then pay to keep the final route live.",
        "",
        "## Connector Requests",
        "",
    ])
    plan = packet.get("connector_plan") if isinstance(packet.get("connector_plan"), dict) else {}
    requests = plan.get("requests") if isinstance(plan.get("requests"), list) else []
    if not requests:
        lines.append("- No external connector requested yet.")
    for item in requests:
        if not isinstance(item, dict):
            continue
        lines.append(f"- {item.get('id')}: {item.get('status')}")
        for need in item.get("needs") or []:
            lines.append(f"  - {need}")
    lines.extend(["", "## Next Commands", ""])
    for cmd in packet.get("next_commands") or []:
        lines.append(f"```bash\n{cmd}\n```")
    lines.append("")
    return "\n".join(lines)


def _folder_plan_markdown(payload: dict[str, Any]) -> str:
    inventory = payload.get("inventory") if isinstance(payload.get("inventory"), dict) else {}
    counts = inventory.get("counts") if isinstance(inventory.get("counts"), dict) else {}
    files = "\n".join(f"- {item}" for item in inventory.get("top_files") or []) or "- No files found yet."
    steps = "\n".join(f"- {item}" for item in payload.get("teaching_steps") or [])
    missing = "\n".join(f"- {item}" for item in payload.get("missing") or []) or "- No required folder basics are missing."
    commands = "\n".join(f"```bash\n{item}\n```" for item in payload.get("next_commands") or [])
    return f"""# Codee Folder Plan

Business: {payload.get('business')}
Service: {payload.get('service')}
Folder: {payload.get('root')}

## Folder Status

- Folder exists: {inventory.get('exists')}
- Has index.html: {inventory.get('has_index')}
- Has asset folder: {inventory.get('has_assets')}
- Total files: {inventory.get('total_files')}
- HTML: {counts.get('html', 0)}
- CSS: {counts.get('css', 0)}
- JS: {counts.get('js', 0)}
- Images: {counts.get('images', 0)}
- PDFs: {counts.get('pdfs', 0)}
- Videos: {counts.get('videos', 0)}

## Missing

{missing}

## Teaching Steps

{steps}

## Files Seen

{files}

## Next Commands

{commands}
"""


def _domain_plan_markdown(payload: dict[str, Any]) -> str:
    steps = "\n".join(f"- {item}" for item in payload.get("teaching_steps") or [])
    records = "\n".join(f"- {item}" for item in payload.get("dns_records_to_confirm") or [])
    checks = "\n".join(f"- {item}" for item in payload.get("proof_checks") or [])
    route = payload.get("route_check") if isinstance(payload.get("route_check"), dict) else {}
    commands = "\n".join(f"```bash\n{item}\n```" for item in payload.get("next_commands") or [])
    route_line = f"status={route.get('status')} ok={route.get('ok')} final_url={route.get('final_url')}" if route else "No live route scan requested."
    return f"""# Codee Domain Plan

Business: {payload.get('business')}
Domain: {payload.get('domain') or 'not set'}
Target URL: {payload.get('target_url') or 'not set'}
Registrar: {payload.get('registrar')}
Hosting: {payload.get('hosting')}

## Plain-English Rule

{payload.get('rule')}

## DNS Records To Confirm

{records}

## Teaching Steps

{steps}

## Proof Checks

{checks}

## Latest Route Check

{route_line}

## Next Commands

{commands}
"""


def _toolkit_hub_html(payload: dict[str, Any]) -> str:
    business = str(payload.get("business") or "Codee Toolkit")
    courses = payload.get("courses") if isinstance(payload.get("courses"), list) else []
    cards = "\n".join(
        f"""      <article>
        <small>Volume {index + 1:02d}</small>
        <h2>{item.get('name')}</h2>
        <p>{item.get('lesson')}</p>
        <a href="{item.get('folder')}/index.html">Open local folder</a>
        <a href="{item.get('target_url')}">Open live lesson</a>
      </article>"""
        for index, item in enumerate(courses)
    )
    return f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>{business} | Codee Toolkit</title>
  <style>
    * {{ box-sizing: border-box; }}
    body {{ margin: 0; min-height: 100vh; color: #f7f1e7; font-family: Arial, sans-serif; background: #050607; }}
    main {{ width: min(1120px, calc(100% - 28px)); margin: 0 auto; padding: 28px 0 56px; }}
    header, article, section {{ border: 1px solid rgba(255,255,255,.14); border-radius: 10px; background: rgba(17,20,23,.88); padding: 22px; margin-bottom: 14px; }}
    h1 {{ margin: 0; font-size: clamp(2.4rem, 7vw, 5.2rem); line-height: .94; }}
    h2 {{ margin: 10px 0 0; }}
    p, li {{ color: #bdb5a8; line-height: 1.6; font-weight: 700; }}
    small {{ color: #d7b35b; font-weight: 900; text-transform: uppercase; }}
    .grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; }}
    a {{ min-height: 42px; display: inline-flex; align-items: center; margin: 12px 8px 0 0; padding: 0 13px; border: 1px solid rgba(255,255,255,.16); border-radius: 8px; color: #f7f1e7; text-decoration: none; font-weight: 900; }}
  </style>
</head>
<body>
  <main>
    <header>
      <small>Codee Open-Source Toolkit</small>
      <h1>{business}</h1>
      <p>{payload.get('purpose')}</p>
      <a href="https://clients.codee.chat/codee-toolkit.html">Open public toolkit</a>
      <a href="https://clients.codee.chat/codee-workbench.html">Open Codee Workbench</a>
    </header>
    <section>
      <small>Core course folders</small>
      <div class="grid">
{cards}
      </div>
    </section>
    <section>
      <small>Proof commands</small>
      <ul>
        <li>Run `python3 codee.py skill-policy . --preset operator --force`.</li>
        <li>Run `python3 codee.py toolkit-smoke .` before calling the toolkit ready.</li>
        <li>Run `python3 codee.py browser-scan . --url https://clients.codee.chat/codee-toolkit.html --full-page` when Playwright is available.</li>
      </ul>
    </section>
  </main>
</body>
</html>
"""


def _toolkit_readme(payload: dict[str, Any]) -> str:
    course_lines = "\n".join(f"- {item['id']}: `{item['folder']}/index.html` -> {item['target_url']}" for item in payload.get("courses") or [])
    command_lines = "\n".join(f"```bash\n{cmd}\n```" for cmd in payload.get("next_commands") or [])
    return f"""# Codee Open-Source Toolkit

Business: {payload.get('business')}

{payload.get('purpose')}

## Core Course Folders

{course_lines}

## Use It With

- Codee CLI
- Codee Workbench
- QRCodee Open-Source Course
- Codee Flyer Open-Source Course
- Codee App Open-Source Course
- Optional Playwright browser scans

## Next Commands

{command_lines}

## Rule

This toolkit is useful when it leaves proof: course packets, route scans, browser screenshots, delivery-room links, and support request packets.
"""


def _admin_training_markdown(payload: dict[str, Any]) -> str:
    governance = "\n".join(
        f"- {item['lane']}: {item['entity']} - {item['role']}"
        for item in payload.get("governance_model") or []
    )
    stack = "\n".join(
        f"- {item['platform']}: {item['role']} Admin proof: {item['proof']}"
        for item in payload.get("platform_stack") or []
    )
    tiers = "\n".join(
        f"- {item['tier']}: {item['payment_model']} Unlocks: {item['what_unlocks']} Recurring: {item['recurring']}"
        for item in payload.get("tier_ladder") or []
    )
    lessons = "\n".join(f"- {item}" for item in payload.get("admin_lessons") or [])
    certification = "\n".join(
        f"- {item['label']}: {item['proof']}"
        for item in payload.get("certification_checks") or []
    )
    return f"""# {payload.get('name')}

Version: {payload.get('version')}

{payload.get('purpose')}

## Governance Model

{governance}

Important: this is an admin operating model, not legal or tax advice. Final nonprofit licensing, IP ownership, and revenue-sharing documents should be reviewed by qualified counsel and tax/accounting support.

## Platform Stack

{stack}

## Open Source, Done For You, and Recurring Tiers

{tiers}

## Admin Lessons

{lessons}

## Certification Checks

{certification}

## Proof Commands

```bash
python3 codee.py admin-training . --write
python3 codee.py admin-certify . --json
python3 codee.py folder-plan . --business "My Business" --service codee-service --write
python3 codee.py domain-plan . --domain example.com --target-url https://example.com --write
python3 codee.py toolkit-smoke ./codee-open-source-toolkit
python3 codee.py browser-scan ./codee-open-source-toolkit --url https://clients.codee.chat/codee-admin-training.html --full-page
python3 codee.py scan . --url https://clients.codee.chat/codee-admin-training.html --url https://clients.codee.chat/codee-toolkit.html
```
"""


def _admin_guidebook_markdown(payload: dict[str, Any]) -> str:
    pages = "\n\n".join(
        f"## Page {item['number']}: {item['title']}\n\n"
        f"Tag: {item['tag']}\n\n"
        f"{item['lesson']}\n\n"
        f"Proof: {item['proof']}"
        for item in payload.get("pages") or []
    )
    source_lines = "\n".join(
        f"- {item['label']}: {item['url']}"
        for item in payload.get("sources") or []
    )
    return f"""# {payload.get('title')}

{payload.get('subtitle')}

Rule: {payload.get('rule')}

Owner page: {payload.get('owner_page')}

## Pages

{pages}

## Source Study

{source_lines}

## Proof Commands

```bash
python3 codee.py scan . --url {payload.get('owner_page')}
python3 codee.py browser-scan . --url {payload.get('owner_page')} --full-page
python3 codee.py course-smoke --json
```
"""


def _admin_certification_markdown(payload: dict[str, Any]) -> str:
    checks = "\n".join(
        f"- [{'x' if item.get('ok') else ' '}] {item.get('name')}: {item.get('summary')}"
        for item in payload.get("checks") or []
    )
    routes = "\n".join(
        f"- [{'x' if item.get('ok') else ' '}] {item.get('name')}: status={item.get('status')} url={item.get('url')}"
        for item in payload.get("route_checks") or []
    ) or "- No live route checks were run."
    actions = "\n".join(f"- {item}" for item in payload.get("next_actions") or []) or "- Keep scanning after each platform or service change."
    return f"""# Codee Admin Certification

Created: {payload.get('created_at')}

Workspace: {payload.get('root')}

Score: {payload.get('score')}%

Status: {payload.get('status')}

## Local Checks

{checks}

## Live Route Checks

{routes}

## Next Actions

{actions}
"""


def _business_type_by_id(type_id: str) -> dict[str, Any]:
    clean = _slugify(type_id)
    for item in BUSINESS_ASSISTANT_TYPES:
        if str(item.get("id") or "") == clean:
            return item
    allowed = ", ".join(str(item.get("id")) for item in BUSINESS_ASSISTANT_TYPES)
    raise SystemExit(f"Unknown business type '{type_id}'. Use one of: {allowed}.")


def _business_assistant_markdown(payload: dict[str, Any]) -> str:
    assistant = payload.get("assistant") if isinstance(payload.get("assistant"), dict) else {}
    lines = {
        "questions": "\n".join(f"- {item}" for item in assistant.get("intake_questions") or []),
        "lanes": "\n".join(f"- {item}" for item in assistant.get("core_lanes") or []),
        "deliverables": "\n".join(f"- {item}" for item in assistant.get("deliverables") or []),
        "proof": "\n".join(f"- {item}" for item in assistant.get("proof_checks") or []),
        "commands": "\n".join(f"```bash\n{item}\n```" for item in payload.get("next_commands") or []),
    }
    return f"""# {assistant.get('assistant_name')} Business Assistant

Business: {payload.get('business')}

Business type: {assistant.get('name')}

Audience: {assistant.get('audience')}

First offer: {assistant.get('first_offer')}

## Intake Questions

{lines['questions']}

## Recommended Codee Lanes

{lines['lanes']}

## Deliverables

{lines['deliverables']}

## Recurring Support Logic

{assistant.get('recurring_support')}

## Proof Checklist

{lines['proof']}

## Next Commands

{lines['commands']}
"""


def _business_assistant_html(payload: dict[str, Any]) -> str:
    assistant = payload.get("assistant") if isinstance(payload.get("assistant"), dict) else {}
    def items(values: list[str]) -> str:
        return "\n".join(f"<li>{value}</li>" for value in values)
    return f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>{payload.get('business')} | {assistant.get('assistant_name')}</title>
  <style>
    * {{ box-sizing: border-box; }}
    body {{ margin: 0; min-height: 100vh; color: #f7f1e7; font-family: Arial, sans-serif; background: #050607; }}
    main {{ width: min(980px, calc(100% - 28px)); margin: 0 auto; padding: 26px 0 52px; }}
    header, section {{ border: 1px solid rgba(255,255,255,.14); border-radius: 10px; background: rgba(17,20,23,.9); padding: 22px; margin-bottom: 14px; }}
    h1 {{ margin: 0; font-size: clamp(2.3rem, 7vw, 4.8rem); line-height: .94; }}
    h2 {{ margin: 0 0 10px; }}
    p, li {{ color: #bdb5a8; line-height: 1.58; font-weight: 700; }}
    small {{ color: #d7b35b; font-weight: 900; text-transform: uppercase; }}
    .grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 12px; }}
    .card {{ border: 1px solid rgba(255,255,255,.12); border-radius: 8px; padding: 16px; background: rgba(255,255,255,.05); }}
    a {{ min-height: 42px; display: inline-flex; align-items: center; margin: 12px 8px 0 0; padding: 0 13px; border: 1px solid rgba(255,255,255,.16); border-radius: 8px; color: #f7f1e7; text-decoration: none; font-weight: 900; }}
  </style>
</head>
<body>
  <main>
    <header>
      <small>{assistant.get('name')}</small>
      <h1>{assistant.get('assistant_name')} for {payload.get('business')}</h1>
      <p>{assistant.get('first_offer')}</p>
      <a href="https://clients.codee.chat/codee-course-teacher.html?business={assistant.get('id')}">Open chat teacher</a>
      <a href="https://clients.codee.chat/codee-chat.html?service=business-assistant&amp;business_type={assistant.get('id')}&amp;autostart=1">Ask Codee to build</a>
    </header>
    <section>
      <small>Intake</small>
      <h2>Questions to ask before building</h2>
      <ul>{items(assistant.get('intake_questions') or [])}</ul>
    </section>
    <section class="grid">
      <div class="card"><small>Lanes</small><ul>{items(assistant.get('core_lanes') or [])}</ul></div>
      <div class="card"><small>Deliverables</small><ul>{items(assistant.get('deliverables') or [])}</ul></div>
      <div class="card"><small>Proof</small><ul>{items(assistant.get('proof_checks') or [])}</ul></div>
    </section>
    <section>
      <small>Recurring support</small>
      <p>{assistant.get('recurring_support')}</p>
    </section>
  </main>
</body>
</html>
"""


def _money(amount_cents: int, currency: str = "usd") -> str:
    prefix = "$" if currency.lower() == "usd" else f"{currency.upper()} "
    return f"{prefix}{amount_cents / 100:,.2f}"


def _print_pricing(payload: dict[str, Any]) -> None:
    print("Codee CLI pricing")
    print("")
    for plan in payload.get("plans") or []:
        if not isinstance(plan, dict):
            continue
        cadence = f"/{plan.get('interval')}" if plan.get("interval") else ""
        print(f"{plan.get('id')}: {plan.get('name')} - {_money(int(plan.get('amount_cents') or 0), str(plan.get('currency') or payload.get('currency') or 'usd'))}{cadence}")
        description = str(plan.get("description") or "").strip()
        if description:
            print(f"  {description}")
        if plan.get("invoice_allowed"):
            print("  Invoice supported for this plan.")
    print("")
    print("Payments are handled through Codee backend and Stripe-hosted pages. The CLI never stores card numbers or Stripe secret keys.")


def command_explain(_: argparse.Namespace) -> int:
    print("Codee Platform model")
    print("")
    print("Umbrella: INVEST IN VETS Foundation keeps the mission tied to homeless and disabled veterans.")
    print("Tech company: AI K9 Kennel builds public service lanes, demos, templates, and partner systems.")
    print("Platform: Codee is the downloadable workflow layer for intake, scan, build, deliver, and report.")
    print("Partners: AI K9 Partners can use Codee rules, routes, and reports with their preferred AI tools.")
    print("")
    print("Codee does not replace Claude, OpenAI, Gemini, or other AI tools.")
    print("Codee gives the business operator a repeatable mission system around those tools.")
    print("Codee AGI means Applied Good Intelligence: science, technology, ethics, society, capital creation, and mission reinvestment.")
    print("The `agent-core` command installs this guarded operating loop with goals, memory, tools, proof, heartbeat, and permission gates.")
    print("Codee has a local-first `memory-vault` for each codee_user_id so preferences, proof, service history, and next steps can survive beyond one session.")
    print("")
    print("Direction: teach QRCodee first. One folder with index.html can become the first business surface.")
    print("Codee keeps the skills, scans, proof, support room, and paid hosting upsells attached to that folder.")
    print("")
    print("Fastest useful path:")
    print("1. codee init creates the workspace.")
    print("2. codee course-init ./qrcodee-course --course qrcodee creates the first teachable lane.")
    print("3. codee folder-plan checks the folder and index file before hosting.")
    print("4. codee agent-core --write installs the governed agent rules.")
    print("5. codee memory-vault init creates the user memory layer.")
    print("6. codee accessibility --write installs veteran-first course rules.")
    print("7. codee heartbeat shows what is alive, missing, and next.")
    print("8. codee scan checks live routes before anyone calls it ready.")
    print("9. codee support or codee upgrade moves the user into paid help only when they need hosting, scans, or done-for-you support.")
    return 0


def command_init(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    business = args.business.strip() or "Codee Client"
    owner = args.owner.strip() or "Business Owner"
    owner_email = str(args.email or "").strip().lower()
    client_id = _slugify(args.client_id or business)
    codee_user_id = _codee_user_id(owner_email, f"{owner}:{business}:{client_id}")
    mission = args.mission.strip() or "Turn one business idea into a simple income-ready digital service."
    force = bool(args.force)

    codee_dir = root / ".codee"
    commands_dir = codee_dir / "commands"
    reports_dir = codee_dir / "reports"
    reports_dir.mkdir(parents=True, exist_ok=True)

    manifest = {
        "schema": "codee.platform.v0",
        "version": VERSION,
        "created_at": _now(),
        "business": business,
        "owner": owner,
        "owner_email": owner_email,
        "codee_user_id": codee_user_id,
        "client_id": client_id,
        "identity": {
            "provider": "codee-local-v0",
            "status": "local_workspace",
            "codee_user_id": codee_user_id,
            "email": owner_email,
            "next_step": "A hosted Codee account can bind this local ID to login, tiers, delivery rooms, and scans."
        },
        "mission": mission,
        "umbrella": "INVEST IN VETS Foundation",
        "tech_company": "AI K9 Kennel",
        "platform": "Codee",
        "partner_program": "AI K9 Partners",
        "preferred_ai_tools": ["Codee", "Claude", "OpenAI", "Gemini"],
        "guardrails": [
            "Do not delete client work without an explicit target list.",
            "Do not publish external messages without owner review.",
            "Do not claim a deliverable is ready until its route and assets are verified.",
            "Keep payment, delivery, and support proof attached to the client record."
        ],
        "service_flow": ["intake", "offer-map", "scan", "plan", "build", "deliver", "verify", "report"],
        "starter_lane": {
            "course": "qrcodee",
            "rule": "Teach one folder/index QRCodee lane first, then upsell hosting, scans, delivery room, support, or done-for-you services.",
            "folder_index_contract": {
                "index.html": "The first public page and smallest business surface.",
                "assets/": "Images, logos, QR files, PDFs, videos, and downloads.",
                ".codee/": "Skills, route lists, support packets, payment proof, and reports."
            },
            "default_next_commands": [
                "python3 codee.py course-init ./qrcodee-course --course qrcodee --business \"My Business\" --target-url https://example.com --force",
                "python3 codee.py folder-plan ./qrcodee-course --business \"My Business\" --service qrcodee --write --force",
                "python3 codee.py verify ./qrcodee-course --service codeeqr",
                "python3 codee.py hooks ./qrcodee-course --write",
                "python3 codee.py connectors ./qrcodee-course --write",
                "python3 codee.py platform ./qrcodee-course --write --force",
                "python3 codee.py task create ./qrcodee-course --title \"Make QRCodee live\" --service codeeqr --prompt \"Verify the QRCodee folder, connect it to backend, and prepare paid activation.\"",
                "python3 codee.py skills --access public",
                "python3 codee.py course-smoke ./qrcodee-course",
                "python3 codee.py support ./qrcodee-course --service qrcodee --message \"Review my first QRCodee folder for hosting.\""
            ]
        },
        "evidence": {
            "route_report": ".codee/reports/latest-route-scan.json",
            "project_manifest": ".codee/codee.json"
        }
    }
    routes = [
        {
            "name": "homepage",
            "url": "https://codee.chat/",
            "expected": [200, 301, 302, 307, 308]
        },
        {
            "name": "codee-platform",
            "url": "https://clients.codee.chat/codee-platform.html",
            "expected": [200]
        }
    ]
    partners = {
        "program": "AI K9 Partners",
        "purpose": "Let builders, veterans, local businesses, and nonprofits use Codee workflows without being locked into one AI provider.",
        "roles": [
            {"name": "Operator", "job": "Runs intake, route checks, and delivery reports."},
            {"name": "Builder", "job": "Turns the plan into pages, assets, scripts, and automation."},
            {"name": "Reviewer", "job": "Checks claims, links, payment paths, accessibility, and launch readiness."},
            {"name": "Mission Partner", "job": "Helps connect revenue to veteran housing, training, and support outcomes."}
        ]
    }
    skill_policy = _build_skill_policy(preset="public")
    codee_md = f"""# CODEE.md

Business: {business}
Owner: {owner}
Codee User ID: {codee_user_id}
Client ID: {client_id}

## Mission

{mission}

## Operating Model

- INVEST IN VETS Foundation is the mission umbrella.
- AI K9 Kennel is the technology company building service lanes and proof systems.
- Codee is the platform layer: intake, scan, plan, build, deliver, verify, and report.
- AI K9 Partners can use this workspace with Codee, Claude, OpenAI, Gemini, or another approved AI tool.
- First lesson: QRCodee. One folder with `index.html` is the smallest business surface Codee can teach, scan, host, and support.
- Upsell rule: sell hosting, scans, delivery room, support, or done-for-you execution only after the folder path makes sense.

## Rules

- Start by checking `.codee/codee.json`.
- Use `.codee/routes.json` before claiming a site is live.
- Save proof in `.codee/reports/`.
- Ask for owner approval before payments, external sends, destructive cleanup, or sensitive data handling.
"""
    commands = {
        "mission.md": "Explain this business mission in simple language and list the next 3 useful actions.",
        "money-map.md": "Turn this business into one simple sellable offer with audience, price, CTA, checkout path, delivery path, and proof report.",
        "scan.md": "Check every route in .codee/routes.json and report any 404, 500, broken redirect, or slow route.",
        "launch.md": "Prepare a small launch checklist: offer, page, CTA, payment path, delivery path, and proof report.",
        "partner.md": "Explain how an AI K9 Partner should help this business without taking over ownership."
    }

    writes = [
        (root / "CODEE.md", codee_md),
    ]
    written = []
    skipped = []
    for path, text in writes:
        if _write_text(path, text, force=force):
            written.append(str(path))
        else:
            skipped.append(str(path))
    for name, prompt in commands.items():
        path = commands_dir / name
        if _write_text(path, prompt + "\n", force=force):
            written.append(str(path))
        else:
            skipped.append(str(path))
    for path, payload in [
        (codee_dir / "codee.json", manifest),
        (codee_dir / "routes.json", routes),
        (codee_dir / "partners.json", partners),
        (codee_dir / "skills.json", skill_policy),
    ]:
        if _write_json(path, payload, force=force):
            written.append(str(path))
        else:
            skipped.append(str(path))
    if _write_text(codee_dir / "SKILLS.md", _skill_policy_markdown(skill_policy), force=force):
        written.append(str(codee_dir / "SKILLS.md"))
    else:
        skipped.append(str(codee_dir / "SKILLS.md"))

    print(f"Codee workspace ready: {root}")
    print(f"written={len(written)} skipped={len(skipped)}")
    if skipped:
        print("Use --force to overwrite existing Codee files.")
    return 0


def _load_route_targets(path: Path, urls: list[str], expected: list[int]) -> list[dict[str, Any]]:
    if urls:
        return [{"name": url, "url": url, "expected": expected} for url in urls]
    route_file = path / ".codee" / "routes.json"
    if not route_file.exists():
        return []
    payload = json.loads(route_file.read_text(encoding="utf-8"))
    if not isinstance(payload, list):
        raise SystemExit(".codee/routes.json must be a JSON list")
    return [item for item in payload if isinstance(item, dict) and str(item.get("url") or "").startswith(("http://", "https://"))]


def _load_manifest(root: Path) -> dict[str, Any]:
    manifest_path = root / ".codee" / "codee.json"
    if not manifest_path.exists():
        return {
            "business": "Codee Client",
            "owner": "Business Owner",
            "owner_email": "",
            "client_id": root.name,
            "codee_user_id": _codee_user_id(seed=str(root)),
            "mission": "Turn one business idea into a simple income-ready digital service.",
        }
    payload = json.loads(manifest_path.read_text(encoding="utf-8"))
    if not isinstance(payload, dict):
        raise SystemExit(".codee/codee.json must be a JSON object")
    return payload


def _route_check(target: dict[str, Any], timeout: float) -> dict[str, Any]:
    url = str(target["url"])
    expected = [int(code) for code in target.get("expected") or [200]]
    started = time.monotonic()
    req = urllib.request.Request(url, method="GET", headers={"User-Agent": f"CodeeCLI/{VERSION}"})
    status = 0
    error = ""
    final_url = url
    sample = ""
    transport = "urllib"
    try:
        with urllib.request.urlopen(req, timeout=timeout) as res:
            status = int(res.status)
            final_url = str(res.geturl() or url)
            sample = res.read(180).decode("utf-8", errors="replace")
    except urllib.error.HTTPError as exc:
        status = int(exc.code)
        final_url = str(exc.geturl() or url)
        sample = exc.read(180).decode("utf-8", errors="replace")
    except Exception as exc:
        error = f"{type(exc).__name__}: {str(exc)[:180]}"
        fallback = _curl_fetch("GET", url, timeout=timeout)
        if fallback.get("ok"):
            status = int(fallback.get("status") or 0)
            final_url = str(fallback.get("final_url") or url)
            sample = str(fallback.get("body") or "")[:180]
            transport = "curl-fallback"
            error = "" if status else str(fallback.get("error") or "")[:180]
        elif fallback.get("error"):
            error = f"{error}; curl: {str(fallback.get('error') or '')[:120]}"
    elapsed_ms = int((time.monotonic() - started) * 1000)
    return {
        "name": str(target.get("name") or url),
        "url": url,
        "status": status,
        "expected": expected,
        "ok": bool(status in expected and status != 404 and status < 500 and not error),
        "route_missing": status == 404,
        "server_error": status >= 500,
        "error": error,
        "elapsed_ms": elapsed_ms,
        "final_url": final_url,
        "transport": transport,
        "sample": sample
    }


def command_scan(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    expected = [int(value) for value in args.expected.split(",") if value.strip()]
    targets = _load_route_targets(root, list(args.url or []), expected)
    if not targets:
        print("No targets. Run `codee init` first or pass --url https://example.com.")
        return 2
    checks = [_route_check(target, float(args.timeout)) for target in targets]
    payload = {
        "ok": all(item["ok"] for item in checks),
        "version": VERSION,
        "created_at": _now(),
        "checks": checks,
        "failed": [item for item in checks if not item["ok"]],
        "not_found_count": sum(1 for item in checks if item["route_missing"])
    }
    report = root / ".codee" / "reports" / "latest-route-scan.json"
    report.parent.mkdir(parents=True, exist_ok=True)
    report.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
    if args.json:
        print(json.dumps(payload, indent=2))
    else:
        print(f"ok={payload['ok']} checks={len(checks)} failed={len(payload['failed'])} not_found={payload['not_found_count']}")
        for item in payload["failed"]:
            print(f"{item['name']} status={item['status']} url={item['url']} error={item['error']}")
        print(f"report={report}")
    return 0 if payload["ok"] else 1


def _verify_markdown(payload: dict[str, Any]) -> str:
    checks = payload.get("checks") if isinstance(payload.get("checks"), list) else []
    timeline = payload.get("activation_timeline") if isinstance(payload.get("activation_timeline"), list) else []
    lines = [
        "# Codee Verify Report",
        "",
        f"Service: {payload.get('service_label') or payload.get('service')}",
        f"Workspace: {payload.get('workspace_id')}",
        f"Status: {'PASS' if payload.get('ok') else 'NEEDS WORK'}",
        f"Activation: {payload.get('activation_status')}",
        "",
        "## Checks",
        "",
    ]
    for item in checks:
        marker = "PASS" if item.get("ok") else str(item.get("severity") or "warn").upper()
        lines.append(f"- {marker}: {item.get('label')} - {item.get('copy')}")
    lines.extend(["", "## Activation Timeline", ""])
    for item in timeline:
        lines.append(f"- {item.get('label')}: {item.get('status')} - {item.get('copy')}")
    lines.extend(["", "## Next Commands", ""])
    for command in payload.get("next_commands") or []:
        lines.append(f"```bash\n{command}\n```")
    lines.append("")
    return "\n".join(lines)


def command_verify(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    _append_event(root, "PreVerify", {"service": args.service or "", "strict": bool(args.strict)})
    payload = _connection_payload(root, args, action="verify")
    service = _normalize_service(str(args.service or payload.get("service") or "codee-cli"))
    rules = SERVICE_VERIFY_RULES.get(service) or SERVICE_VERIFY_RULES.get("codeeflyer" if "flyer" in service else "codeeqr")
    inventory = payload.get("folder_inventory") if isinstance(payload.get("folder_inventory"), dict) else {}
    counts = inventory.get("counts") if isinstance(inventory.get("counts"), dict) else {}
    course_packet = payload.get("course_packet") if isinstance(payload.get("course_packet"), dict) else {}
    activation_packet = payload.get("activation_packet") if isinstance(payload.get("activation_packet"), dict) else {}
    connection = _read_json_if_exists(root / ".codee" / "backend-connection.json")
    license_payload = _read_json_if_exists(root / ".codee" / "license.json")
    target_url = str(args.target_url or payload.get("target_url") or "").strip()
    index_path = root / "index.html"
    index_text = ""
    if index_path.exists():
        try:
            index_text = index_path.read_text(encoding="utf-8", errors="replace")
        except Exception:
            index_text = ""
    checks: list[dict[str, Any]] = []

    def add_check(key: str, label: str, ok: bool, copy: str, *, severity: str = "fail", proof: str = "") -> None:
        checks.append(
            {
                "id": key,
                "label": label,
                "ok": bool(ok),
                "severity": severity,
                "copy": copy,
                "proof": proof,
            }
        )

    has_index = bool(index_path.exists() and inventory.get("has_index"))
    has_course_packet = bool(course_packet and not course_packet.get("error"))
    has_activation_packet = bool(activation_packet and not activation_packet.get("error"))
    has_backend_connection = bool(connection.get("ok") and connection.get("connection_id"))
    has_payment_proof = bool(license_payload.get("paid") or license_payload.get("session_id") or license_payload.get("invoice_id"))
    has_images = int(counts.get("images") or 0) > 0
    has_pdfs = int(counts.get("pdfs") or 0) > 0
    has_assets = bool(inventory.get("has_assets") or has_images or has_pdfs)
    route_mentions_target = bool(target_url and target_url in index_text)
    sensitive_hits = _scan_sensitive_files(root)

    add_check("folder", "Folder exists", bool(inventory.get("exists")), "The workspace folder can be inspected.", proof=str(root))
    add_check("index.html", "index.html exists", has_index, "The client site has a public entry page.", proof=str(index_path))
    add_check("target_url", "Target URL present", bool(target_url), "The QR, flyer, or app has a destination/buyer path.")
    if target_url:
        add_check("target_url_in_index", "Target URL is linked in index", route_mentions_target, "The generated page points visitors to the intended action.", severity="warn")
    add_check("course_packet", "Course packet saved", has_course_packet, "The open-source course record is saved in the folder.", proof=str(root / "codee-course.json"))
    add_check("activation_packet", "Activation packet saved", has_activation_packet, "The paid-hosting activation contract is saved locally.", proof=str(root / ".codee" / "course-activation.json"))
    add_check("service_match", "Service lane recognized", bool(rules), f"Codee recognized this as {rules.get('label') if rules else service}.")
    add_check("assets", "Assets available", has_assets, "Client images, logos, PDFs, or media should be present before paid activation.", severity="warn")
    add_check("sensitive-files", "No sensitive files in workspace", not sensitive_hits, "Secrets, private keys, tokens, and .env files must not be submitted or attached.", severity="warn", proof=", ".join(item["path"] for item in sensitive_hits[:5]))
    if service == "codeeapp250":
        add_check("guidebook_asset", "Guidebook or cover available", bool(has_pdfs or has_images), "CodeeApp250 should include a PDF/guidebook or cover image before fulfillment.", severity="warn")
    if service in {"codeeflyer", "codeeflyer250"}:
        add_check("flyer_asset", "Flyer or logo image available", has_images, "CodeeFlyer should include at least one visual asset before fulfillment.", severity="warn")
    add_check("backend_connection", "Backend connection saved", has_backend_connection, "Run codee connect so Codee backend can attach delivery room, workbench, and activation timeline.", severity="warn")
    add_check("payment_gate", "Payment gate enforced", not has_payment_proof or bool(connection.get("requires_payment", True)), "Hosted activation stays locked until Stripe/payment verification.", severity="warn")

    route_results: list[dict[str, Any]] = []
    if args.route_check and target_url.startswith(("http://", "https://")):
        route = _route_check({"name": "target-url", "url": target_url, "expected": [200, 301, 302, 307, 308]}, float(args.timeout))
        route_results.append(route)
        add_check("target_route", "Target URL route opens", bool(route.get("ok")), f"HTTP {route.get('status')} via {route.get('transport')}.", proof=target_url)

    live_status: dict[str, Any] = {}
    if args.live and connection.get("connection_id"):
        live_status = _request_json("GET", _api_url(args.api_base, f"/api/codee/cli/connection/{connection.get('connection_id')}"), timeout=float(args.timeout))
        add_check("backend_live_status", "Backend connection can be read", bool(live_status.get("ok")), "The public API can retrieve this connection record.", severity="warn")

    fail_count = sum(1 for item in checks if not item.get("ok") and item.get("severity") == "fail")
    warn_count = sum(1 for item in checks if not item.get("ok") and item.get("severity") != "fail")
    ok = fail_count == 0 and (warn_count == 0 if args.strict else True)
    activation_status = str(connection.get("activation_status") or ("local_generated_payment_required" if has_activation_packet else "local_only"))
    timeline = _activation_timeline(
        status=activation_status,
        payment_verified=bool(has_payment_proof and license_payload.get("paid")),
        has_assets=has_assets,
        hosted_url=str(connection.get("delivery_url") or connection.get("hosted_url") or ""),
        backend_connected=has_backend_connection,
    )
    next_commands = [
        f"python3 codee.py connect {root} --service {service} --email {payload.get('account_email') or 'owner@example.com'}",
        f"python3 codee.py activate {root} --service {service}",
        f"python3 codee.py support {root} --service {service} --message \"Review my verified folder and activate hosted delivery after payment/uploads.\" --submit",
    ]
    report = {
        "ok": ok,
        "schema": "codee.verify.v1",
        "created_at": _now(),
        "version": VERSION,
        "workspace_id": payload.get("workspace_id"),
        "codee_user_id": payload.get("codee_user_id"),
        "service": service,
        "service_label": rules.get("label") if rules else service,
        "activation_status": activation_status,
        "strict": bool(args.strict),
        "payment_required": True,
        "hosted_activation_locked_until": ["payment_verified", "uploads_verified", "scan_passed"],
        "required_uploads": rules.get("required_uploads") if rules else [],
        "checks": checks,
        "fail_count": fail_count,
        "warn_count": warn_count,
        "route_results": route_results,
        "sensitive_files": sensitive_hits,
        "live_status": live_status,
        "activation_timeline": timeline,
        "next_commands": next_commands,
        "payload": payload,
    }
    report_path = _write_report(root, "latest-codee-verify.json", report)
    _write_text(root / ".codee" / "CODEE_VERIFY.md", _verify_markdown(report), force=True)
    _append_event(root, "PostVerify", {"ok": ok, "service": service, "fail_count": fail_count, "warn_count": warn_count, "report": str(report_path)})
    if args.json:
        print(json.dumps(report | {"report": str(report_path)}, indent=2))
    else:
        print(f"Codee verify: ok={ok} service={service} fails={fail_count} warnings={warn_count}")
        for item in checks:
            if item.get("ok"):
                continue
            print(f"{item.get('severity').upper()}: {item.get('label')} - {item.get('copy')}")
        print(f"timeline={root / '.codee' / 'CODEE_VERIFY.md'}")
        print(f"report={report_path}")
    return 0 if ok else 1


def command_money_map(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _load_manifest(root)
    business = (args.business or str(manifest.get("business") or "Codee Client")).strip()
    mission = str(manifest.get("mission") or "Turn one business idea into a simple income-ready digital service.").strip()
    audience = args.audience.strip() or "local businesses, creators, and operators who need a cleaner digital launch path"
    service = args.service.strip() or "one focused starter service"
    offer = args.offer.strip() or f"{service} with a clear page, CTA, checkout path, delivery path, and route scan"

    first_offer_steps = [
        "Pick one painful problem the audience already understands.",
        "Package the first version as one narrow service, not a giant platform.",
        "Create a public page, QR/flyer route, or Codee App example that shows the outcome.",
        "Connect one payment path and one delivery room or download path.",
        "Run a route scan and save proof before outreach starts.",
        "Send the offer to ten specific prospects with a direct link and a simple ask.",
        "Use responses to improve the offer before adding more features."
    ]
    service_ladder = [
        {"lane": "QRCODEE", "purpose": "Offline-to-online scan route for one offer."},
        {"lane": "Codee Flyer 100", "purpose": "Single hosted promo with one CTA."},
        {"lane": "Codee Flyer 250", "purpose": "Richer flyer request with QR, assets, and revision support."},
        {"lane": "Codee App 250", "purpose": "Hosted page for a guide, product, ebook, or simple tool."},
        {"lane": "Codee Business Suite", "purpose": "Bundle the earlier assets into a supported business presence."}
    ]
    proof_checks = [
        "Does the offer page open on mobile?",
        "Is the CTA visible without confusion?",
        "Does checkout or contact routing work?",
        "Does delivery happen in a place the client can return to?",
        "Did the latest scan save a report in .codee/reports?"
    ]
    payload = {
        "ok": True,
        "version": VERSION,
        "created_at": _now(),
        "business": business,
        "mission": mission,
        "audience": audience,
        "service": service,
        "offer": offer,
        "important_note": "This is a launch plan, not a revenue guarantee. Codee helps reduce confusion, speed up delivery, and prove routes before outreach.",
        "first_offer_steps": first_offer_steps,
        "service_ladder": service_ladder,
        "proof_checks": proof_checks,
    }
    report_dir = root / ".codee" / "reports"
    report_dir.mkdir(parents=True, exist_ok=True)
    json_path = report_dir / "quick-income-map.json"
    md_path = report_dir / "quick-income-map.md"
    json_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
    md = f"""# Codee Quick Income Map

Business: {business}

Audience: {audience}

Mission: {mission}

First offer: {offer}

Important: this is a launch plan, not a revenue guarantee. Codee helps reduce confusion, speed up delivery, and prove routes before outreach.

## Fastest Responsible Path

1. {first_offer_steps[0]}
2. {first_offer_steps[1]}
3. {first_offer_steps[2]}
4. {first_offer_steps[3]}
5. {first_offer_steps[4]}
6. {first_offer_steps[5]}
7. {first_offer_steps[6]}

## Service Ladder

- QRCODEE: Offline-to-online scan route for one offer.
- Codee Flyer 100: Single hosted promo with one CTA.
- Codee Flyer 250: Richer flyer request with QR, assets, and revision support.
- Codee App 250: Hosted page for a guide, product, ebook, or simple tool.
- Codee Business Suite: Bundle the earlier assets into a supported business presence.

## Proof Before Outreach

- Does the offer page open on mobile?
- Is the CTA visible without confusion?
- Does checkout or contact routing work?
- Does delivery happen in a place the client can return to?
- Did the latest scan save a report in `.codee/reports`?
"""
    md_path.write_text(md, encoding="utf-8")
    if args.json:
        print(json.dumps(payload, indent=2))
    else:
        print("Codee quick income map: ready")
        print(f"business={business}")
        print(f"offer={offer}")
        print(f"markdown={md_path}")
        print(f"json={json_path}")
    return 0


def command_toolkit(args: argparse.Namespace) -> int:
    payload = {
        "ok": True,
        "created_at": _now(),
        "cli_version": VERSION,
        "toolkit": TOOLKIT_STACK,
        "commands": [
            "python3 codee.py toolkit-init ./codee-open-source-toolkit --business \"My Business\" --force",
            "python3 codee.py admin-training ./codee-open-source-toolkit --write --force",
            "python3 codee.py folder-plan ./codee-open-source-toolkit --business \"My Business\" --service codee-toolkit --write --force",
            "python3 codee.py domain-plan ./codee-open-source-toolkit --domain example.com --target-url https://example.com --write --force",
            "python3 codee.py business-assistant-init ./restaurant-assistant --business-type restaurant --business \"My Restaurant\" --force",
            "python3 codee.py toolkit-smoke ./codee-open-source-toolkit",
            "python3 codee.py skill-check browser-scan ./codee-open-source-toolkit",
            "python3 codee.py browser-scan ./codee-open-source-toolkit --url https://clients.codee.chat/codee-toolkit.html --full-page",
        ],
        "rule": "The toolkit should be the one-folder starting point for anyone using the Codee open-source course tools.",
    }
    if args.json:
        print(json.dumps(payload, indent=2))
        return 0
    print("Codee Open-Source Toolkit")
    print(TOOLKIT_STACK["purpose"])
    print("")
    print("Core courses:")
    for course_id in TOOLKIT_COURSES:
        course = _course_by_id(course_id)
        print(f"- {course_id}: {course.get('name')}")
    print("")
    print("Start:")
    for cmd in payload["commands"]:
        print(cmd)
    return 0


def command_folder_plan(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    if args.write:
        root.mkdir(parents=True, exist_ok=True)
    manifest = _load_manifest(root) if (root / ".codee" / "codee.json").exists() else {}
    business = str(args.business or manifest.get("business") or "My Business").strip()
    service = str(args.service or manifest.get("service") or "codee-service").strip()
    domain = str(args.domain or "").strip()
    inventory = _folder_inventory(root)
    missing = []
    if not inventory.get("exists"):
        missing.append("Create the root folder before trying to host or support the service.")
    if not inventory.get("has_index"):
        missing.append("Add index.html so the folder has a clear first page.")
    if not inventory.get("has_assets"):
        missing.append("Add assets/ for logos, images, PDFs, videos, and downloadable files.")
    if not (root / ".codee" / "codee.json").exists():
        missing.append("Add .codee/codee.json so Codee knows the business, owner, route, and service lane.")
    next_commands = [
        f"python3 codee.py init {root} --business \"{business}\" --force",
        f"python3 codee.py folder-plan {root} --business \"{business}\" --service {service} --write --force",
    ]
    if domain:
        next_commands.append(f"python3 codee.py domain-plan {root} --domain {domain} --write --force")
    next_commands.extend([
        f"python3 codee.py scan {root} --url https://clients.codee.chat/codee-folder-domain.html",
        f"python3 codee.py support {root} --service {service} --message \"Review my folder and help me prepare it for hosting.\"",
    ])
    payload = {
        "ok": True,
        "created_at": _now(),
        "cli_version": VERSION,
        "business": business,
        "service": service,
        "domain": domain,
        "root": str(root),
        "inventory": inventory,
        "missing": missing,
        "teaching_steps": FOLDER_ASSIST_STEPS,
        "folder_contract": {
            "index": "index.html is the first page Codee should host or scan.",
            "assets": "assets/ stores client images, logos, downloads, and media.",
            "codee": ".codee/ stores identity, routes, reports, support packets, and skill policy.",
            "reports": ".codee/reports/ stores proof after scans and checks.",
        },
        "next_commands": next_commands,
    }
    report_path = ""
    if args.write:
        codee_dir = root / ".codee"
        codee_dir.mkdir(parents=True, exist_ok=True)
        _write_json(codee_dir / "folder-plan.json", payload, force=bool(args.force))
        _write_text(codee_dir / "FOLDER_PLAN.md", _folder_plan_markdown(payload), force=bool(args.force))
        report_path = str(_write_report(root, "latest-folder-plan.json", payload))
    if args.json:
        print(json.dumps(payload | {"report": report_path}, indent=2))
        return 0
    print(f"Codee folder plan: ok=True folder={root}")
    print(f"business={business}")
    print(f"service={service}")
    print(f"has_index={inventory.get('has_index')} has_assets={inventory.get('has_assets')} files={inventory.get('total_files')}")
    if missing:
        print("missing:")
        for item in missing:
            print(f"- {item}")
    if report_path:
        print(f"report={report_path}")
    return 0


def command_domain_plan(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    if args.write:
        root.mkdir(parents=True, exist_ok=True)
    manifest = _load_manifest(root) if (root / ".codee" / "codee.json").exists() else {}
    business = str(args.business or manifest.get("business") or "My Business").strip()
    domain = str(args.domain or "").strip().replace("https://", "").replace("http://", "").strip("/")
    target_url = str(args.target_url or "").strip()
    if not target_url and domain:
        target_url = f"https://{domain}"
    route_check: dict[str, Any] = {}
    if target_url and str(target_url).startswith(("http://", "https://")) and not args.no_scan:
        route_check = _route_check({"name": "domain-target", "url": target_url, "expected": [200, 301, 302]}, float(args.timeout))
    proof_checks = [
        "Registrar account can open the DNS settings.",
        "Hosting provider shows the exact DNS records to copy.",
        "SSL certificate is active before public promotion.",
        "Primary route and redirect route both avoid 404.",
        "Final route scan is saved under .codee/reports.",
    ]
    next_commands = [
        f"python3 codee.py domain-plan {root} --domain {domain or 'example.com'} --target-url {target_url or 'https://example.com'} --write --force",
    ]
    if target_url:
        next_commands.append(f"python3 codee.py scan {root} --url {target_url}")
        next_commands.append(f"python3 codee.py browser-scan {root} --url {target_url} --full-page")
    next_commands.append(f"python3 codee.py support {root} --service domain-support --message \"Help me prove this domain is connected and ready.\"")
    payload = {
        "ok": bool(not route_check or route_check.get("ok")),
        "created_at": _now(),
        "cli_version": VERSION,
        "business": business,
        "root": str(root),
        "domain": domain,
        "target_url": target_url,
        "registrar": str(args.registrar or "GoDaddy").strip(),
        "hosting": str(args.hosting or "Codee hosting").strip(),
        "rule": "A domain is not ready because it was purchased. It is ready when DNS, SSL, route scan, and browser proof all pass.",
        "dns_records_to_confirm": [
            "CNAME for www or service subdomain when the hosting provider asks for one.",
            "A or ALIAS/ANAME records for the naked domain only when the hosting provider gives exact values.",
            "TXT verification records when the hosting or search provider asks for ownership proof.",
            "Redirect rule from the unused route to the route the client will actually share.",
        ],
        "teaching_steps": DOMAIN_ASSIST_STEPS,
        "proof_checks": proof_checks,
        "route_check": route_check,
        "next_commands": next_commands,
    }
    report_path = ""
    if args.write:
        codee_dir = root / ".codee"
        codee_dir.mkdir(parents=True, exist_ok=True)
        _write_json(codee_dir / "domain-plan.json", payload, force=bool(args.force))
        _write_text(codee_dir / "DOMAIN_PLAN.md", _domain_plan_markdown(payload), force=bool(args.force))
        report_path = str(_write_report(root, "latest-domain-plan.json", payload))
    if args.json:
        print(json.dumps(payload | {"report": report_path}, indent=2))
        return 0
    print(f"Codee domain plan: ok={payload['ok']} domain={domain or 'not set'}")
    print(f"target_url={target_url or 'not set'}")
    if route_check:
        print(f"route_status={route_check.get('status')} route_ok={route_check.get('ok')}")
    if report_path:
        print(f"report={report_path}")
    return 0 if payload["ok"] else 1


def command_admin_training(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = {
        "ok": True,
        "created_at": _now(),
        "cli_version": VERSION,
        "training": ADMIN_TRAINING,
        "public_page": f"{DEFAULT_API_BASE}/codee-admin-training.html",
        "recommended_commands": [
            "python3 codee.py admin-training . --write",
            "python3 codee.py folder-plan . --business \"My Business\" --service codee-service --write",
            "python3 codee.py domain-plan . --domain example.com --target-url https://example.com --write",
            "python3 codee.py business-types",
            "python3 codee.py toolkit-init ./codee-open-source-toolkit --business \"My Business\" --force",
            "python3 codee.py toolkit-smoke ./codee-open-source-toolkit",
            "python3 codee.py browser-scan ./codee-open-source-toolkit --url https://clients.codee.chat/codee-admin-training.html --full-page",
        ],
        "rule": "Open source teaches the lane. Done-for-you sells execution. Recurring charges should attach to hosting, scans, storage, support, or an active service window.",
    }
    report_path = ""
    if args.write:
        codee_dir = root / ".codee"
        codee_dir.mkdir(parents=True, exist_ok=True)
        _write_json(codee_dir / "admin-training.json", payload, force=bool(args.force))
        _write_text(codee_dir / "ADMIN_TRAINING.md", _admin_training_markdown(ADMIN_TRAINING), force=bool(args.force))
        report_path = str(_write_report(root, "latest-admin-training.json", payload))
    if args.json:
        print(json.dumps(payload | {"report": report_path}, indent=2))
        return 0
    print("Codee Admin Training")
    print(ADMIN_TRAINING["purpose"])
    print("")
    print("Tier rule:")
    print(payload["rule"])
    print("")
    print("Platform stack:")
    for item in ADMIN_TRAINING["platform_stack"]:
        print(f"- {item['platform']}: {item['role']}")
    print("")
    print("Open-source and paid lanes:")
    for item in ADMIN_TRAINING["tier_ladder"]:
        print(f"- {item['tier']}: {item['payment_model']} {item['recurring']}")
    if report_path:
        print(f"report={report_path}")
    return 0


def command_admin_guidebook(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = {
        "ok": True,
        "created_at": _now(),
        "cli_version": VERSION,
        "title": "Codee Admin Training Guidebook",
        "subtitle": "Ten-page operating guide for teaching, selling, hosting, proving, and scaling Codee.",
        "rule": "The guidebook is a live page, not a flat image. Codee should render readable pages from structured content, then prove every link and route.",
        "owner_page": f"{DEFAULT_API_BASE}/codee-admin-guidebook.html",
        "json_page": f"{DEFAULT_API_BASE}/assets/codee/codee-admin-guidebook.json",
        "codeemail_page": f"{DEFAULT_API_BASE}/codeemail.html",
        "pages": ADMIN_GUIDEBOOK_PAGES,
        "sources": [
            {"label": "OpenAI Codex", "url": "https://openai.com/index/codex-now-generally-available/"},
            {"label": "Claude Code", "url": "https://code.claude.com/docs/en/how-claude-code-works"},
            {"label": "Gemini CLI", "url": "https://google-gemini.github.io/gemini-cli/"},
            {"label": "OpenAI Canvas", "url": "https://academy.openai.com/public/clubs/work-users-ynjqu/resources/canvas"},
            {"label": "GitHub Copilot cloud agent", "url": "https://docs.github.com/en/copilot/concepts/agents/cloud-agent/about-cloud-agent"},
        ],
        "recommended_commands": [
            "python3 codee.py admin-guidebook . --write",
            "python3 codee.py scan . --url https://clients.codee.chat/codee-admin-guidebook.html",
            "python3 codee.py browser-scan . --url https://clients.codee.chat/codee-admin-guidebook.html --full-page",
            "python3 codee.py course-smoke --json",
        ],
    }
    report_path = ""
    if args.write:
        codee_dir = root / ".codee"
        codee_dir.mkdir(parents=True, exist_ok=True)
        _write_json(codee_dir / "admin-guidebook.json", payload, force=bool(args.force))
        _write_text(codee_dir / "ADMIN_GUIDEBOOK.md", _admin_guidebook_markdown(payload), force=bool(args.force))
        report_path = str(_write_report(root, "latest-admin-guidebook.json", payload))
    if args.json:
        print(json.dumps(payload | {"report": report_path}, indent=2))
        return 0
    print(payload["title"])
    print(payload["subtitle"])
    print("")
    print(f"Owner page: {payload['owner_page']}")
    print(f"JSON page: {payload['json_page']}")
    print("")
    for page in ADMIN_GUIDEBOOK_PAGES:
        print(f"- Page {page['number']}: {page['title']} ({page['tag']})")
    if report_path:
        print(f"report={report_path}")
    return 0


def command_admin_certify(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    codee_dir = root / ".codee"
    admin_json = _read_json_if_exists(codee_dir / "admin-training.json")
    toolkit_json = _read_json_if_exists(root / "codee-toolkit.json")
    skill_policy = _read_json_if_exists(codee_dir / "skills.json")
    route_report = _read_json_if_exists(codee_dir / "reports" / "latest-route-scan.json")
    browser_report = _read_json_if_exists(codee_dir / "reports" / "latest-browser-scan.json")
    support_report = _read_json_if_exists(codee_dir / "reports" / "latest-support-request.json")
    delivery_report = _read_json_if_exists(codee_dir / "reports" / "latest-delivery-room.json")
    certification_items = ADMIN_TRAINING.get("certification_checks") or []
    admin_stack = (((admin_json.get("training") or {}).get("platform_stack")) or ADMIN_TRAINING["platform_stack"]) if isinstance(admin_json, dict) else ADMIN_TRAINING["platform_stack"]
    admin_tiers = (((admin_json.get("training") or {}).get("tier_ladder")) or ADMIN_TRAINING["tier_ladder"]) if isinstance(admin_json, dict) else ADMIN_TRAINING["tier_ladder"]
    screenshot_path = str(((browser_report.get("screenshot") or {}).get("path")) or "")
    local_checks = [
        {
            "name": "admin-training-json",
            "ok": bool(admin_json and admin_json.get("ok") and (codee_dir / "admin-training.json").exists()),
            "summary": "Admin training JSON exists and loads.",
            "next_action": "Run `python3 codee.py admin-training . --write --force`.",
        },
        {
            "name": "admin-training-markdown",
            "ok": (codee_dir / "ADMIN_TRAINING.md").exists(),
            "summary": "Admin training markdown exists for human review.",
            "next_action": "Run `python3 codee.py admin-training . --write --force`.",
        },
        {
            "name": "platform-stack-covered",
            "ok": len(admin_stack) >= 7,
            "summary": "Training covers domain, hosting, backend, storage, payments, delivery, email, and proof layers.",
            "next_action": "Review the platform stack section and add missing platform responsibilities.",
        },
        {
            "name": "tier-ladder-covered",
            "ok": len(admin_tiers) >= 4,
            "summary": "Training separates open source, done-for-you, hosting/support, and Business Suite.",
            "next_action": "Review the tier ladder and keep recurring fees tied to ongoing value.",
        },
        {
            "name": "toolkit-workspace",
            "ok": bool(toolkit_json.get("schema") == "codee.toolkit.v1"),
            "summary": "Toolkit workspace exists with course folders and routes.",
            "next_action": "Run `python3 codee.py toolkit-init . --business \"My Business\" --force` inside a toolkit folder.",
        },
        {
            "name": "skill-policy",
            "ok": bool(skill_policy.get("ok") or skill_policy.get("schema") == "codee.skills.policy.v1"),
            "summary": "Workspace has a skill policy separating public and credential-gated tools.",
            "next_action": "Run `python3 codee.py skill-policy . --preset operator --force`.",
        },
        {
            "name": "latest-route-scan",
            "ok": bool(route_report.get("ok")),
            "summary": "Latest route scan report is passing.",
            "next_action": "Run `python3 codee.py scan . --url https://clients.codee.chat/codee-admin-training.html --url https://clients.codee.chat/codee-toolkit.html`.",
        },
        {
            "name": "latest-browser-scan",
            "ok": bool(browser_report.get("ok") and screenshot_path),
            "summary": "Latest browser proof includes a screenshot artifact.",
            "next_action": "Run `python3 codee.py browser-scan . --url https://clients.codee.chat/codee-admin-training.html --full-page`.",
        },
        {
            "name": "support-or-delivery-path",
            "ok": bool(support_report.get("ok") or delivery_report.get("ok")),
            "summary": "Workspace has a support request or delivery-room proof path.",
            "next_action": "Run `python3 codee.py room . --service admin-training` or create a support request packet.",
        },
    ]
    route_checks = []
    if not args.local_only:
        targets = [
            {"name": "codee-admin-training", "url": f"{DEFAULT_API_BASE}/codee-admin-training.html", "expected": [200]},
            {"name": "codee-toolkit", "url": f"{DEFAULT_API_BASE}/codee-toolkit.html", "expected": [200]},
            {"name": "codee-workbench", "url": f"{DEFAULT_API_BASE}/codee-workbench.html", "expected": [200]},
            {"name": "codee-skills", "url": f"{DEFAULT_API_BASE}/codee-skills.html", "expected": [200]},
        ]
        for url in args.url or []:
            targets.append({"name": str(url).split("?")[0].rstrip("/").rsplit("/", 1)[-1] or "custom-url", "url": url, "expected": [200]})
        route_checks = [_route_check(item, float(args.timeout)) for item in targets]
    passed = sum(1 for item in local_checks if item["ok"]) + sum(1 for item in route_checks if item.get("ok"))
    total = len(local_checks) + len(route_checks)
    score = int(round((passed / total) * 100)) if total else 0
    failed = [item for item in local_checks if not item["ok"]] + [item for item in route_checks if not item.get("ok")]
    if score >= 90 and not failed:
        status = "certified"
    elif score >= 75:
        status = "operator-ready-with-gaps"
    else:
        status = "needs-more-proof"
    next_actions = [str(item.get("next_action") or f"Fix {item.get('name')}") for item in local_checks if not item["ok"]]
    next_actions += [
        f"Fix route {item.get('name')} status={item.get('status')} url={item.get('url')}"
        for item in route_checks
        if not item.get("ok")
    ]
    payload = {
        "ok": status == "certified",
        "created_at": _now(),
        "cli_version": VERSION,
        "root": str(root),
        "score": score,
        "status": status,
        "checks": local_checks,
        "route_checks": route_checks,
        "certification_items": certification_items,
        "failed": failed,
        "next_actions": next_actions,
        "rule": "Admin readiness is proof-based: training files, tier clarity, live route checks, browser proof, and support/delivery path.",
    }
    report_path = _write_report(root, "latest-admin-certification.json", payload)
    md_path = codee_dir / "ADMIN_CERTIFICATION.md"
    _write_text(md_path, _admin_certification_markdown(payload), force=True)
    if args.json:
        print(json.dumps(payload | {"report": str(report_path), "markdown": str(md_path)}, indent=2))
    else:
        print(f"Codee admin certification: status={status} score={score}% failed={len(failed)}")
        for item in next_actions:
            print(f"next={item}")
        print(f"report={report_path}")
        print(f"markdown={md_path}")
    return 0 if payload["ok"] else 1


def command_business_types(args: argparse.Namespace) -> int:
    payload = {
        "ok": True,
        "created_at": _now(),
        "cli_version": VERSION,
        "business_types": BUSINESS_ASSISTANT_TYPES,
        "public_page": f"{DEFAULT_API_BASE}/codee-business-types.html",
        "teacher_page": f"{DEFAULT_API_BASE}/codee-course-teacher.html",
        "rule": "Every business type gets its own assistant, but each assistant still follows the same Codee proof system: intake, lane, deliverable, support logic, scan proof.",
    }
    if args.json:
        print(json.dumps(payload, indent=2))
        return 0
    print("Codee business-type assistants")
    print(payload["rule"])
    print("")
    for item in BUSINESS_ASSISTANT_TYPES:
        print(f"- {item['id']}: {item['assistant_name']} - {item['first_offer']}")
    return 0


def command_business_assistant_init(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    business_type = _business_type_by_id(args.business_type)
    business = str(args.business or business_type.get("name") or "Codee Client").strip()
    owner_email = str(args.email or "").strip().lower()
    client_id = _slugify(args.client_id or business)
    force = bool(args.force)
    root.mkdir(parents=True, exist_ok=True)
    codee_dir = root / ".codee"
    codee_dir.mkdir(parents=True, exist_ok=True)
    manifest = {
        "schema": "codee.platform.v0",
        "version": VERSION,
        "created_at": _now(),
        "business": business,
        "owner": str(args.owner or "Business Owner"),
        "owner_email": owner_email,
        "codee_user_id": _codee_user_id(owner_email, f"{business}:{business_type['id']}"),
        "client_id": client_id,
        "business_type": business_type["id"],
        "mission": f"Use {business_type['assistant_name']} to turn {business_type['audience']} into one clear Codee service path.",
    }
    routes = [
        {"name": "codee-course-teacher", "url": f"{DEFAULT_API_BASE}/codee-course-teacher.html?business={business_type['id']}", "expected": [200]},
        {"name": "codee-business-types", "url": f"{DEFAULT_API_BASE}/codee-business-types.html", "expected": [200]},
        {"name": "codee-chat-business-assistant", "url": f"{DEFAULT_API_BASE}/codee-chat.html?service=business-assistant&business_type={business_type['id']}", "expected": [200]},
    ]
    payload = {
        "schema": "codee.business_assistant.v1",
        "ok": True,
        "created_at": _now(),
        "cli_version": VERSION,
        "business": business,
        "assistant": business_type,
        "tier_rule": "Open source teaches this assistant lane. Done-for-you sells the first build. Recurring support only applies to hosting, scans, storage, edits, or an active support window.",
        "routes": routes,
        "next_commands": [
            f"python3 codee.py business-types --json",
            f"python3 codee.py scan {root} --url {DEFAULT_API_BASE}/codee-course-teacher.html?business={business_type['id']} --url {DEFAULT_API_BASE}/codee-business-types.html",
            f"python3 codee.py browser-scan {root} --url {DEFAULT_API_BASE}/codee-course-teacher.html?business={business_type['id']} --full-page",
            f"python3 codee.py support {root} --service business-assistant --message \"Help me package {business_type['name']} into a hosted Codee lane.\"",
        ],
    }
    writes = {
        "manifest": _write_json(codee_dir / "codee.json", manifest, force=force),
        "assistant": _write_json(codee_dir / "business-assistant.json", payload, force=force),
        "markdown": _write_text(root / "BUSINESS_ASSISTANT.md", _business_assistant_markdown(payload), force=force),
        "html": _write_text(root / "business-assistant.html", _business_assistant_html(payload), force=force),
        "routes": _write_json(codee_dir / "routes.json", routes, force=force),
    }
    report_path = _write_report(root, "latest-business-assistant.json", payload | {"writes": writes})
    if args.json:
        print(json.dumps({"ok": True, "root": str(root), "writes": writes, "assistant": business_type, "report": str(report_path)}, indent=2))
    else:
        print(f"Codee business assistant ready: {business_type['assistant_name']}")
        print(f"business={business}")
        print(f"root={root}")
        print(f"report={report_path}")
        if not all(writes.values()):
            print("Some files already existed. Use --force to overwrite.")
    return 0


def command_toolkit_init(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    business = str(args.business or "My Business").strip()
    target_base = str(args.target_base or f"{DEFAULT_API_BASE}/index2income").strip().rstrip("/")
    force = bool(args.force)
    root.mkdir(parents=True, exist_ok=True)
    codee_dir = root / ".codee"
    codee_dir.mkdir(parents=True, exist_ok=True)
    policy = _build_skill_policy(preset=args.preset, enabled_extra=["support-room"], disabled=[])
    courses = []
    course_results = []
    for course_id in TOOLKIT_COURSES:
        target_url = _toolkit_target_url(target_base, course_id)
        course_root = root / "courses" / course_id
        result = _write_course_workspace(course_root, course_id=course_id, business=business, target_url=target_url, force=force)
        course_results.append(result)
        course = _course_by_id(course_id)
        courses.append({
            "id": course_id,
            "name": course.get("name"),
            "lesson": course.get("lesson"),
            "folder": f"courses/{course_id}",
            "target_url": target_url,
        })
    routes = [
        {"name": "codee-toolkit", "url": f"{DEFAULT_API_BASE}/codee-toolkit.html", "expected": [200]},
        {"name": "codee-workbench", "url": f"{DEFAULT_API_BASE}/codee-workbench.html", "expected": [200]},
        {"name": "codee-skills", "url": f"{DEFAULT_API_BASE}/codee-skills.html", "expected": [200]},
        {"name": "index2income", "url": f"{DEFAULT_API_BASE}/index2income/", "expected": [200]},
    ] + [
        {"name": f"course-{item['id']}", "url": item["target_url"], "expected": [200]}
        for item in courses
    ]
    payload = {
        "schema": "codee.toolkit.v1",
        "ok": True,
        "version": VERSION,
        "toolkit_version": TOOLKIT_STACK["version"],
        "created_at": _now(),
        "business": business,
        "purpose": TOOLKIT_STACK["purpose"],
        "target_base": target_base,
        "courses": courses,
        "skill_policy": policy,
        "routes": routes,
        "next_commands": [
            "python3 codee.py skills --access public",
            f"python3 codee.py admin-training {root} --write --force",
            f"python3 codee.py folder-plan {root} --business \"{business}\" --service codee-toolkit --write --force",
            f"python3 codee.py domain-plan {root} --domain example.com --target-url https://example.com --write --force",
            f"python3 codee.py skill-policy {root} --preset {args.preset} --force",
            f"python3 codee.py toolkit-smoke {root}",
            f"python3 codee.py browser-scan {root} --url {DEFAULT_API_BASE}/codee-toolkit.html --full-page",
            f"python3 codee.py support {root} --service codee-toolkit --message \"I finished the toolkit export and want hosting support.\"",
        ],
    }
    manifest = {
        "schema": "codee.platform.v0",
        "version": VERSION,
        "created_at": _now(),
        "business": business,
        "owner": str(args.owner or "Business Owner"),
        "owner_email": str(args.email or "").strip().lower(),
        "codee_user_id": _codee_user_id(str(args.email or "").strip().lower(), str(root)),
        "client_id": _slugify(args.client_id or business),
        "mission": "Use the Codee open-source toolkit to turn one idea into course outputs, scans, and support-ready proof.",
    }
    writes = {
        "toolkit": _write_json(root / "codee-toolkit.json", payload, force=force),
        "readme": _write_text(root / "README.md", _toolkit_readme(payload), force=force),
        "index": _write_text(root / "index.html", _toolkit_hub_html(payload), force=force),
        "manifest": _write_json(codee_dir / "codee.json", manifest, force=force),
        "routes": _write_json(codee_dir / "routes.json", routes, force=force),
        "skills": _write_json(codee_dir / "skills.json", policy, force=force),
        "skills_md": _write_text(codee_dir / "SKILLS.md", _skill_policy_markdown(policy), force=force),
    }
    report_path = _write_report(root, "latest-toolkit-init.json", {
        "ok": True,
        "created_at": _now(),
        "root": str(root),
        "writes": writes,
        "course_results": course_results,
        "toolkit": payload,
    })
    if args.json:
        print(json.dumps({"ok": True, "root": str(root), "writes": writes, "courses": course_results, "report": str(report_path)}, indent=2))
    else:
        print(f"Codee toolkit ready: {root}")
        print(f"courses={len(courses)}")
        print(f"report={report_path}")
        if not all(writes.values()):
            print("Some files already existed. Use --force to overwrite.")
    return 0


def command_toolkit_smoke(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    toolkit_path = root / "codee-toolkit.json"
    toolkit = _read_json_if_exists(toolkit_path)
    courses = toolkit.get("courses") if isinstance(toolkit.get("courses"), list) else []
    local_checks = [
        {"name": "toolkit-json", "ok": bool(toolkit_path.exists() and toolkit.get("schema") == "codee.toolkit.v1"), "path": str(toolkit_path)},
        {"name": "hub-index", "ok": (root / "index.html").exists(), "path": str(root / "index.html")},
        {"name": "readme", "ok": (root / "README.md").exists(), "path": str(root / "README.md")},
        {"name": "skill-policy", "ok": (root / ".codee" / "skills.json").exists(), "path": str(root / ".codee" / "skills.json")},
        {"name": "skill-policy-markdown", "ok": (root / ".codee" / "SKILLS.md").exists(), "path": str(root / ".codee" / "SKILLS.md")},
    ]
    for course_id in TOOLKIT_COURSES:
        course_root = root / "courses" / course_id
        packet = _read_json_if_exists(course_root / "codee-course.json")
        local_checks.append({
            "name": f"course-{course_id}",
            "ok": bool(
                (course_root / "README.md").exists()
                and (course_root / "index.html").exists()
                and packet.get("course_id") == course_id
                and str(packet.get("target_url") or "").startswith(("http://", "https://"))
            ),
            "path": str(course_root),
            "target_url": packet.get("target_url", ""),
        })
    route_checks = []
    if not args.local_only:
        route_targets = toolkit.get("routes") if isinstance(toolkit.get("routes"), list) else []
        route_checks = [_route_check(item, float(args.timeout)) for item in route_targets if isinstance(item, dict) and str(item.get("url") or "").startswith(("http://", "https://"))]
    payload = {
        "ok": bool(all(item["ok"] for item in local_checks) and all(item.get("ok") for item in route_checks)),
        "created_at": _now(),
        "root": str(root),
        "local_checks": local_checks,
        "route_checks": route_checks,
        "failed": [item for item in local_checks if not item["ok"]] + [item for item in route_checks if not item.get("ok")],
    }
    report_path = _write_report(root, "latest-toolkit-smoke.json", payload)
    if args.json:
        print(json.dumps(payload | {"report": str(report_path)}, indent=2))
    else:
        print(f"Codee toolkit smoke: ok={payload['ok']} local={len(local_checks)} routes={len(route_checks)} failed={len(payload['failed'])}")
        for item in payload["failed"]:
            print(f"failed={item.get('name')} path={item.get('path', '')} url={item.get('url', '')}")
        print(f"report={report_path}")
    return 0 if payload["ok"] else 1


def command_pricing(args: argparse.Namespace) -> int:
    if args.local:
        payload = dict(LOCAL_PRICING)
    else:
        try:
            payload = _request_json("GET", _api_url(args.api_base, "/api/stripe/codee-cli/pricing"), timeout=float(args.timeout))
            if not payload.get("ok"):
                payload = dict(LOCAL_PRICING) | {"remote_error": payload}
        except Exception as exc:
            payload = dict(LOCAL_PRICING) | {"remote_error": f"{type(exc).__name__}: {exc}"}
    if args.json:
        print(json.dumps(payload, indent=2))
    else:
        _print_pricing(payload)
    return 0 if payload.get("ok") else 1


def _payment_payload(root: Path, args: argparse.Namespace, *, action: str) -> dict[str, Any]:
    manifest = _load_manifest(root)
    codee_user_id = str(manifest.get("codee_user_id") or "").strip() or _codee_user_id(args.email, str(manifest.get("client_id") or root.name))
    return {
        "plan": args.plan,
        "email": args.email,
        "account_email": args.email,
        "codee_user_id": codee_user_id,
        "user_id": codee_user_id,
        "business": args.business or str(manifest.get("business") or ""),
        "owner": args.owner or str(manifest.get("owner") or ""),
        "workspace_id": str(manifest.get("client_id") or root.name),
        "ref": args.ref,
        "dry_run": bool(args.dry_run),
        "source_surface": "codee-cli",
        "cli_version": VERSION,
        "action": action,
    }


def _print_payment_result(payload: dict[str, Any], *, action: str, report_path: Path) -> None:
    if payload.get("dry_run"):
        print(f"Codee {action} dry run: ok={payload.get('ok')}")
    else:
        print(f"Codee {action}: ok={payload.get('ok')}")
    plan = payload.get("plan") if isinstance(payload.get("plan"), dict) else {}
    if plan:
        print(f"plan={plan.get('id')} {plan.get('label')}")
    url = str(payload.get("url") or payload.get("hosted_invoice_url") or "").strip()
    if url:
        print(f"payment_url={url}")
    if payload.get("session_id"):
        print(f"session_id={payload.get('session_id')}")
    if payload.get("invoice_id"):
        print(f"invoice_id={payload.get('invoice_id')}")
    if payload.get("error"):
        print(f"error={payload.get('error')}")
        if payload.get("detail"):
            print(f"detail={payload.get('detail')}")
    print(f"report={report_path}")


def command_upgrade(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    if "@" not in str(args.email or ""):
        print("A valid --email is required so Stripe can send the hosted checkout receipt.")
        return 2
    payload = _payment_payload(root, args, action="checkout")
    try:
        result = _request_json("POST", _api_url(args.api_base, "/api/stripe/codee-cli/checkout"), payload, timeout=float(args.timeout))
        if args.dry_run and not result.get("ok"):
            result = {"ok": True, "dry_run": True, "action": "checkout", "plan": {"id": args.plan}, "email": args.email, "remote_error": result}
    except Exception as exc:
        if args.dry_run:
            result = {"ok": True, "dry_run": True, "action": "checkout", "plan": {"id": args.plan}, "email": args.email, "local_error": f"{type(exc).__name__}: {exc}"}
        else:
            raise
    report_path = _write_report(root, "latest-payment-request.json", result | {"request": payload})
    _print_payment_result(result, action="upgrade", report_path=report_path)
    url = str(result.get("url") or "").strip()
    if args.open and url:
        webbrowser.open(url)
    return 0 if result.get("ok") else 1


def command_invoice(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    if "@" not in str(args.email or ""):
        print("A valid --email is required so Stripe can send the hosted invoice page.")
        return 2
    payload = _payment_payload(root, args, action="invoice")
    payload["days_until_due"] = int(args.days_until_due)
    try:
        result = _request_json("POST", _api_url(args.api_base, "/api/stripe/codee-cli/invoice"), payload, timeout=float(args.timeout))
        if args.dry_run and not result.get("ok"):
            result = {"ok": True, "dry_run": True, "action": "invoice", "plan": {"id": args.plan}, "email": args.email, "remote_error": result}
    except Exception as exc:
        if args.dry_run:
            result = {"ok": True, "dry_run": True, "action": "invoice", "plan": {"id": args.plan}, "email": args.email, "local_error": f"{type(exc).__name__}: {exc}"}
        else:
            raise
    report_path = _write_report(root, "latest-invoice-request.json", result | {"request": payload})
    _print_payment_result(result, action="invoice", report_path=report_path)
    url = str(result.get("hosted_invoice_url") or "").strip()
    if args.open and url:
        webbrowser.open(url)
    return 0 if result.get("ok") else 1


def command_license(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    license_path = root / ".codee" / "license.json"
    if not args.session_id and not args.invoice_id:
        if not license_path.exists():
            print("No local Codee license found. Use --session-id or --invoice-id after payment.")
            return 1
        payload = json.loads(license_path.read_text(encoding="utf-8"))
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            plan = payload.get("plan") if isinstance(payload.get("plan"), dict) else {}
            print(f"Codee license: paid={payload.get('paid')} status={payload.get('status')} plan={plan.get('id')}")
            print(f"license={license_path}")
        return 0 if payload.get("paid") else 1

    query = {}
    if args.session_id:
        query["session_id"] = args.session_id
    if args.invoice_id:
        query["invoice_id"] = args.invoice_id
    result = _request_json("GET", _api_url(args.api_base, "/api/stripe/codee-cli/license", query), timeout=float(args.timeout))
    if result.get("ok") or args.save_unpaid:
        license_path.parent.mkdir(parents=True, exist_ok=True)
        license_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
    if args.json:
        print(json.dumps(result, indent=2))
    else:
        plan = result.get("plan") if isinstance(result.get("plan"), dict) else {}
        print(f"Codee license lookup: paid={result.get('paid')} status={result.get('status')} plan={plan.get('id')}")
        if result.get("ok") or args.save_unpaid:
            print(f"license={license_path}")
        elif result.get("error"):
            print(f"error={result.get('error')}")
    return 0 if result.get("ok") else 1


def command_client(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    root.mkdir(parents=True, exist_ok=True)
    has_manifest = (root / ".codee" / "codee.json").exists()
    manifest = _load_manifest(root)
    service = _normalize_service(str(args.service or manifest.get("service") or "codeeqr"))
    business = str(args.business or manifest.get("business") or "").strip()
    owner = str(args.owner or manifest.get("owner") or "").strip()
    email = str(args.email or manifest.get("owner_email") or "").strip().lower()
    target_url = str(args.target_url or "").strip()
    goal = str(args.goal or "").strip()
    if args.ask:
        business = _cli_prompt("Business/client name", business) or "Codee Client"
        owner = _cli_prompt("Owner/contact name", owner) or "Business Owner"
        email = _cli_prompt("Client email", email).lower()
        service = _normalize_service(_cli_prompt("Service lane (codeeqr/codeeflyer100/codeeflyer250/codeeapp250/codeecard/codeebeeper/minicodeesite)", service))
        target_url = _cli_prompt("Target URL or main CTA", target_url)
        goal = _cli_prompt("What should Codee generate or improve?", goal)
        wp_answer = _cli_prompt("Need WordPress help? Type site URL or press Enter", "")
        if wp_answer and not args.wordpress_site:
            args.wordpress_site = wp_answer
            args.connect_wordpress = True
    workspace_id = str(manifest.get("client_id") if has_manifest else root.name).strip() or _normalize_service(business or root.name)
    codee_user_id = str(manifest.get("codee_user_id") or "").strip() or _codee_user_id(email, workspace_id)
    connector_plan = _client_connector_plan(args, workspace_id=workspace_id, codee_user_id=codee_user_id, service=service)
    contract = _service_contract(service)
    chat_payload = _client_service_to_chat_payload(
        service,
        business=business or "Codee Client",
        email=email,
        target_url=target_url,
        goal=goal,
    )
    chat_payload.update(
        {
            "client_id": workspace_id,
            "codee_user_id": codee_user_id,
            "owner": owner or "Business Owner",
            "external_connector_plan": connector_plan,
            "paywall_mode": "preview_10_min_to_true_deploy",
            "true_deploy_status": "locked_until_paid",
            "service_contract": contract,
            "service_contract_version": "codee.service-contracts.v1",
        }
    )
    packet = {
        "schema": "codee.cli.client.intake.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "workspace_id": workspace_id,
        "client_id": workspace_id,
        "codee_user_id": codee_user_id,
        "business": business or "Codee Client",
        "owner": owner or "Business Owner",
        "account_email": email,
        "service": service,
        "target_url": target_url,
        "goal": goal,
        "service_contract": contract,
        "paywall": {
            "status": "preview_ready_payment_required",
            "preview_window_minutes": 10,
            "unlock_rule": "Stripe/payment verification unlocks true deploy, hosted route, delivery room, managed scans, and live edit support.",
            "teachable_pattern": ["folder", "index.html", "chat-style intake", "locked preview", "Stripe unlock", "delivery room", "CLI workbench support"],
        },
        "connector_plan": connector_plan,
        "chat_intake_payload": chat_payload,
        "next_commands": [
            f"python3 codee.py verify {root} --service {service}",
            f"python3 codee.py client {root} --service {service} --business \"{business or 'Codee Client'}\" --email {email or 'owner@example.com'} --target-url {target_url or 'https://example.com'} --submit",
            f"bash {root / '.codee' / 'submit-with-shell-curl.sh'}",
            f"python3 codee.py connect {root} --service {service} --email {email or 'owner@example.com'}",
            f"python3 codee.py activate {root} --service {service}",
        ],
    }
    submit_payload_path = root / ".codee" / "latest-chat-submit-payload.json"
    shell_submit_script_path = root / ".codee" / "submit-with-shell-curl.sh"
    shell_submit_script = _curl_submit_script(
        api_base=str(args.api_base or DEFAULT_API_BASE),
        path="/api/forms/intake/chat",
        payload_path=submit_payload_path,
        timeout=float(args.timeout),
    )
    packet["submit_payload_path"] = str(submit_payload_path)
    packet["shell_curl_submit_script"] = str(shell_submit_script_path)
    packet["shell_curl_submit_command"] = f"bash {shlex.quote(str(shell_submit_script_path))}"
    _write_json(root / ".codee" / "client-intake.json", packet, force=True)
    _write_json(submit_payload_path, chat_payload, force=True)
    _write_text(shell_submit_script_path, shell_submit_script, force=True)
    try:
        shell_submit_script_path.chmod(0o755)
    except Exception:
        pass
    _write_json(root / ".codee" / "paywall-deploy.json", packet["paywall"], force=True)
    _write_text(root / ".codee" / "CLIENT_INTAKE.md", _client_intake_markdown(packet), force=True)
    request_path = _write_report(root, "latest-client-intake-request.json", packet)
    result: dict[str, Any] = {"ok": True, "dry_run": True, "message": "Local client intake packet created."}
    if args.submit and not args.dry_run:
        result = _request_json_with_api_fallbacks(
            "POST",
            args.api_base,
            "/api/forms/intake/chat",
            chat_payload,
            timeout=float(args.timeout),
            fallback_bases=list(getattr(args, "api_fallback_base", []) or []),
        )
        if result.get("ok"):
            _write_json(root / ".codee" / "latest-chat-intake.json", result, force=True)
            packet["backend_result"] = result
            if isinstance(result.get("preview"), dict):
                _write_json(root / ".codee" / "latest-paywalled-preview.json", result.get("preview") or {}, force=True)
        _write_json(
            root / ".codee" / "latest-submit-transport.json",
            {
                "schema": "codee.submit-transport.v1",
                "created_at": _now(),
                "api_base_requested": args.api_base,
                "attempts": result.get("transport_attempts") or [],
                "api_base_used": result.get("api_base_used") or "",
                "ok": bool(result.get("ok")),
                "http_status": result.get("http_status") or 0,
            },
            force=True,
        )
        if not result.get("ok") and _should_try_next_api_base(result):
            result.setdefault("manual_submit_available", True)
            result.setdefault("submit_payload_path", str(submit_payload_path))
            result.setdefault("shell_curl_submit_script", str(shell_submit_script_path))
            result.setdefault("shell_curl_submit_command", f"bash {shlex.quote(str(shell_submit_script_path))}")
            result.setdefault(
                "message",
                "Python networking could not resolve the Codee API from this shell. The same payload is saved with a shell curl fallback command.",
            )
    report_path = _write_report(root, "latest-client-intake.json", result | {"request": packet})
    _append_event(
        root,
        "ClientIntake",
        {
            "ok": bool(result.get("ok")),
            "service": service,
            "workspace_id": workspace_id,
            "submitted": bool(args.submit and not args.dry_run),
            "preview_url": ((result.get("preview") or {}) if isinstance(result.get("preview"), dict) else {}).get("preview_url") if isinstance(result, dict) else "",
        },
    )
    if args.json:
        print(json.dumps(result | {"request": packet, "request_report": str(request_path), "report": str(report_path)}, indent=2))
    else:
        print(f"Codee client intake: ok={result.get('ok')} service={service} workspace_id={workspace_id}")
        preview = result.get("preview") if isinstance(result.get("preview"), dict) else {}
        next_obj = result.get("next") if isinstance(result.get("next"), dict) else {}
        if preview.get("preview_url"):
            print(f"preview_url={preview.get('preview_url')}")
        if next_obj.get("checkout_url") or next_obj.get("start_checkout_url"):
            print(f"checkout_url={next_obj.get('checkout_url') or next_obj.get('start_checkout_url')}")
        requests = connector_plan.get("requests") if isinstance(connector_plan.get("requests"), list) else []
        for item in requests:
            if not isinstance(item, dict):
                continue
            print(f"{item.get('id')}_status={item.get('status')}")
            if item.get("assistant_url"):
                print(f"wordpress_assistant={item.get('assistant_url')}")
            if item.get("connect_url"):
                print(f"google_connect={item.get('connect_url')}")
        print(f"packet={root / '.codee' / 'CLIENT_INTAKE.md'}")
        print(f"report={report_path}")
        if result.get("error"):
            print(f"error={result.get('error')}")
    return 0 if result.get("ok") else 1


def command_connect(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = _connection_payload(root, args, action="connect")
    _append_event(root, "PreConnect", {"service": payload.get("service"), "workspace_id": payload.get("workspace_id"), "fingerprint": payload.get("workspace_fingerprint")})
    request_path = _write_report(root, "latest-backend-connect-request.json", payload)
    if args.dry_run:
        result = {
            "ok": True,
            "dry_run": True,
            "message": "Local connection packet created. Remove --dry-run to register this folder with Codee backend.",
            "connection_id": f"local_{payload['workspace_fingerprint'][:18]}",
            "activation_status": "local_only",
            "delivery_room_url": _delivery_room_url(
                {
                    "client_id": payload["workspace_id"],
                    "codee_user_id": payload["codee_user_id"],
                    "business": payload["business"],
                },
                service=payload["service"],
            ),
        }
    else:
        result = _request_json("POST", _api_url(args.api_base, "/api/codee/cli/connect"), payload, timeout=float(args.timeout))
    report_path = _write_report(root, "latest-backend-connect.json", result | {"request": payload})
    if result.get("ok") and not args.dry_run:
        _write_json(root / ".codee" / "backend-connection.json", result, force=True)
    _append_event(
        root,
        "PostConnect",
        {
            "ok": bool(result.get("ok")),
            "connection_id": result.get("connection_id"),
            "activation_status": result.get("activation_status"),
            "delivery_room_url": result.get("delivery_room_url"),
        },
    )
    if args.json:
        print(json.dumps(result | {"request": payload, "request_report": str(request_path), "report": str(report_path)}, indent=2))
    else:
        print(f"Codee backend connect: ok={result.get('ok')} connection_id={result.get('connection_id', '')}")
        print(f"workspace_id={payload['workspace_id']} service={payload['service']} course={payload.get('course_id') or 'none'}")
        print(f"delivery_room={result.get('delivery_room_url', '')}")
        print(f"activate_url={result.get('activate_url', '')}")
        print(f"report={report_path}")
        if result.get("error"):
            print(f"error={result.get('error')}")
    if args.open and result.get("workbench_url"):
        webbrowser.open(str(result.get("workbench_url")))
    return 0 if result.get("ok") else 1


def command_activate(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    connection = _read_json_if_exists(root / ".codee" / "backend-connection.json")
    payload = _connection_payload(root, args, action="activate")
    payload.update(
        {
            "connection_id": str(args.connection_id or connection.get("connection_id") or "").strip(),
            "activation_token": str(args.activation_token or connection.get("activation_token") or "").strip(),
            "plan": str(args.plan or "single-lane-hosting").strip(),
            "checkout_session_id": str(args.checkout_session_id or "").strip(),
            "invoice_id": str(args.invoice_id or "").strip(),
            "activation_mode": "hosted_link_after_payment",
            "payment_required": True,
        }
    )
    _append_event(root, "PreActivate", {"service": payload.get("service"), "connection_id": payload.get("connection_id"), "plan": payload.get("plan")})
    if args.dry_run:
        result = {
            "ok": True,
            "dry_run": True,
            "activation_status": "payment_required",
            "message": "Activation packet created locally. Remove --dry-run to ask Codee backend for the locked hosted activation path.",
            "paid_intake_url": _course_paid_intake_url(
                _course_by_id(payload.get("course_id") or "qrcodee") if payload.get("course_id") in set(TOOLKIT_COURSES) else {"id": "qrcodee", "activation_service": payload["service"]},
                business=payload["business"],
                target_url=payload.get("target_url") or "https://codee.chat",
                source="codee-cli-activate",
            ),
        }
    else:
        result = _request_json("POST", _api_url(args.api_base, "/api/codee/cli/activate"), payload, timeout=float(args.timeout))
    report_path = _write_report(root, "latest-activation-request.json", result | {"request": payload})
    if result.get("requires_payment") or result.get("activation_status") == "payment_required":
        _append_event(root, "PaymentRequired", {"connection_id": result.get("connection_id") or payload.get("connection_id"), "paid_intake_url": result.get("paid_intake_url")})
    _append_event(
        root,
        "PostActivate",
        {
            "ok": bool(result.get("ok")),
            "activation_status": result.get("activation_status"),
            "activation_id": result.get("activation_id"),
            "connection_id": result.get("connection_id") or payload.get("connection_id"),
        },
    )
    if args.json:
        print(json.dumps(result | {"request": payload, "report": str(report_path)}, indent=2))
    else:
        print(f"Codee activation: ok={result.get('ok')} status={result.get('activation_status', '')}")
        print(f"connection_id={result.get('connection_id') or payload.get('connection_id')}")
        print(f"paid_intake={result.get('paid_intake_url', '')}")
        print(f"delivery_room={result.get('delivery_room_url', '')}")
        print(f"report={report_path}")
        if result.get("error"):
            print(f"error={result.get('error')}")
    if args.open:
        url = str(result.get("paid_intake_url") or result.get("activate_url") or result.get("delivery_room_url") or "").strip()
        if url:
            webbrowser.open(url)
    return 0 if result.get("ok") else 1


def command_hooks(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _hook_manifest()
    wrote = False
    if args.write:
        wrote = _write_json(root / ".codee" / "hooks.json", manifest, force=args.force)
        _append_event(root, "HooksConfigured", {"wrote": wrote, "mode": manifest.get("mode")})
    if args.json:
        print(json.dumps(manifest | {"wrote": wrote, "path": str(root / ".codee" / "hooks.json")}, indent=2))
    else:
        print("Codee hooks")
        print(f"mode={manifest['mode']}")
        for item in manifest["events"]:
            print(f"- {item['event']}: {item['purpose']} ({item['default_action']})")
        if args.write:
            print(f"hooks={root / '.codee' / 'hooks.json'} {'written' if wrote else 'exists'}")
        print(f"event_log={root / '.codee' / 'events.jsonl'}")
    return 0


def command_connectors(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _connector_manifest()
    if args.public_only:
        manifest["connectors"] = [item for item in manifest["connectors"] if item.get("public_cli")]
    wrote = False
    if args.write:
        wrote = _write_json(root / ".codee" / "connectors.json", manifest, force=args.force)
        _append_event(root, "ConnectorsConfigured", {"wrote": wrote, "connector_count": len(manifest.get("connectors") or [])})
    if args.json:
        print(json.dumps(manifest | {"wrote": wrote, "path": str(root / ".codee" / "connectors.json")}, indent=2))
    else:
        print("Codee connectors")
        print(manifest["public_rule"])
        for item in manifest["connectors"]:
            flag = "public" if item.get("public_cli") else item.get("status")
            print(f"- {item['name']} ({item['id']}): {flag} - {item['purpose']}")
        if args.write:
            print(f"connectors={root / '.codee' / 'connectors.json'} {'written' if wrote else 'exists'}")
    return 0


def command_permissions(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = _permissions_manifest(args.mode)
    wrote = False
    if args.write:
        wrote = _write_json(root / ".codee" / "permissions.json", payload, force=args.force)
        _write_text(root / ".codee" / "PERMISSIONS.md", _permissions_markdown(payload), force=args.force)
        _append_event(root, "PermissionsConfigured", {"mode": payload.get("selected_mode"), "wrote": wrote})
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "path": str(root / ".codee" / "permissions.json")}, indent=2))
    else:
        print("Codee permission modes")
        print(f"selected={payload['selected_mode']}")
        for item in payload["modes"]:
            marker = "*" if item["id"] == payload["selected_mode"] else "-"
            print(f"{marker} {item['id']}: writes={item['file_writes']} shell={item['shell']} network={item['network']}")
        if args.write:
            print(f"permissions={root / '.codee' / 'permissions.json'} {'written' if wrote else 'exists'}")
    return 0


def command_agents(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = _agents_manifest(args.mode)
    wrote = False
    if args.write:
        wrote = _write_json(root / ".codee" / "agents.json", payload, force=args.force)
        _write_text(root / ".codee" / "AGENTS.md", _agents_markdown(payload), force=args.force)
        agents_dir = root / ".codee" / "agents"
        for agent in payload.get("agents") or []:
            _write_text(agents_dir / f"{agent.get('id')}.md", _agent_profile_markdown(agent), force=args.force)
        _append_event(root, "AgentsConfigured", {"count": len(payload.get("agents") or []), "mode": args.mode, "wrote": wrote})
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "path": str(root / ".codee" / "agents.json")}, indent=2))
    else:
        print("Codee agent profiles")
        print(payload["routing_rule"])
        for item in payload["agents"]:
            print(f"- {item['id']}: {item['name']} ({item['permission_mode']})")
        if args.write:
            print(f"agents={root / '.codee' / 'agents.json'} {'written' if wrote else 'exists'}")
    return 0


def command_mcp(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = _mcp_manifest(args.api_base, public_only=bool(args.public_only))
    wrote = False
    if args.write:
        wrote = _write_json(root / ".codee" / "mcp.json", payload, force=args.force)
        _write_text(root / ".codee" / "MCP.md", _mcp_markdown(payload), force=args.force)
        _append_event(root, "McpConfigured", {"server_count": len(payload.get("servers") or []), "wrote": wrote})
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "path": str(root / ".codee" / "mcp.json")}, indent=2))
    else:
        print("Codee MCP-style connector blueprint")
        for item in payload["servers"]:
            flag = "public" if item.get("public_cli") else "gated"
            print(f"- {item['id']}: {flag} {item.get('transport')}")
        if args.write:
            print(f"mcp={root / '.codee' / 'mcp.json'} {'written' if wrote else 'exists'}")
    return 0


def command_memory(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = _memory_manifest(root, business=args.business, service=args.service)
    wrote = False
    if args.write:
        wrote = _write_json(root / ".codee" / "memory.json", payload, force=args.force)
        markdown = _memory_markdown(payload)
        _write_text(root / "CODEE.md", markdown, force=args.force)
        _write_text(root / "AGENTS.md", _agents_markdown(_agents_manifest(args.mode)), force=args.force)
        _write_text(root / ".codee" / "rules" / "service-lane.md", markdown, force=args.force)
        _append_event(root, "MemoryConfigured", {"business": payload.get("business"), "service": payload.get("service"), "wrote": wrote})
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "path": str(root / ".codee" / "memory.json")}, indent=2))
    else:
        print("Codee project memory")
        print(f"business={payload['business']} service={payload['service']}")
        for item in payload["memory_files"]:
            print(f"- {item}")
        if args.write:
            print(f"memory={root / '.codee' / 'memory.json'} {'written' if wrote else 'exists'}")
    return 0


def command_memory_vault(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    action = str(getattr(args, "memory_action", "") or "init")
    service = _normalize_service(str(getattr(args, "service", "") or "codee-service"))
    base = _ensure_user_memory_vault(
        root,
        business=str(getattr(args, "business", "") or ""),
        owner=str(getattr(args, "owner", "") or ""),
        email=str(getattr(args, "email", "") or ""),
        service=service,
        force=bool(getattr(args, "force", False)),
    )
    vault = base["vault"]
    paths = {key: Path(value) for key, value in base["paths"].items()}
    records = _read_jsonl(paths["journal"])

    if action == "add":
        text = str(getattr(args, "text", "") or "").strip()
        if not text:
            print("memory-vault add requires --text")
            return 2
        tags = [str(item).strip().lower() for item in (getattr(args, "tag", None) or []) if str(item).strip()]
        record = {
            "schema": "codee.user-memory-record.v1",
            "memory_id": "mem_" + hashlib.sha256(f"{vault.get('codee_user_id')}:{text}:{time.time_ns()}".encode("utf-8")).hexdigest()[:18],
            "created_at": _now(),
            "codee_user_id": vault.get("codee_user_id"),
            "business": str(getattr(args, "business", "") or vault.get("business") or ""),
            "service": service,
            "kind": str(getattr(args, "kind", "") or "note").strip() or "note",
            "importance": str(getattr(args, "importance", "") or "normal").strip() or "normal",
            "source": str(getattr(args, "source", "") or "codee-cli").strip() or "codee-cli",
            "tags": tags,
            "text": text,
        }
        _write_jsonl_append(paths["journal"], record)
        records.append(record)
        index = _user_memory_index(records)
        _write_json(paths["index"], index, force=True)
        _write_text(paths["markdown"], _user_memory_markdown(vault, index, records), force=True)
        _write_text(paths["root_markdown"], _user_memory_markdown(vault, index, records), force=True)
        report = {"ok": True, "created_at": _now(), "action": "add", "record": record, "vault": vault, "index": index}
        report_path = _write_report(root, "latest-user-memory.json", report)
        _append_event(root, "UserMemoryUpdated", {"action": "add", "memory_id": record["memory_id"], "kind": record["kind"], "tags": tags})
        if args.json:
            print(json.dumps(report | {"report": str(report_path)}, indent=2))
        else:
            print(f"Codee memory saved: {record['memory_id']}")
            print(f"vault={paths['vault']}")
            print(f"records={index['record_count']}")
        return 0

    if action in {"search", "recall"}:
        query = str(getattr(args, "query", "") or "").strip()
        if not query:
            print(f"memory-vault {action} requires --query")
            return 2
        limit = max(1, min(int(getattr(args, "limit", 10) or 10), 100))
        matches = []
        for item in records:
            score = _memory_score(item, query)
            if score > 0:
                matches.append(dict(item) | {"score": score})
        matches.sort(key=lambda item: (int(item.get("score") or 0), str(item.get("created_at") or "")), reverse=True)
        matches = matches[:limit]
        report = {
            "ok": True,
            "created_at": _now(),
            "action": action,
            "query": query,
            "match_count": len(matches),
            "matches": matches,
            "vault": vault,
            "index": _user_memory_index(records),
        }
        report_path = _write_report(root, "latest-user-memory-search.json", report)
        _append_event(root, "UserMemoryUpdated", {"action": action, "query": query, "matches": len(matches)})
        if args.json:
            print(json.dumps(report | {"report": str(report_path)}, indent=2))
        else:
            print(f"Codee memory recall: {len(matches)} match(es)")
            for item in matches:
                print(f"- {item.get('memory_id')} score={item.get('score')} {item.get('kind')}: {item.get('text')}")
            print(f"report={report_path}")
        return 0

    if action == "list":
        limit = max(1, min(int(getattr(args, "limit", 10) or 10), 100))
        latest = records[-limit:][::-1]
        payload = {"ok": True, "created_at": _now(), "action": "list", "records": latest, "vault": vault, "index": _user_memory_index(records)}
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            print(f"Codee user memory: {len(records)} record(s)")
            for item in latest:
                print(f"- {item.get('memory_id')} {item.get('kind')}: {item.get('text')}")
        _append_event(root, "UserMemoryUpdated", {"action": "list", "count": len(records)})
        return 0

    if action == "export":
        export_payload = {"ok": True, "created_at": _now(), "vault": vault, "index": _user_memory_index(records), "records": records}
        output = str(getattr(args, "output", "") or "").strip()
        export_path = Path(output).expanduser().resolve() if output else paths["export_dir"] / f"user-memory-export-{_safe_time_slug()}.json"
        export_path.parent.mkdir(parents=True, exist_ok=True)
        export_path.write_text(json.dumps(export_payload, indent=2) + "\n", encoding="utf-8")
        _append_event(root, "UserMemoryUpdated", {"action": "export", "path": str(export_path), "count": len(records)})
        if args.json:
            print(json.dumps(export_payload | {"export_path": str(export_path)}, indent=2))
        else:
            print(f"Codee user memory export: {export_path}")
            print(f"records={len(records)}")
        return 0

    index = _user_memory_index(records)
    _write_json(paths["index"], index, force=True)
    _write_text(paths["markdown"], _user_memory_markdown(vault, index, records), force=True)
    _write_text(paths["root_markdown"], _user_memory_markdown(vault, index, records), force=True)
    _append_event(root, "UserMemoryUpdated", {"action": "init", "count": len(records)})
    payload = {"ok": True, "action": "init", "vault": vault, "index": index, "paths": base["paths"], "writes": base["writes"]}
    if args.json:
        print(json.dumps(payload, indent=2))
    else:
        print("Codee user memory vault ready")
        print(f"user={vault['codee_user_id']}")
        print(f"records={index['record_count']}")
        print(f"vault={paths['vault']}")
        print(f"journal={paths['journal']}")
    return 0


def command_agent_core(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = _agent_core_manifest(root, business=args.business, service=args.service, mode=args.mode, api_base=args.api_base)
    wrote = False
    if args.write:
        root.mkdir(parents=True, exist_ok=True)
        wrote = _write_json(root / ".codee" / "agent-core.json", payload, force=args.force)
        _write_text(root / ".codee" / "AGENT_CORE.md", _agent_core_markdown(payload), force=args.force)
        _write_text(root / ".codee" / "UPGRADE_PATH.md", _agent_core_upgrade_markdown(payload), force=args.force)
        _append_event(root, "AgentCoreConfigured", {"business": payload.get("business"), "service": payload.get("service"), "mode": args.mode, "wrote": wrote})
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "path": str(root / ".codee" / "agent-core.json")}, indent=2))
    else:
        print("Codee AGI core")
        print(payload["capability_statement"])
        print("")
        print(f"AGI meaning: {payload['codee_agi']['meaning']}")
        print("")
        print("Operating loop")
        for item in payload["operating_loop"]:
            print(f"- {item['step']}: {item['purpose']}")
        print("")
        print("Hardcoded tools")
        for item in payload["tools"]:
            visibility = "public" if item.get("public") else "owner-gated"
            print(f"- {item['tool']}: {visibility}")
        if args.write:
            print(f"agent_core={root / '.codee' / 'agent-core.json'} {'written' if wrote else 'exists'}")
    return 0


def command_accessibility(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = _accessibility_manifest(root, business=args.business, service=args.service)
    wrote = False
    if args.write:
        wrote = _write_json(root / ".codee" / "accessibility.json", payload, force=args.force)
        _write_text(root / ".codee" / "ACCESSIBILITY.md", _accessibility_markdown(payload), force=args.force)
        _append_event(root, "AccessibilityConfigured", {"business": payload.get("business"), "service": payload.get("service"), "wrote": wrote})
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "path": str(root / ".codee" / "accessibility.json")}, indent=2))
    else:
        print("Codee veteran accessibility mode")
        print(payload["principle"])
        for item in payload["course_rules"]:
            print(f"- {item}")
        if args.write:
            print(f"accessibility={root / '.codee' / 'accessibility.json'} {'written' if wrote else 'exists'}")
    return 0


def command_platform(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = _platform_manifest(root, permission_mode=args.mode, api_base=args.api_base)
    wrote = False
    if args.write:
        result = _write_platform_layer(root, mode=args.mode, business=args.business, service=args.service, api_base=args.api_base, force=args.force)
        payload = result["payload"]
        wrote = bool(result["writes"].get("platform_parity"))
        _append_event(root, "PlatformConfigured", {"mode": args.mode, "wrote": wrote, "gap_count": len(CODEE_PLATFORM_GAPS)})
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "path": str(root / ".codee" / "platform-parity.json")}, indent=2))
    else:
        print("Codee platform layer")
        print(payload["summary"])
        for item in payload["gaps_closed"]:
            print(f"- {item['feature']}: {item['codee_status']}")
        if args.write:
            print(f"platform={root / '.codee' / 'platform-parity.json'} {'written' if wrote else 'exists'}")
    return 0


def _codeecpa_payload(root: Path, args: argparse.Namespace) -> dict[str, Any]:
    manifest = _load_manifest(root)
    business = str(getattr(args, "business", "") or manifest.get("business") or "Codee Client").strip()
    owner = str(getattr(args, "owner", "") or manifest.get("owner") or "Business Owner").strip()
    topic = str(getattr(args, "topic", "") or "company legal, tax, and accounting review").strip()
    jurisdiction = str(getattr(args, "jurisdiction", "") or "United States / Ohio").strip()
    entity = str(getattr(args, "entity", "") or "AI K9 Kennel / Invest In Vets alignment").strip()
    tax_year = str(getattr(args, "tax_year", "") or dt.datetime.now().strftime("%Y")).strip()
    packet = json.loads(json.dumps(CODEECPA_PACKET))
    packet.update(
        {
            "created_at": _now(),
            "workspace": {
                "root": "public-safe" if bool(getattr(args, "public_safe", False)) else str(root),
                "business": business,
                "owner": "Owner" if bool(getattr(args, "public_safe", False)) else owner,
                "topic": topic,
                "jurisdiction": jurisdiction,
                "entity": entity,
                "tax_year": tax_year,
                "workspace_id": str(manifest.get("client_id") or manifest.get("workspace_id") or _slugify(business)),
                "codee_user_id": str(manifest.get("codee_user_id") or ""),
            },
            "document_requests": [
                "entity formation documents and EIN letters",
                "operating agreement, bylaws, board minutes, and conflict-of-interest policy",
                "Stripe exports, invoices, refunds, and product catalog",
                "bank statements, bookkeeping summary, receipts, and GCloud/Firebase/storage bills",
                "donation, sponsorship, grant, and nonprofit shop records",
                "contractor, volunteer, employee, and contributor agreements",
                "technology license drafts between company and nonprofit",
                "terms, privacy, refund, support, acceptable-use, and remote-control consent drafts",
                "trademark, copyright, domain, and asset ownership records",
                "proof reports, delivery-room samples, route scans, and case-study evidence with private data removed",
            ],
            "professional_questions": [
                "What legal structure and written agreements best separate the nonprofit mission and technology company?",
                "What tax and accounting treatment applies to service revenue, hosting subscriptions, digital products, sponsorships, and donations?",
                "What sales-tax or digital-product obligations apply in the states where customers buy?",
                "What language should be changed before any income, business opportunity, investor, grant, housing, voucher, or tax claim is public?",
                "What records are required before licensing Codee technology to the nonprofit?",
                "What insurance, privacy, data security, remote-access, and customer support risks need written controls?",
                "What should the company track monthly so a CPA, attorney, investor, sponsor, or board can verify the story?",
            ],
        }
    )
    return packet


def _codeecpa_consult_markdown(payload: dict[str, Any]) -> str:
    workspace = payload.get("workspace") or {}
    lines = [
        "# CODEECPA Consultation Prep",
        "",
        str(payload.get("positioning") or ""),
        "",
        "## Guardrails",
        "",
    ]
    lines.extend(f"- {item}" for item in payload.get("guardrails") or [])
    lines.extend(
        [
            "",
            "## Workspace",
            "",
            f"- Business: {workspace.get('business')}",
            f"- Owner: {workspace.get('owner')}",
            f"- Topic: {workspace.get('topic')}",
            f"- Jurisdiction: {workspace.get('jurisdiction')}",
            f"- Entity lane: {workspace.get('entity')}",
            f"- Tax year: {workspace.get('tax_year')}",
            "",
            "## Document Requests",
            "",
        ]
    )
    lines.extend(f"- {item}" for item in payload.get("document_requests") or [])
    lines.extend(["", "## Official Source Pointers", ""])
    for item in payload.get("official_sources") or []:
        lines.append(f"- {item.get('name')}: {item.get('url')} - {item.get('use')}")
    lines.extend(["", "## Red Flags", ""])
    lines.extend(f"- {item}" for item in payload.get("red_flags") or [])
    return "\n".join(lines) + "\n"


def _codeecpa_questions_markdown(payload: dict[str, Any]) -> str:
    lines = ["# CPA And Law Firm Question List", "", "Use this to control the consultation and get written answers.", ""]
    for index, item in enumerate(payload.get("professional_questions") or [], start=1):
        lines.append(f"{index}. {item}")
    lines.extend(["", "## Answer Log", "", "- Reviewer name:", "- License/role:", "- Date:", "- Answer:", "- Approved next action:", "- Follow-up required:"])
    return "\n".join(lines) + "\n"


def _codeecpa_review_log_markdown() -> str:
    return """# Professional Review Log

Use this after every attorney, CPA, enrolled agent, board, insurance, or advisor call.

| Date | Reviewer | Role/license | Topic | Decision | Documents reviewed | Next action |
| --- | --- | --- | --- | --- | --- | --- |
| ____ | ____ | ____ | ____ | ____ | ____ | ____ |
"""


def _codeecpa_live_sop_markdown() -> str:
    return """# CODEE Live CPA SOP

Operational draft for future trained professionals.

## Mission

Help founders, nonprofits, and small businesses prepare clean evidence packets before paid professional review.

## SOP

1. Confirm the user understands CODEECPA is preparation, not final legal or tax advice.
2. Identify the jurisdiction, entity, tax year, and decision needed.
3. Request documents without collecting unnecessary sensitive data.
4. Separate facts, assumptions, questions, and professional recommendations.
5. Flag unsupported earnings, housing, grant, tax, investor, or legal claims.
6. Prepare a written question list for the licensed reviewer.
7. Record the reviewer answer and approved next action.
8. Never file, sign, submit, or represent the client unless the professional is licensed and engaged to do so.
"""


def command_codeecpa(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = _codeecpa_payload(root, args)
    writes: dict[str, bool] = {}
    if args.write:
        codeecpa_dir = root / ".codee" / "codeecpa"
        codeecpa_dir.mkdir(parents=True, exist_ok=True)
        writes = {
            "intake_json": _write_json(codeecpa_dir / "codeecpa-intake.json", payload, force=args.force),
            "consult_prep": _write_text(codeecpa_dir / "CODEECPA_CONSULT_PREP.md", _codeecpa_consult_markdown(payload), force=args.force),
            "question_list": _write_text(codeecpa_dir / "CPA_LAW_FIRM_QUESTION_LIST.md", _codeecpa_questions_markdown(payload), force=args.force),
            "review_log": _write_text(codeecpa_dir / "PROFESSIONAL_REVIEW_LOG.md", _codeecpa_review_log_markdown(), force=args.force),
            "live_cpa_sop": _write_text(codeecpa_dir / "CODEECPA_LIVE_CPA_SOP.md", _codeecpa_live_sop_markdown(), force=args.force),
            "public_route": _write_json(root / ".codee" / "codeecpa-route.json", {"name": "codeecpa", "url": CODEE_CPA_URL, "expected": [200]}, force=args.force),
            "workspace_route": _write_json(root / ".codee" / "codeecpa-workspace-route.json", {"name": "codeecpa-workspace", "url": CODEE_CPA_WORKSPACE_URL, "expected": [200]}, force=args.force),
            "public_routes": _write_json(root / ".codee" / "codeecpa-routes.json", [{"name": "codeecpa", "url": CODEE_CPA_URL, "expected": [200]}, {"name": "codeecpa-workspace", "url": CODEE_CPA_WORKSPACE_URL, "expected": [200]}], force=args.force),
        }
        _append_event(root, "CodeeCPAConfigured", {"wrote": any(writes.values()), "topic": (payload.get("workspace") or {}).get("topic")})
    if args.json:
        print(json.dumps(payload | {"writes": writes}, indent=2))
    else:
        print("CODEECPA consultation-prep packet")
        print(f"public_page={CODEE_CPA_URL}")
        print(f"workspace_page={CODEE_CPA_WORKSPACE_URL}")
        print("rule=preparation only; licensed review still required")
        print(f"review_lanes={len(payload.get('review_lanes') or [])}")
        if args.write:
            for name, wrote in writes.items():
                print(f"{name}: {'written' if wrote else 'exists'}")
    return 0


def _codeeadmin_state_name_to_code() -> dict[str, str]:
    lookup: dict[str, str] = {}
    for state in CODEEADMIN_US_STATES:
        code = str(state.get("code") or "").upper()
        name = str(state.get("name") or "").lower()
        lookup[code] = code
        lookup[name] = code
    return lookup


def _normalize_codeeadmin_state(value: str) -> str:
    raw = str(value or "").strip()
    if not raw:
        return ""
    lookup = _codeeadmin_state_name_to_code()
    return lookup.get(raw.upper(), lookup.get(raw.lower(), ""))


def _codeeadmin_active_state_codes(args: argparse.Namespace) -> list[str]:
    requested: list[str] = []
    for item in list(getattr(args, "state", []) or []):
        for part in re.split(r"[,;]", str(item or "")):
            code = _normalize_codeeadmin_state(part)
            if code and code not in requested:
                requested.append(code)
    if bool(getattr(args, "all_states", False)):
        return [str(item["code"]) for item in CODEEADMIN_US_STATES]
    return requested or ["NY", "OH"]


def _codeeadmin_stage_for_state(code: str, active: set[str]) -> dict[str, Any]:
    stage_id = "source-links" if code in active else "queued"
    for stage in CODEEADMIN_STATE_READINESS_STAGES:
        if stage["id"] == stage_id:
            return dict(stage)
    return dict(CODEEADMIN_STATE_READINESS_STAGES[0])


def _codeeadmin_state_source_links_needed() -> list[dict[str, str]]:
    return [
        {"id": "veterans", "label": "State veteran affairs office", "proof_needed": "Current official state veteran services URL."},
        {"id": "housing-finance", "label": "Housing finance agency", "proof_needed": "Official housing finance or affordable housing program URL."},
        {"id": "housing-authority", "label": "Housing authority / voucher partners", "proof_needed": "Official voucher partner or housing authority URL."},
        {"id": "land", "label": "Land bank or public land source", "proof_needed": "Official land bank, county land, public property, or acquisition source URL."},
        {"id": "economic-development", "label": "Economic development / grants", "proof_needed": "Official grant, sponsor, workforce, or development source URL."},
        {"id": "zoning", "label": "Zoning and permitting authority", "proof_needed": "Official city, county, or state permitting and zoning URL."},
        {"id": "utility-solar", "label": "Utility and solar incentive sources", "proof_needed": "Official utility, energy office, solar incentive, or interconnection source URL."},
    ]


def _codeeadmin_state_packet(state: dict[str, Any], active: set[str]) -> dict[str, Any]:
    code = str(state["code"])
    stage = _codeeadmin_stage_for_state(code, active)
    focus_regions = CODEEADMIN_STATE_FOCUS_REGIONS.get(code, [])
    source_links_needed = _codeeadmin_state_source_links_needed()
    return {
        "schema": "codeeadmin.state-packet.v2",
        "version": VERSION,
        "updated_at": "2026-05-27",
        "code": code,
        "name": state["name"],
        "region": state["region"],
        "priority": "active" if code in active else "queued",
        "public_page": f"{CODEEADMIN_STATE_PACKET_URL}?state={code}",
        "focus_regions": focus_regions,
        "readiness": {
            "stage_id": stage.get("id"),
            "stage_label": stage.get("label"),
            "score": stage.get("score"),
            "next_gate": stage.get("gate"),
            "score_is_structural": True,
            "rule": "This score measures packet readiness, not live state opportunity or legal approval.",
        },
        "owner_next_three": [
            "Attach official source links before any public state-specific claim.",
            "Send professional-review questions to CODEECPA before land, grant, voucher, tax, or legal commitments.",
            "Prepare one sponsor/partner proof packet only after sources and review questions are organized.",
        ],
        "source_links_needed": source_links_needed,
        "action_rooms": CODEEADMIN_STATE_ACTION_ROOMS,
        "state_packet_sections": [
            "mission snapshot",
            "official source links",
            "housing and voucher partner map",
            "land and zoning review questions",
            "solar/data center concept fit",
            "sponsor and donor one-page",
            "Codee service activation map",
            "board/advisor/professional review notes",
        ],
        "codee_service_angle": [
            "Offer free or sponsored Codee training to eligible homeless and disabled veterans first.",
            "Use QRCodee, CodeeFlyer, CodeeApp, CodeeCard, and CodeeBlog as local business proof examples.",
            "Keep paid business services under AI K9 Kennel and mission funding under Invest In Vets Foundation.",
            "Route every public claim to proof links or leave it as a draft until verified.",
        ],
        "review_gate": {
            "required_before_commitment": ["owner approval", "board/advisor review", "licensed professional review when applicable"],
            "never_skip": ["restricted funds", "land purchase", "housing/voucher promises", "tax/legal claims", "grant commitments"],
        },
    }


def _codeeadmin_state_playbook(active_codes: list[str]) -> dict[str, Any]:
    active = set(active_codes or [])
    rows: list[dict[str, Any]] = []
    packets: list[dict[str, Any]] = []
    for state in CODEEADMIN_US_STATES:
        code = str(state["code"])
        packet = _codeeadmin_state_packet(state, active)
        packets.append(packet)
        rows.append(packet)
    return {
        "schema": "codeeadmin.state-playbook.v1",
        "version": VERSION,
        "updated_at": "2026-05-27",
        "public_page": CODEEADMIN_STATES_URL,
        "manifest": CODEEADMIN_STATES_MANIFEST_URL,
        "state_packet_page": CODEEADMIN_STATE_PACKET_URL,
        "state_packet_manifest": CODEEADMIN_STATE_PACKET_MANIFEST_URL,
        "coverage_count": len(rows),
        "active_states": active_codes,
        "readiness_stages": CODEEADMIN_STATE_READINESS_STAGES,
        "action_rooms": CODEEADMIN_STATE_ACTION_ROOMS,
        "states": rows,
        "state_packets": packets,
        "rule": "State pages are operating checklists, not legal, tax, zoning, grant, or investment advice. Verify state facts with official current sources before action.",
    }


def _codeeadmin_state_playbook_markdown(playbook: dict[str, Any]) -> str:
    lines = [
        "# CodeeAdmin State-By-State Playbook",
        "",
        f"Generated: {_now()}",
        f"Coverage: {playbook.get('coverage_count')} states/regions",
        f"Active states: {', '.join(playbook.get('active_states') or [])}",
        "",
        str(playbook.get("rule") or ""),
        "",
    ]
    for state in playbook.get("states") or []:
        if state.get("priority") != "active":
            continue
        readiness = state.get("readiness") or {}
        lines.extend(
            [
                f"## {state.get('name')} ({state.get('code')})",
                "",
                f"- Region: {state.get('region')}",
                f"- Priority: {state.get('priority')}",
                f"- Packet page: {state.get('public_page')}",
                f"- Readiness stage: {readiness.get('stage_label')} ({readiness.get('score')}/100 structural)",
                f"- Next gate: {readiness.get('next_gate')}",
            ]
        )
        focus_regions = state.get("focus_regions") or []
        if focus_regions:
            lines.extend(["- Focus regions: " + ", ".join(focus_regions)])
        lines.extend(["", "### Next Three", ""])
        lines.extend(f"{index}. {item}" for index, item in enumerate(state.get("owner_next_three") or [], start=1))
        lines.extend(["", "### Source Links Needed", ""])
        for item in state.get("source_links_needed") or []:
            if isinstance(item, dict):
                lines.append(f"- {item.get('label')}: {item.get('proof_needed')}")
            else:
                lines.append(f"- {item}")
        lines.extend(["", "### Codee Service Angle", ""])
        lines.extend(f"- {item}" for item in state.get("codee_service_angle") or [])
        lines.extend([""])
    return "\n".join(lines) + "\n"


def _codeeadmin_state_packet_markdown(packet: dict[str, Any]) -> str:
    readiness = packet.get("readiness") or {}
    lines = [
        f"# {packet.get('name')} CodeeAdmin State Packet",
        "",
        f"Generated: {_now()}",
        f"Packet page: {packet.get('public_page')}",
        f"Priority: {packet.get('priority')}",
        f"Readiness: {readiness.get('stage_label')} ({readiness.get('score')}/100 structural)",
        f"Next gate: {readiness.get('next_gate')}",
        "",
        "This is an operating packet. Verify state facts with official current sources before action.",
        "",
        "## Focus Regions",
        "",
    ]
    focus_regions = packet.get("focus_regions") or ["statewide"]
    lines.extend(f"- {item}" for item in focus_regions)
    lines.extend(["", "## Owner Next Three", ""])
    lines.extend(f"{index}. {item}" for index, item in enumerate(packet.get("owner_next_three") or [], start=1))
    lines.extend(["", "## Source Links Needed", ""])
    for item in packet.get("source_links_needed") or []:
        lines.append(f"- {item.get('label')}: {item.get('proof_needed')}" if isinstance(item, dict) else f"- {item}")
    lines.extend(["", "## Action Rooms", ""])
    for room in packet.get("action_rooms") or []:
        lines.append(f"- {room.get('label')} / {room.get('owner_agent')}: {room.get('purpose')}")
    lines.extend(["", "## Codee Service Angle", ""])
    lines.extend(f"- {item}" for item in packet.get("codee_service_angle") or [])
    lines.extend(["", "## Review Gate", ""])
    review_gate = packet.get("review_gate") or {}
    lines.extend(f"- Required: {item}" for item in review_gate.get("required_before_commitment") or [])
    lines.extend(f"- Never skip: {item}" for item in review_gate.get("never_skip") or [])
    return "\n".join(lines) + "\n"


def _codeeadmin_state_packet_index_markdown(playbook: dict[str, Any]) -> str:
    lines = [
        "# CodeeAdmin State Packet Index",
        "",
        f"Generated: {_now()}",
        f"Coverage: {playbook.get('coverage_count')}",
        "",
        "## Active",
        "",
    ]
    for state in playbook.get("states") or []:
        if state.get("priority") == "active":
            readiness = state.get("readiness") or {}
            lines.append(f"- {state.get('name')} ({state.get('code')}): {readiness.get('stage_label')} - {state.get('public_page')}")
    lines.extend(["", "## Rule", "", str(playbook.get("rule") or "")])
    return "\n".join(lines) + "\n"


def _codeeadmin_payload(root: Path, args: argparse.Namespace) -> dict[str, Any]:
    manifest = _load_manifest(root)
    business = str(getattr(args, "business", "") or manifest.get("business") or "AI K9 / Invest In Vets").strip()
    owner = str(getattr(args, "owner", "") or manifest.get("owner") or "Sean").strip()
    focus = str(getattr(args, "focus", "") or "land housing mission").strip()
    month = _company_month(str(getattr(args, "month", "") or ""))
    workspace_id = str(manifest.get("client_id") or manifest.get("workspace_id") or _slugify(business)).strip()
    codee_user_id = str(manifest.get("codee_user_id") or _codee_user_id(seed=f"{business}:{owner}:{workspace_id}")).strip()
    active_states = _codeeadmin_active_state_codes(args)
    state_playbook = _codeeadmin_state_playbook(active_states)
    payload = json.loads(json.dumps(CODEEADMIN_MODEL))
    payload.update(
        {
            "created_at": _now(),
            "month": month,
            "focus": focus,
            "workspace": {
                "root": str(root),
                "business": business,
                "owner": owner,
                "workspace_id": workspace_id,
                "codee_user_id": codee_user_id,
                "service": "codeeadmin",
            },
            "owner_next_three": [
                "Approve or adjust the next Invest In Vets land and housing move.",
                "Review the latest route proof before any public campaign or hard-selling push.",
                "Open CODEEMAIL and delivery rooms only for paid-client, donation, sponsor, or urgent support items.",
            ],
            "handled_without_owner": [
                "Keep service, shop, donation, and recurring-money checks in one operating packet.",
                "Route each request to Codee, Landee, Cappy, Bizy, CODEECPA, or guarded research lanes.",
                "Keep proof links, owner tasks, and daily next moves written before work expands.",
            ],
            "proof_routes": [
                {"name": "codeeadmin", "url": CODEEADMIN_URL, "expected": [200]},
                {"name": "codeeadmin-manifest", "url": CODEEADMIN_MANIFEST_URL, "expected": [200]},
                {"name": "codeeadmin-daily", "url": CODEEADMIN_DAILY_DIGEST_URL, "expected": [200]},
                {"name": "codeeadmin-daily-digest", "url": CODEEADMIN_DAILY_DIGEST_MANIFEST_URL, "expected": [200]},
                {"name": "codeeadmin-states", "url": CODEEADMIN_STATES_URL, "expected": [200]},
                {"name": "codeeadmin-state-playbook", "url": CODEEADMIN_STATES_MANIFEST_URL, "expected": [200]},
                {"name": "codeeadmin-state-packet", "url": f"{CODEEADMIN_STATE_PACKET_URL}?state=OH", "expected": [200]},
                {"name": "codeeadmin-state-packets", "url": CODEEADMIN_STATE_PACKET_MANIFEST_URL, "expected": [200]},
                {"name": "codeeadmin-next20", "url": CODEEADMIN_NEXT20_URL, "expected": [200]},
                {"name": "codeeadmin-next20-manifest", "url": CODEEADMIN_NEXT20_MANIFEST_URL, "expected": [200]},
                {"name": "landee-mission-packet", "url": LANDEE_MISSION_PACKET_URL, "expected": [200]},
                {"name": "landee-mission-manifest", "url": LANDEE_MISSION_PACKET_MANIFEST_URL, "expected": [200]},
                {"name": "proof-wall", "url": CODEE_PROOF_WALL_URL, "expected": [200]},
                {"name": "saas-manifest", "url": CODEE_SAAS_MANIFEST_URL, "expected": [200]},
                {"name": "codeecpa-workspace", "url": CODEE_CPA_WORKSPACE_URL, "expected": [200]},
            ],
            "next_commands": [
                f"python3 codee.py codeeadmin {shlex.quote(str(root))} --business {shlex.quote(business)} --owner {shlex.quote(owner)} --focus {shlex.quote(focus)} --write --force",
                f"python3 codee.py doctor {shlex.quote(str(root))}",
                f"python3 codee.py company {shlex.quote(str(root))} --business {shlex.quote(business)} --owner {shlex.quote(owner)} --packet all --month {month} --write --force",
                f"python3 codee.py codeecpa {shlex.quote(str(root))} --business {shlex.quote(business)} --owner {shlex.quote(owner)} --topic {shlex.quote('entity, nonprofit, investor, tax, and land acquisition review')} --write --force",
            ],
            "active_states": active_states,
            "state_playbook": state_playbook,
        }
    )
    digest = _codeeadmin_daily_digest(payload)
    landee_packet = _codeeadmin_landee_packet(payload)
    payload["daily_digest"] = digest
    payload["landee_packet"] = landee_packet
    return payload


def _codeeadmin_markdown(payload: dict[str, Any]) -> str:
    workspace = payload.get("workspace") or {}
    lines = [
        "# CodeeAdmin Daily Operator",
        "",
        f"Generated: {payload.get('created_at')}",
        f"Month: {payload.get('month')}",
        f"Owner: {workspace.get('owner')}",
        f"Business: {workspace.get('business')}",
        f"Focus: {payload.get('focus')}",
        "",
        "## Mission",
        "",
        str(payload.get("mission") or ""),
        "",
        "## Next Three Owner Moves",
        "",
    ]
    lines.extend(f"{index}. {item}" for index, item in enumerate(payload.get("owner_next_three") or [], start=1))
    lines.extend(["", "## Daily Operating Loop", ""])
    lines.extend(f"- {item}" for item in payload.get("daily_operating_loop") or [])
    lines.extend(["", "## Entity Routing", ""])
    for entity in payload.get("entities") or []:
        lines.extend(
            [
                f"### {entity.get('name')}",
                "",
                f"- Role: {entity.get('role')}",
                f"- CodeeAdmin rule: {entity.get('codeeadmin_rule')}",
                "",
            ]
        )
    lines.extend(["## Guardrails", ""])
    lines.extend(f"- {item}" for item in payload.get("owner_focus_rules") or [])
    focus_lock = payload.get("focus_lock") or {}
    lines.extend(["", "## 72-Hour Focus Lock", ""])
    lines.append(f"- Hours: {focus_lock.get('hours', 72)}")
    lines.append(f"- Rule: {focus_lock.get('rule')}")
    lines.extend(["", "## Money Lanes", ""])
    for lane in payload.get("money_lanes") or []:
        lines.append(f"- {lane.get('label')}: {lane.get('rule')}")
    lines.extend(["", "## Weekly Proof Report Slots", ""])
    lines.extend(f"- {item}" for item in payload.get("weekly_proof_report") or [])
    lines.extend(["", "## Proof Commands", ""])
    lines.extend(f"```bash\n{item}\n```" for item in payload.get("next_commands") or [])
    return "\n".join(lines) + "\n"


def _codeeadmin_agent_handoffs_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# AI K9 Agent Handoffs",
        "",
        "CodeeAdmin does not activate a new AI K9 because the name sounds useful. It needs a job, guardrails, proof route, and owner approval gate.",
        "",
    ]
    for agent in payload.get("ai_k9_agents") or []:
        status = str(agent.get("status") or "planned")
        lines.extend(
            [
                f"## {str(agent.get('id') or '').upper()}",
                "",
                f"- Status: {status}",
                f"- Job: {agent.get('job')}",
                f"- Activation gate: {'owner-approved and proof-routed' if status in {'active', 'ready-next'} else 'guarded until policy and proof exist'}",
                "",
            ]
        )
    lines.extend(
        [
            "## Standing Rules",
            "",
            "- Mission, service, shop, and investor work stay separated before money or public claims move.",
            "- Sporty and Tradez remain research-only until written legal, risk, and funding guardrails are reviewed.",
            "- CODEECPA prepares questions and packets; licensed professionals still make final legal, tax, and CPA decisions.",
        ]
    )
    return "\n".join(lines) + "\n"


def _codeeadmin_priority_scorecard(payload: dict[str, Any]) -> dict[str, Any]:
    return {
        "schema": "codeeadmin.priority-scorecard.v1",
        "created_at": _now(),
        "workspace": payload.get("workspace") or {},
        "month": payload.get("month"),
        "focus": payload.get("focus"),
        "owner_next_three": payload.get("owner_next_three") or [],
        "handled_without_owner": payload.get("handled_without_owner") or [],
        "agent_status": {str(item.get("id")): str(item.get("status")) for item in payload.get("ai_k9_agents") or []},
        "proof_gates": [
            {"gate": "route proof", "status": "run doctor or 404 loop before public push", "proof": CODEE_PROOF_WALL_URL},
            {"gate": "money separation", "status": "track services, shops, donations, recurring separately", "proof": "Owner Workspace"},
            {"gate": "professional review", "status": "route legal/tax/investor claims through CODEECPA prep", "proof": CODEE_CPA_WORKSPACE_URL},
            {"gate": "AI K9 initiation", "status": "new agent needs job, guardrails, proof route, owner approval", "proof": CODEEADMIN_URL},
        ],
    }


def _codeeadmin_next20_payload(payload: dict[str, Any]) -> dict[str, Any]:
    workspace = payload.get("workspace") or {}
    active_states = payload.get("active_states") or ["NY", "OH"]
    moves = json.loads(json.dumps(CODEEADMIN_NEXT20_MOVES))
    return {
        "schema": "codeeadmin.next20.v1",
        "version": VERSION,
        "created_at": _now(),
        "public_page": CODEEADMIN_NEXT20_URL,
        "manifest": CODEEADMIN_NEXT20_MANIFEST_URL,
        "business": workspace.get("business"),
        "owner": workspace.get("owner"),
        "focus": payload.get("focus"),
        "active_states": active_states,
        "move_count": len(moves),
        "rule": "Complete these 20 moves in order before opening another public lane. Each move must leave proof, a route, or a written owner handoff.",
        "proof_wall": CODEE_PROOF_WALL_URL,
        "state_tool": CODEEADMIN_STATES_URL,
        "daily_digest": CODEEADMIN_DAILY_DIGEST_URL,
        "landee_packet": LANDEE_MISSION_PACKET_URL,
        "codeecpa_workspace": CODEE_CPA_WORKSPACE_URL,
        "moves": moves,
        "proof_gates": [
            {"gate": "route proof", "command": "python3 tools/codee_404_loop.py --loops 1 --timeout 25 --json", "required": True},
            {"gate": "cli write proof", "command": "python3 codee.py codeeadmin . --write --force", "required": True},
            {"gate": "doctor proof", "command": "python3 codee.py doctor .", "required": True},
            {"gate": "professional review", "command": "Open CODEECPA before legal, tax, grant, land, housing, or investment claims.", "required": True},
        ],
        "owner_next_three": [
            "Review NY and OH source slots before any sponsor or land claim.",
            "Use the Next 20 board as the morning checklist until every move has proof.",
            "Keep new AI K9 ideas parked until CodeeAdmin route proof stays green.",
        ],
    }


def _codeeadmin_next20_markdown(next20: dict[str, Any]) -> str:
    lines = [
        "# CodeeAdmin Next 20 Execution Board",
        "",
        f"Generated: {next20.get('created_at')}",
        f"Owner: {next20.get('owner')}",
        f"Business: {next20.get('business')}",
        f"Focus: {next20.get('focus')}",
        "",
        "## Rule",
        "",
        str(next20.get("rule") or ""),
        "",
        "## Owner Next Three",
        "",
    ]
    lines.extend(f"{index}. {item}" for index, item in enumerate(next20.get("owner_next_three") or [], start=1))
    lines.extend(["", "## Moves", ""])
    for index, move in enumerate(next20.get("moves") or [], start=1):
        lines.extend(
            [
                f"### {index}. {move.get('title')}",
                "",
                f"- ID: {move.get('id')}",
                f"- Owner agent: {move.get('owner_agent')}",
                f"- Proof gate: {move.get('proof_gate')}",
                f"- Output: {move.get('output')}",
                "",
            ]
        )
    lines.extend(["## Proof Gates", ""])
    for gate in next20.get("proof_gates") or []:
        lines.append(f"- {gate.get('gate')}: {gate.get('command')}")
    return "\n".join(lines) + "\n"


def _codeeadmin_daily_digest(payload: dict[str, Any]) -> dict[str, Any]:
    workspace = payload.get("workspace") or {}
    focus_lock = payload.get("focus_lock") or {}
    money_lanes = payload.get("money_lanes") or []
    return {
        "schema": "codeeadmin.daily-digest.v1",
        "created_at": _now(),
        "public_page": CODEEADMIN_DAILY_DIGEST_URL,
        "owner": workspace.get("owner"),
        "business": workspace.get("business"),
        "focus": payload.get("focus"),
        "status": "operator_digest_ready",
        "active_states": payload.get("active_states") or [],
        "state_summary": [
            {
                "code": state.get("code"),
                "name": state.get("name"),
                "stage": (state.get("readiness") or {}).get("stage_label"),
                "score": (state.get("readiness") or {}).get("score"),
                "packet": state.get("public_page"),
            }
            for state in ((payload.get("state_playbook") or {}).get("states") or [])
            if state.get("priority") == "active"
        ],
        "owner_next_three": payload.get("owner_next_three") or [],
        "handled_without_owner": payload.get("handled_without_owner") or [],
        "today_routing": [
            {"lane": "Mission", "agent": "Landee", "move": "Advance land, housing, voucher, sponsor, or donor proof."},
            {"lane": "Paid services", "agent": "Codee", "move": "Protect delivery rooms, service scans, customer support, and paid activation gates."},
            {"lane": "Social/assets", "agent": "Cappy", "move": "Create proof-backed campaign assets only for live routes."},
            {"lane": "Leads", "agent": "Bizy", "move": "Queue follow-up and outreach without promising outcomes."},
            {"lane": "Review", "agent": "CODEECPA", "move": "Prepare legal, tax, nonprofit, investor, and land-acquisition questions for licensed review."},
        ],
        "money_lane_register": [
            {"id": lane.get("id"), "label": lane.get("label"), "owner": lane.get("owner"), "needs_live_amount": True, "rule": lane.get("rule")}
            for lane in money_lanes
        ],
        "focus_lock": {
            "active": True,
            "hours": focus_lock.get("hours", 72),
            "allowed_new_work": focus_lock.get("allowed_new_work") or [],
            "blocked_new_work": focus_lock.get("blocked_new_work") or [],
        },
        "next20_summary": {
            "move_count": len(CODEEADMIN_NEXT20_MOVES),
            "public_page": CODEEADMIN_NEXT20_URL,
            "manifest": CODEEADMIN_NEXT20_MANIFEST_URL,
            "first_five": CODEEADMIN_NEXT20_MOVES[:5],
            "rule": "Use the Next 20 board as the owner-visible execution checklist before any new lane opens.",
        },
        "codeemail_notice": {
            "subject": "CodeeAdmin Daily Digest",
            "category": "CodeeAdmin",
            "priority": "owner",
            "body": "Next three owner moves are ready. CodeeAdmin routed mission, service, content, lead, and review work before opening new lanes.",
            "links": [
                {"label": "Open CodeeAdmin", "url": CODEEADMIN_URL},
                {"label": "Open daily digest", "url": CODEEADMIN_DAILY_DIGEST_URL},
                {"label": "Open state-by-state tool", "url": CODEEADMIN_STATES_URL},
                {"label": "Open Ohio state packet", "url": f"{CODEEADMIN_STATE_PACKET_URL}?state=OH"},
                {"label": "Open Next 20", "url": CODEEADMIN_NEXT20_URL},
                {"label": "Open Landee mission packet", "url": LANDEE_MISSION_PACKET_URL},
                {"label": "Open CODEEMAIL", "url": f"{DEFAULT_API_BASE}/codeemail.html"},
            ],
        },
    }


def _codeeadmin_daily_digest_markdown(digest: dict[str, Any]) -> str:
    lines = [
        "# CodeeAdmin Daily Digest",
        "",
        f"Generated: {digest.get('created_at')}",
        f"Owner: {digest.get('owner')}",
        f"Business: {digest.get('business')}",
        f"Focus: {digest.get('focus')}",
        "",
        "## Next Three",
        "",
    ]
    lines.extend(f"{index}. {item}" for index, item in enumerate(digest.get("owner_next_three") or [], start=1))
    lines.extend(["", "## CodeeAdmin Handled", ""])
    lines.extend(f"- {item}" for item in digest.get("handled_without_owner") or [])
    lines.extend(["", "## Routing", ""])
    for item in digest.get("today_routing") or []:
        lines.append(f"- {item.get('agent')} / {item.get('lane')}: {item.get('move')}")
    lines.extend(["", "## Active State Packets", ""])
    for state in digest.get("state_summary") or []:
        lines.append(f"- {state.get('name')} ({state.get('code')}): {state.get('stage')} / {state.get('score')} structural - {state.get('packet')}")
    next20 = digest.get("next20_summary") or {}
    lines.extend(["", "## Next 20 Execution", ""])
    lines.append(f"- Moves: {next20.get('move_count', len(CODEEADMIN_NEXT20_MOVES))}")
    lines.append(f"- Board: {next20.get('public_page', CODEEADMIN_NEXT20_URL)}")
    lines.append(f"- Rule: {next20.get('rule', '')}")
    lines.extend(["", "## Money Lane Register", ""])
    for lane in digest.get("money_lane_register") or []:
        lines.append(f"- {lane.get('label')} ({lane.get('owner')}): {lane.get('rule')}")
    lines.extend(["", "## CODEEMAIL Notice", ""])
    notice = digest.get("codeemail_notice") or {}
    lines.append(f"Subject: {notice.get('subject')}")
    lines.append("")
    lines.append(str(notice.get("body") or ""))
    return "\n".join(lines) + "\n"


def _codeeadmin_landee_packet(payload: dict[str, Any]) -> dict[str, Any]:
    workspace = payload.get("workspace") or {}
    spec = payload.get("landee_mission_packet") or {}
    return {
        "schema": "landee.mission-packet.v1",
        "created_at": _now(),
        "public_page": LANDEE_MISSION_PACKET_URL,
        "manifest": LANDEE_MISSION_PACKET_MANIFEST_URL,
        "owner": workspace.get("owner"),
        "mission": "Acquire and develop land for veteran housing while keeping technology revenue, nonprofit funds, sponsor funds, and advisor-reviewed commitments separated.",
        "first_regions": spec.get("first_regions") or [],
        "active_state_packets": [
            {
                "code": state.get("code"),
                "name": state.get("name"),
                "packet": state.get("public_page"),
                "readiness": state.get("readiness") or {},
            }
            for state in ((payload.get("state_playbook") or {}).get("states") or [])
            if state.get("priority") == "active"
        ],
        "core_sections": [
            "land search criteria",
            "housing voucher and partner criteria",
            "solar energy development center concept",
            "small data center / Invest In Vets network concept",
            "sponsor and donor packet",
            "board/advisor review checklist",
            "professional questions for zoning, tax, grant, insurance, and real estate review",
        ],
        "next_actions": spec.get("next_actions") or [],
        "funding_separation": [
            "Do not mix donations with paid service revenue.",
            "Do not commit nonprofit funds to land without board/advisor and professional review.",
            "Track sponsor restrictions, donor intent, grant restrictions, and technology support costs separately.",
        ],
        "codeeadmin_gate": "Landee can prepare research and packets. Commitments still need owner, board, advisor, and licensed professional review.",
    }


def _codeeadmin_landee_packet_markdown(packet: dict[str, Any]) -> str:
    lines = [
        "# Landee Mission Packet",
        "",
        f"Generated: {packet.get('created_at')}",
        "",
        "## Mission",
        "",
        str(packet.get("mission") or ""),
        "",
        "## First Regions",
        "",
    ]
    lines.extend(f"- {item}" for item in packet.get("first_regions") or [])
    lines.extend(["", "## Active State Packets", ""])
    for state in packet.get("active_state_packets") or []:
        readiness = state.get("readiness") or {}
        lines.append(f"- {state.get('name')} ({state.get('code')}): {readiness.get('stage_label')} - {state.get('packet')}")
    lines.extend(["", "## Core Sections", ""])
    lines.extend(f"- {item}" for item in packet.get("core_sections") or [])
    lines.extend(["", "## Next Actions", ""])
    lines.extend(f"{index}. {item}" for index, item in enumerate(packet.get("next_actions") or [], start=1))
    lines.extend(["", "## Funding Separation", ""])
    lines.extend(f"- {item}" for item in packet.get("funding_separation") or [])
    lines.extend(["", "## Gate", "", str(packet.get("codeeadmin_gate") or "")])
    return "\n".join(lines) + "\n"


def _codeeadmin_weekly_proof_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# CodeeAdmin Weekly Proof Report",
        "",
        f"Month: {payload.get('month')}",
        "",
        "Use verified numbers only. Leave unknown fields blank instead of guessing.",
        "",
    ]
    for item in payload.get("weekly_proof_report") or []:
        lines.extend([f"## {str(item).title()}", "", "- Verified count:", "- Source/proof link:", "- Notes:", ""])
    lines.extend(["## Mission Progress", "", "- Land/housing packet update:", "- Sponsor/donor update:", "- Board/advisor review needed:", ""])
    return "\n".join(lines)


def command_codeeadmin(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = _codeeadmin_payload(root, args)
    scorecard = _codeeadmin_priority_scorecard(payload)
    digest = payload.get("daily_digest") if isinstance(payload.get("daily_digest"), dict) else _codeeadmin_daily_digest(payload)
    landee_packet = payload.get("landee_packet") if isinstance(payload.get("landee_packet"), dict) else _codeeadmin_landee_packet(payload)
    state_playbook = payload.get("state_playbook") if isinstance(payload.get("state_playbook"), dict) else _codeeadmin_state_playbook(payload.get("active_states") or ["NY", "OH"])
    next20 = _codeeadmin_next20_payload(payload)
    payload["next20_execution_payload"] = next20
    writes: dict[str, bool] = {}
    report_path = _write_report(root, "latest-codeeadmin.json", {"ok": True, "payload": payload, "scorecard": scorecard, "daily_digest": digest, "landee_packet": landee_packet, "next20": next20})
    if args.write:
        codee_dir = root / ".codee"
        admin_dir = codee_dir / "codeeadmin"
        codeemail_dir = codee_dir / "codeemail"
        owner_dir = codee_dir / "owner-workspace"
        landee_dir = codee_dir / "landee"
        state_packets_dir = admin_dir / "states"
        admin_dir.mkdir(parents=True, exist_ok=True)
        codeemail_dir.mkdir(parents=True, exist_ok=True)
        owner_dir.mkdir(parents=True, exist_ok=True)
        landee_dir.mkdir(parents=True, exist_ok=True)
        state_packets_dir.mkdir(parents=True, exist_ok=True)
        writes = {
            "admin_json": _write_json(codee_dir / "codeeadmin.json", payload, force=args.force),
            "admin_manifest": _write_json(admin_dir / "codeeadmin-manifest.json", payload, force=args.force),
            "daily_operator": _write_text(codee_dir / "CODEEADMIN_DAILY_OPERATOR.md", _codeeadmin_markdown(payload), force=args.force),
            "daily_digest_json": _write_json(codee_dir / "reports" / "codeeadmin-daily-digest.json", digest, force=args.force),
            "daily_digest_md": _write_text(codee_dir / "CODEEADMIN_DAILY_DIGEST.md", _codeeadmin_daily_digest_markdown(digest), force=args.force),
            "codeemail_digest_json": _write_json(codeemail_dir / "codeeadmin-daily-digest-codeemail.json", digest.get("codeemail_notice") or {}, force=args.force),
            "codeemail_digest_md": _write_text(codeemail_dir / "CODEEADMIN_DAILY_DIGEST_CODEEMAIL.md", _codeeadmin_daily_digest_markdown(digest), force=args.force),
            "owner_workspace_digest": _write_json(owner_dir / "codeeadmin-owner-summary.json", {"next_three": payload.get("owner_next_three") or [], "money_lanes": digest.get("money_lane_register") or [], "focus_lock": digest.get("focus_lock") or {}, "links": (digest.get("codeemail_notice") or {}).get("links") or []}, force=args.force),
            "state_playbook_json": _write_json(admin_dir / "state-by-state-playbook.json", state_playbook, force=args.force),
            "state_playbook_md": _write_text(admin_dir / "STATE_BY_STATE_PLAYBOOK.md", _codeeadmin_state_playbook_markdown(state_playbook), force=args.force),
            "state_packet_index_json": _write_json(
                admin_dir / "state-packets.json",
                {
                    "schema": "codeeadmin.state-packets.v2",
                    "version": VERSION,
                    "updated_at": "2026-05-27",
                    "public_page": CODEEADMIN_STATE_PACKET_URL,
                    "manifest": CODEEADMIN_STATE_PACKET_MANIFEST_URL,
                    "coverage_count": state_playbook.get("coverage_count"),
                    "active_states": state_playbook.get("active_states") or [],
                    "readiness_stages": state_playbook.get("readiness_stages") or [],
                    "action_rooms": state_playbook.get("action_rooms") or [],
                    "states": state_playbook.get("states") or [],
                    "rule": state_playbook.get("rule"),
                },
                force=args.force,
            ),
            "state_packet_index_md": _write_text(admin_dir / "STATE_PACKET_INDEX.md", _codeeadmin_state_packet_index_markdown(state_playbook), force=args.force),
            "next20_json": _write_json(admin_dir / "next20-execution.json", next20, force=args.force),
            "next20_md": _write_text(admin_dir / "NEXT20_EXECUTION.md", _codeeadmin_next20_markdown(next20), force=args.force),
            "landee_packet_json": _write_json(landee_dir / "landee-mission-packet.json", landee_packet, force=args.force),
            "landee_packet_md": _write_text(landee_dir / "LANDEE_MISSION_PACKET.md", _codeeadmin_landee_packet_markdown(landee_packet), force=args.force),
            "weekly_proof_report": _write_text(admin_dir / "WEEKLY_PROOF_REPORT.md", _codeeadmin_weekly_proof_markdown(payload), force=args.force),
            "focus_lock": _write_json(admin_dir / "72-hour-focus-lock.json", payload.get("focus_lock") or {}, force=args.force),
            "agent_handoffs": _write_text(codee_dir / "AI_K9_AGENT_HANDOFFS.md", _codeeadmin_agent_handoffs_markdown(payload), force=args.force),
            "priority_scorecard": _write_json(codee_dir / "reports" / "codeeadmin-priorities.json", scorecard, force=args.force),
            "admin_routes": _write_json(codee_dir / "codeeadmin-routes.json", payload.get("proof_routes") or [], force=args.force),
        }
        for state_packet in state_playbook.get("states") or []:
            code = str(state_packet.get("code") or "").lower()
            if not code:
                continue
            writes[f"state_packet_{code}_json"] = _write_json(state_packets_dir / f"{code}.json", state_packet, force=args.force)
            if state_packet.get("priority") == "active":
                writes[f"state_packet_{code}_md"] = _write_text(state_packets_dir / f"{code.upper()}_STATE_PACKET.md", _codeeadmin_state_packet_markdown(state_packet), force=args.force)
        state = _load_state(root)
        state.update(
            {
                "business": (payload.get("workspace") or {}).get("business"),
                "owner": (payload.get("workspace") or {}).get("owner"),
                "client_id": (payload.get("workspace") or {}).get("workspace_id"),
                "workspace_id": (payload.get("workspace") or {}).get("workspace_id"),
                "codee_user_id": (payload.get("workspace") or {}).get("codee_user_id"),
                "service": "codeeadmin",
                "focus": payload.get("focus"),
                "codeeadmin_url": CODEEADMIN_URL,
                "codeeadmin_daily_digest_url": CODEEADMIN_DAILY_DIGEST_URL,
                "landee_mission_packet_url": LANDEE_MISSION_PACKET_URL,
                "codeeadmin_states_url": CODEEADMIN_STATES_URL,
                "codeeadmin_state_packet_url": CODEEADMIN_STATE_PACKET_URL,
                "codeeadmin_state_packets_url": CODEEADMIN_STATE_PACKET_MANIFEST_URL,
                "codeeadmin_next20_url": CODEEADMIN_NEXT20_URL,
                "codeeadmin_next20_manifest_url": CODEEADMIN_NEXT20_MANIFEST_URL,
                "active_states": payload.get("active_states") or [],
                "proof_wall_url": CODEE_PROOF_WALL_URL,
            }
        )
        _write_state(root, state)
        _append_event(root, "CodeeAdminConfigured", {"wrote": any(writes.values()), "focus": payload.get("focus"), "agent_count": len(payload.get("ai_k9_agents") or []), "daily_digest": bool(digest), "landee_packet": bool(landee_packet), "next20": bool(next20)})
    if args.open:
        webbrowser.open(CODEEADMIN_URL)
    if args.json:
        print(json.dumps({"ok": True, "payload": payload, "scorecard": scorecard, "writes": writes, "report": str(report_path)}, indent=2))
        return 0
    print("CodeeAdmin owner operator")
    print(f"public_page={CODEEADMIN_URL}")
    print(f"manifest={CODEEADMIN_MANIFEST_URL}")
    print(f"focus={payload.get('focus')}")
    print(f"agents={len(payload.get('ai_k9_agents') or [])}")
    print(f"daily_digest={CODEEADMIN_DAILY_DIGEST_URL}")
    print(f"state_tool={CODEEADMIN_STATES_URL}")
    print(f"next20={CODEEADMIN_NEXT20_URL}")
    print(f"landee_packet={LANDEE_MISSION_PACKET_URL}")
    print("next_three:")
    for item in payload.get("owner_next_three") or []:
        print(f"- {item}")
    print(f"report={report_path}")
    if args.write:
        for name, wrote in writes.items():
            print(f"{name}: {'written' if wrote else 'exists'}")
    return 0


def _company_alignment_markdown(payload: dict[str, Any]) -> str:
    entities = payload.get("entities") or {}
    lines = [
        "# Codee Company Alignment",
        "",
        f"Generated: {_now()}",
        "",
        str(payload.get("disclaimer") or "Operational draft only."),
        "",
        "## Structure",
        "",
        f"- Mission umbrella: {entities.get('mission_umbrella', 'Invest In Vets Foundation')}",
        f"- Technology company: {entities.get('technology_company', 'AI K9 Kennel')}",
        f"- Platform: {entities.get('platform', 'Codee')}",
        f"- Public front door: {entities.get('public_front_door', 'https://codee.chat')}",
        f"- Client surfaces: {entities.get('client_surfaces', DEFAULT_API_BASE)}",
        "",
        "## Alignment",
    ]
    lines.extend(f"- {item}" for item in payload.get("alignment") or [])
    lines.extend(["", "## Paid Tool Value Alignment"])
    lines.extend(f"- {item}" for item in payload.get("subscription_value_alignment") or [])
    lines.extend(["", "## Veteran Founder Path"])
    lines.extend(f"- {item}" for item in payload.get("veteran_founder_path") or [])
    lines.extend(["", "## Defensibility"])
    lines.extend(f"- {item}" for item in payload.get("defensibility_layers") or [])
    lines.extend(["", "## Security Rules"])
    lines.extend(f"- {item}" for item in payload.get("security_rules") or [])
    lines.extend(["", "## Investor Metrics"])
    lines.extend(f"- {item}" for item in payload.get("investor_metrics") or [])
    lines.extend(["", "## Next 20 Moves"])
    lines.extend(f"{index}. {item}" for index, item in enumerate(payload.get("next_20_moves") or [], start=1))
    lines.append("")
    return "\n".join(lines)


def _company_ip_markdown(payload: dict[str, Any]) -> str:
    return """# Codee IP And Defensibility Register

Operational draft. Use this for attorney, CPA, contributor, and investor preparation.

## Protectable Assets

- Codee, AI K9 Kennel, Invest In Vets, QRCodee, CodeeFlyer, CodeeApp, CodeeCard, and related marks.
- Codee CLI, Codee Chat, service templates, delivery rooms, proof loops, training lessons, and public pages.
- Private prompts, workflow notes, backend routing, Stripe handling, scan logic, and customer delivery records.
- Domains, release logs, route scans, proof wall history, and customer support packets.

## Protection Stack

- Trademark search and filing plan.
- Copyright records and release logs.
- Contributor assignment agreements.
- Customer terms, privacy, refund, and acceptable-use policies.
- Trade-secret access policy for private workflows.
- Credential and secret scanning.
- Written nonprofit technology license and related-party approval records.

## Security Rule

No public Codee CLI download should contain owner deploy credentials, Stripe secrets, OAuth refresh tokens, service accounts, or private customer data.
"""


def _company_investor_markdown(payload: dict[str, Any]) -> str:
    metrics = "\n".join(f"- {item}" for item in payload.get("investor_metrics") or [])
    return f"""# Codee Investor Readiness Scorecard

Operational draft. This is not an offer to sell securities and is not investment advice.

## Thesis

Codee becomes valuable when it proves repeatable usage, revenue, delivery, retention, low delivery cost, strong brand, clean mission alignment, and protected workflows.

## Subscription Tool Alignment

- One Codee user ID should connect CLI, chat, portal, delivery room, proof wall, tier, and support state.
- Free or sponsored veteran training should stay separate from paid public subscriptions and Business Suite packages.
- Paid value should increase through usage, hosted activation, scans, support, partner workflows, and Business Suite delivery.
- The investor story should prove active workspaces, free-to-paid conversion, retention, delivery speed, and support cost.

## Weekly Metrics

{metrics}

## Data Room Minimum

- Product proof.
- Revenue proof.
- Delivery-room proof.
- Customer support proof.
- Impact reports.
- IP and brand register.
- Security and compliance proof.
- Platform architecture.
- Nonprofit alignment policy.
- Monthly founder report.
"""


def _company_impact_markdown(payload: dict[str, Any]) -> str:
    return """# Codee Impact Model

Operational draft for Invest In Vets and AI K9 Kennel alignment.

## Core Model

Business tools create revenue. Revenue funds better tools, training, support, and mission capacity. Mission capacity supports homeless and disabled veterans through training, sponsored service access, partner relationships, and housing pathway work.

## Required Separation

- Keep nonprofit funds and company funds separate.
- Use written agreements for any licensing, services, sponsorships, or shared assets.
- Use board approval and conflict-of-interest review for related-party transactions.
- Do not promise guaranteed income, benefits, grants, loans, housing, or approvals.

## Mission Metrics

- Veteran trainees served.
- Free or sponsored service lanes delivered.
- Training completions.
- Hosted sites launched.
- Sponsor leads.
- Housing partner conversations.
- Housing node planning milestones.
- Funds allocated to mission programs.

## Veteran Founder Model

- Each veteran founder should start with one Codee agent and one service lane.
- The first investible packet should include founder story, offer, first customer proof, delivery proof, route scan, support notes, and advisor review status.
- Do not promise guaranteed wealth, funding, benefits, approvals, or housing.
"""


def _company_month(value: str = "") -> str:
    raw = str(value or "").strip()
    if re.fullmatch(r"\d{4}-\d{2}", raw):
        return raw
    return dt.datetime.now().strftime("%Y-%m")


def _company_public_workspace(root: Path, args: argparse.Namespace) -> dict[str, str]:
    business = str(args.business or "").strip() or "Codee"
    owner = str(args.owner or "").strip() or "Owner"
    if bool(getattr(args, "public_safe", False)):
        return {"business": business, "owner": "Owner", "root": "public-safe"}
    return {"business": business, "owner": owner, "root": str(root)}


def _company_data_room_markdown(payload: dict[str, Any], *, month: str) -> str:
    folders = "\n".join(f"- {item}" for item in ((payload.get("data_room") or {}).get("folders") or []))
    return f"""# Codee Data Room Index

Month: {month}

Operational draft. Keep private customer data, credentials, internal prompts, and unreconciled financials out of public packets.

## Folder Structure

{folders}

## Minimum Proof

- Product demo links.
- Public proof wall and latest route-loop report.
- CLI doctor report from a generated workspace.
- Stripe revenue export or owner-approved summary.
- Customer delivery-room examples with private data removed.
- Refund and support summary.
- IP and brand register.
- Nonprofit alignment and professional-review notes.
- Monthly investor and mission impact reports.
- Veteran founder case-study packets.
- Subscription and retention metrics by tier.
"""


def _company_governance_markdown(payload: dict[str, Any]) -> str:
    reviews = "\n".join(f"- {item}" for item in payload.get("professional_review_required") or [])
    return f"""# Codee Governance Checklist

Operational draft for owner, attorney, CPA, and board preparation.

## Required Reviews

{reviews}

## Separation Rules

- Keep Invest In Vets Foundation funds separate from AI K9 Kennel funds.
- Use written agreements for technology licensing, sponsorships, grants, services, and shared assets.
- Use board approval and conflict-of-interest review for related-party nonprofit transactions.
- Keep public fundraising language accurate.
- Do not promise income, housing, benefits, grants, loans, tax outcomes, investment outcomes, or approvals.

## Owner Admin Rules

- Archive deploy logs, scan reports, payment references, and delivery artifacts.
- Track actual outcomes monthly.
- Keep every client delivery room as the source of truth.
- Route legal, tax, nonprofit, securities, and insurance questions to qualified professionals.
"""


def _company_trade_secret_markdown(payload: dict[str, Any]) -> str:
    layers = "\n".join(f"- {item}" for item in payload.get("defensibility_layers") or [])
    return f"""# Codee Trade Secret Register

Operational draft. This is a working register for internal process protection.

## Protected Workflow Areas

{layers}

## Access Rules

- Restrict internal prompts, scan logic, Stripe routing, GCloud deployment notes, delivery-room templates, and customer support patterns.
- Do not publish owner credentials, OAuth refresh tokens, service accounts, Stripe secrets, or customer private data.
- Use contributor assignment or license agreements before accepting outside code, designs, prompts, videos, templates, or customer assets.
- Keep public open-source courses useful without exposing restricted backend processes.
"""


def _company_contributor_markdown(payload: dict[str, Any]) -> str:
    return """# Codee Contributor Assignment Checklist

Operational draft. Use this to prepare counsel-reviewed contributor paperwork.

## Before Work Is Accepted

- Identify contributor legal name and contact.
- Define whether the work is employment, contractor work, volunteer work, or licensed third-party work.
- List contributed code, prompts, images, videos, templates, copy, or client materials.
- Confirm whether AI-generated assets were used and what source tools were used.
- Confirm the contributor has the right to assign or license the work.
- Assign or license the work to the correct entity in writing before it becomes proprietary Codee material.

## Never Accept Blindly

- Logos, music, stock images, client data, private documents, copyrighted PDFs, or platform exports without a license or written permission.
"""


def _company_license_prep_markdown(payload: dict[str, Any]) -> str:
    return """# Nonprofit Technology License Prep

Operational draft for attorney, CPA, and board review.

## Goal

Prepare a clean path where AI K9 Kennel can license selected Codee technology to Invest In Vets Foundation for training, mission support, and approved nonprofit programs.

## Terms To Review

- Licensed technology scope.
- Nonprofit use rights.
- Public training rights.
- Brand use rules.
- Support responsibilities.
- Data and privacy boundaries.
- Fair-market value or donation treatment.
- Conflict-of-interest disclosure.
- Board approval and renewal process.
- Termination and audit rights.

## Do Not State As Final Until Reviewed

- Ownership transfer.
- Revenue share.
- Tax treatment.
- Donation treatment.
- Securities or investor language.
- Guaranteed outcomes.
"""


def _company_monthly_impact_markdown(payload: dict[str, Any], *, month: str) -> str:
    metrics = "\n".join(f"- {item}: ______" for item in payload.get("monthly_metrics") or [])
    return f"""# Codee Monthly Impact Report

Month: {month}

Operational draft. Publish only verified numbers.

## Business Metrics

{metrics}

## Mission Narrative

This month, Codee's business tools supported the mission by: ______

## Proof Links

- Public proof wall: {CODEE_PROOF_WALL_URL}
- Company alignment: {CODEE_COMPANY_ALIGNMENT_URL}
- Impact model: {CODEE_IMPACT_MODEL_URL}

## Required Review

Attorney, CPA, and board review are required before this report is used for legal, tax, fundraising, or investor claims.
"""


def _company_case_study_markdown(payload: dict[str, Any]) -> str:
    lanes = "\n".join(f"- {item}" for item in payload.get("case_study_lanes") or [])
    return f"""# Codee Case Study Template

## Approved Lanes To Document

{lanes}

## Case Study Format

- Client or demo name:
- Service lane:
- Problem:
- Assets received:
- What Codee generated:
- Payment or activation path:
- Delivery room:
- Proof scan:
- Result:
- Next upsell:
- Mission connection:

## Public-Safe Rule

Remove private customer information, payment IDs, internal prompts, credentials, and unreconciled financial numbers before publishing.
"""


def _company_investor_scorecard(payload: dict[str, Any], *, month: str, workspace: dict[str, str]) -> dict[str, Any]:
    return {
        "schema": "codee.investor-scorecard.v1",
        "created_at": _now(),
        "month": month,
        "workspace": workspace,
        "metrics": {str(item): None for item in payload.get("monthly_metrics") or []},
        "readiness_gates": [
            {"gate": "public routes", "status": "prove with 404 loop", "proof": CODEE_PROOF_WALL_URL},
            {"gate": "company alignment", "status": "listed", "proof": CODEE_COMPANY_ALIGNMENT_URL},
            {"gate": "agent investment model", "status": "listed", "proof": CODEE_AGENT_INVESTMENT_MODEL_URL},
            {"gate": "IP register", "status": "listed", "proof": CODEE_IP_REGISTER_URL},
            {"gate": "impact model", "status": "listed", "proof": CODEE_IMPACT_MODEL_URL},
            {"gate": "data room", "status": "owner packet", "proof": ".codee/company/DATA_ROOM_INDEX.md"},
            {"gate": "professional review", "status": "required", "proof": "attorney, CPA, and board review required"},
        ],
    }


def command_company(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = json.loads(json.dumps(CODEE_COMPANY_ALIGNMENT))
    payload["created_at"] = _now()
    month = _company_month(str(getattr(args, "month", "") or ""))
    packet = str(getattr(args, "packet", "") or "all").strip() or "all"
    payload["workspace"] = _company_public_workspace(root, args)
    payload["month"] = month
    payload["public_safe"] = bool(getattr(args, "public_safe", False))
    scorecard = {
        "schema": "codee.company-scorecard.v1",
        "created_at": _now(),
        "month": month,
        "workspace": payload["workspace"],
        "readiness_gates": [
            {"gate": "public alignment pages", "status": "listed", "proof": CODEE_COMPANY_ALIGNMENT_URL},
            {"gate": "IP and defensibility register", "status": "listed", "proof": CODEE_IP_REGISTER_URL},
            {"gate": "investor scorecard", "status": "listed", "proof": CODEE_INVESTOR_READINESS_URL},
            {"gate": "agent investment model", "status": "listed", "proof": CODEE_AGENT_INVESTMENT_MODEL_URL},
            {"gate": "impact model", "status": "listed", "proof": CODEE_IMPACT_MODEL_URL},
            {"gate": "proof wall", "status": "listed", "proof": CODEE_PROOF_WALL_URL},
            {"gate": "legal and CPA review", "status": "required", "proof": "professional review still required"},
        ],
    }
    writes: dict[str, bool] = {}
    if args.write:
        codee_dir = root / ".codee"
        company_dir = codee_dir / "company"
        codee_dir.mkdir(parents=True, exist_ok=True)
        company_dir.mkdir(parents=True, exist_ok=True)
        selected = set(["governance", "ip", "investor", "impact", "data-room", "case-study"] if packet == "all" else [packet])
        investor_scorecard = _company_investor_scorecard(payload, month=month, workspace=payload["workspace"])
        workspace_manifest = {
            "schema": "codee.company-workspace.v1",
            "version": VERSION,
            "created_at": _now(),
            "business": payload["workspace"]["business"],
            "owner": payload["workspace"]["owner"],
            "service": "codee-company-alignment",
            "month": month,
            "portal_url": CODEE_PORTAL_URL,
            "proof_wall_url": CODEE_PROOF_WALL_URL,
            "company_alignment_url": CODEE_COMPANY_ALIGNMENT_URL,
            "agent_investment_model_url": CODEE_AGENT_INVESTMENT_MODEL_URL,
        }
        workspace_routes = [
            {"name": "company-alignment", "url": CODEE_COMPANY_ALIGNMENT_URL, "expected": [200]},
            {"name": "ip-register", "url": CODEE_IP_REGISTER_URL, "expected": [200]},
            {"name": "investor-readiness", "url": CODEE_INVESTOR_READINESS_URL, "expected": [200]},
            {"name": "agent-investment-model", "url": CODEE_AGENT_INVESTMENT_MODEL_URL, "expected": [200]},
            {"name": "impact-model", "url": CODEE_IMPACT_MODEL_URL, "expected": [200]},
            {"name": "business-with-a-mission", "url": CODEE_BUSINESS_MISSION_URL, "expected": [200]},
            {"name": "impact-report-template", "url": CODEE_IMPACT_REPORT_TEMPLATE_URL, "expected": [200]},
            {"name": "data-room-checklist", "url": CODEE_DATA_ROOM_CHECKLIST_URL, "expected": [200]},
        ]
        writes = {
            "workspace_manifest": _write_json(codee_dir / "codee.json", workspace_manifest, force=args.force),
            "workspace_routes": _write_json(codee_dir / "routes.json", workspace_routes, force=args.force),
            "workspace_state": bool(_write_state(root, {"business": payload["workspace"]["business"], "owner": payload["workspace"]["owner"], "service": "codee-company-alignment", "month": month, "updated_at": _now()})),
            "company_alignment_json": _write_json(codee_dir / "company-alignment.json", payload, force=args.force),
            "company_alignment_md": _write_text(codee_dir / "COMPANY_ALIGNMENT.md", _company_alignment_markdown(payload), force=args.force),
            "ip_register_md": _write_text(codee_dir / "IP_AND_DEFENSIBILITY.md", _company_ip_markdown(payload), force=args.force),
            "investor_readiness_md": _write_text(codee_dir / "INVESTOR_READINESS.md", _company_investor_markdown(payload), force=args.force),
            "impact_model_md": _write_text(codee_dir / "IMPACT_MODEL.md", _company_impact_markdown(payload), force=args.force),
            "company_scorecard_json": _write_json(codee_dir / "company-scorecard.json", scorecard, force=args.force),
            "company_dir_alignment_json": _write_json(company_dir / "company-alignment.json", payload, force=args.force),
        }
        if "data-room" in selected:
            writes["data_room_index"] = _write_text(company_dir / "DATA_ROOM_INDEX.md", _company_data_room_markdown(payload, month=month), force=args.force)
        if "governance" in selected:
            writes["governance_checklist"] = _write_text(company_dir / "GOVERNANCE_CHECKLIST.md", _company_governance_markdown(payload), force=args.force)
            writes["nonprofit_license_prep"] = _write_text(company_dir / "NONPROFIT_TECH_LICENSE_PREP.md", _company_license_prep_markdown(payload), force=args.force)
        if "ip" in selected:
            writes["trade_secret_register"] = _write_text(company_dir / "TRADE_SECRET_REGISTER.md", _company_trade_secret_markdown(payload), force=args.force)
            writes["contributor_assignment_checklist"] = _write_text(company_dir / "CONTRIBUTOR_ASSIGNMENT_CHECKLIST.md", _company_contributor_markdown(payload), force=args.force)
        if "impact" in selected:
            writes["monthly_impact_report"] = _write_text(company_dir / f"MONTHLY_IMPACT_REPORT_{month}.md", _company_monthly_impact_markdown(payload, month=month), force=args.force)
        if "case-study" in selected:
            writes["case_study_template"] = _write_text(company_dir / "CASE_STUDY_TEMPLATE.md", _company_case_study_markdown(payload), force=args.force)
        if "investor" in selected:
            writes["investor_scorecard"] = _write_json(company_dir / f"INVESTOR_SCORECARD_{month}.json", investor_scorecard, force=args.force)
        _append_event(root, "CompanyAlignmentConfigured", {"wrote": any(writes.values()), "business": payload["workspace"]["business"], "packet": packet, "month": month})
    if args.open:
        webbrowser.open(CODEE_COMPANY_ALIGNMENT_URL)
    if args.json:
        print(json.dumps({"ok": True, "payload": payload, "scorecard": scorecard, "packet": packet, "month": month, "writes": writes}, indent=2))
        return 0
    print("Codee company alignment")
    print(f"mission_umbrella={payload['entities']['mission_umbrella']}")
    print(f"technology_company={payload['entities']['technology_company']}")
    print(f"platform={payload['entities']['platform']}")
    print(f"alignment_page={CODEE_COMPANY_ALIGNMENT_URL}")
    print(f"ip_register={CODEE_IP_REGISTER_URL}")
    print(f"investor_readiness={CODEE_INVESTOR_READINESS_URL}")
    print(f"agent_investment_model={CODEE_AGENT_INVESTMENT_MODEL_URL}")
    print(f"impact_model={CODEE_IMPACT_MODEL_URL}")
    if args.write:
        for name, wrote in writes.items():
            print(f"{name}: {'written' if wrote else 'exists'}")
    print(f"packet={packet}")
    print(f"month={month}")
    print("next_moves=" + str(len(payload.get("next_20_moves") or [])))
    return 0


def _task_payload(root: Path, args: argparse.Namespace, *, existing: dict[str, Any] | None = None) -> dict[str, Any]:
    manifest = _load_manifest(root)
    course_packet = _read_json_if_exists(root / "codee-course.json")
    activation_packet = _read_json_if_exists(root / ".codee" / "course-activation.json")
    service = _normalize_service(str(getattr(args, "service", "") or (existing or {}).get("service") or "codee-cli"))
    title = str(getattr(args, "title", "") or (existing or {}).get("title") or "Codee task").strip()
    prompt = str(getattr(args, "prompt", "") or (existing or {}).get("prompt") or "").strip()
    agent = str(getattr(args, "agent", "") or (existing or {}).get("agent") or "builder").strip()
    task_id = str((existing or {}).get("task_id") or getattr(args, "task_id", "") or "").strip() or _task_id(title, service, root)
    acceptance = [
        "The folder has a clear index.html or generated service output.",
        "The selected Codee service lane is named and verified.",
        "Payment/hosting remains gated until Stripe/payment proof is present.",
        "A delivery room or support path is available for the client.",
        "The latest proof report is saved under .codee/reports.",
    ]
    return {
        "schema": "codee.task.v1",
        "task_id": task_id,
        "created_at": str((existing or {}).get("created_at") or _now()),
        "updated_at": _now(),
        "status": str((existing or {}).get("status") or "local_created"),
        "title": title,
        "prompt": prompt,
        "service": service,
        "agent": agent,
        "priority": str(getattr(args, "priority", "") or (existing or {}).get("priority") or "normal"),
        "workspace_id": str(manifest.get("client_id") or root.name),
        "client_id": str(manifest.get("client_id") or root.name),
        "codee_user_id": str(manifest.get("codee_user_id") or _codee_user_id(seed=str(root))),
        "business": str(getattr(args, "business", "") or manifest.get("business") or course_packet.get("business") or activation_packet.get("business") or "Codee Client"),
        "owner": str(getattr(args, "owner", "") or manifest.get("owner") or "Business Owner"),
        "account_email": str(getattr(args, "email", "") or manifest.get("owner_email") or "").strip().lower(),
        "folder_inventory": _folder_inventory(root),
        "workspace_fingerprint": _workspace_fingerprint(root, _folder_inventory(root)),
        "permission_mode": str(getattr(args, "mode", "") or (existing or {}).get("permission_mode") or "suggest"),
        "acceptance": (existing or {}).get("acceptance") or acceptance,
        "result": str(getattr(args, "result", "") or (existing or {}).get("result") or "").strip(),
        "backend": (existing or {}).get("backend") if isinstance((existing or {}).get("backend"), dict) else {},
        "source_surface": "codee-cli",
        "cli_version": VERSION,
    }


def command_task(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    action = str(args.task_action or "").strip()
    if action == "list":
        tasks = _list_tasks(root)
        payload = {"ok": True, "count": len(tasks), "tasks": tasks}
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            print(f"Codee tasks: {len(tasks)}")
            for task in tasks:
                print(f"- {task.get('task_id')}: {task.get('status')} {task.get('title')}")
        return 0

    if action == "create":
        payload = _task_payload(root, args)
        _tasks_dir(root).mkdir(parents=True, exist_ok=True)
        _write_json(_task_path(root, payload["task_id"]), payload, force=True)
        _write_text(_tasks_dir(root) / f"{payload['task_id']}.md", _task_markdown(payload), force=True)
        _append_event(root, "TaskCreated", {"task_id": payload["task_id"], "service": payload["service"], "agent": payload["agent"]})
        if args.send:
            result = _request_json("POST", _api_url(args.api_base, "/api/codee/cli/tasks"), payload, timeout=float(args.timeout))
            payload["backend"] = result
            payload["status"] = "sent" if result.get("ok") else "send_failed"
            payload["updated_at"] = _now()
            _write_json(_task_path(root, payload["task_id"]), payload, force=True)
            _write_text(_tasks_dir(root) / f"{payload['task_id']}.md", _task_markdown(payload), force=True)
            _append_event(root, "TaskSent", {"task_id": payload["task_id"], "ok": bool(result.get("ok")), "backend_status": result.get("status")})
        if args.json:
            print(json.dumps(payload | {"path": str(_task_path(root, payload["task_id"]))}, indent=2))
        else:
            print(f"Codee task created: {payload['task_id']}")
            print(f"status={payload['status']} service={payload['service']} agent={payload['agent']}")
            print(f"task={_task_path(root, payload['task_id'])}")
            if payload.get("backend"):
                print(f"backend_ok={payload['backend'].get('ok')} workbench={payload['backend'].get('workbench_url', '')}")
        return 0 if payload.get("status") != "send_failed" else 1

    task_id = str(args.task_id or "").strip()
    if not task_id:
        print("--task-id is required for this task action.")
        return 2
    existing = _read_task(root, task_id)
    if not existing:
        print(f"Task not found: {task_id}")
        return 1

    if action == "status":
        if args.live:
            result = _request_json("GET", _api_url(args.api_base, f"/api/codee/cli/tasks/{task_id}"), timeout=float(args.timeout))
            existing["backend"] = result
            existing["updated_at"] = _now()
            _write_json(_task_path(root, task_id), existing, force=True)
        if args.json:
            print(json.dumps(existing, indent=2))
        else:
            print(f"Codee task: {task_id}")
            print(f"status={existing.get('status')} service={existing.get('service')} agent={existing.get('agent')}")
            if existing.get("backend"):
                print(f"backend_ok={existing['backend'].get('ok')} backend_status={existing['backend'].get('status', '')}")
        return 0

    if action == "send":
        result = _request_json("POST", _api_url(args.api_base, "/api/codee/cli/tasks"), existing, timeout=float(args.timeout))
        existing["backend"] = result
        existing["status"] = "sent" if result.get("ok") else "send_failed"
        existing["updated_at"] = _now()
        _write_json(_task_path(root, task_id), existing, force=True)
        _append_event(root, "TaskSent", {"task_id": task_id, "ok": bool(result.get("ok")), "backend_status": result.get("status")})
        if args.json:
            print(json.dumps(existing, indent=2))
        else:
            print(f"Codee task send: ok={result.get('ok')} task_id={task_id}")
            print(f"workbench={result.get('workbench_url', '')}")
        return 0 if result.get("ok") else 1

    if action == "run":
        platform_result: dict[str, Any] = {}
        if args.write_platform:
            platform_result = _write_platform_layer(
                root,
                mode=str(existing.get("permission_mode") or args.mode or "suggest"),
                business=str(existing.get("business") or ""),
                service=str(existing.get("service") or "codee-service"),
                api_base=args.api_base,
                force=bool(args.force),
            )
            _append_event(root, "PlatformConfigured", {"mode": existing.get("permission_mode") or args.mode, "source": "task-run", "task_id": task_id})
        report, report_path = _task_run_report(root, existing, args, platform_result=platform_result)
        existing["status"] = report["status"]
        existing["result"] = report["result"]
        existing["updated_at"] = _now()
        existing["runner"] = {
            "ok": report["ok"],
            "report": str(report_path),
            "fail_count": report["fail_count"],
            "warn_count": report["warn_count"],
            "route_results": report.get("route_results") or [],
        }
        _write_json(_task_path(root, task_id), existing, force=True)
        _write_text(_tasks_dir(root) / f"{task_id}.md", _task_markdown(existing), force=True)
        backend_result: dict[str, Any] = {}
        if args.send_result:
            backend_payload = existing | {
                "status": report["status"],
                "result": report["result"],
                "task_run": report,
                "proof_report": report,
            }
            backend_result = _request_json("POST", _api_url(args.api_base, f"/api/codee/cli/tasks/{task_id}/result"), backend_payload, timeout=float(args.timeout))
            existing["backend"] = backend_result
            existing["status"] = str(backend_result.get("status") or existing["status"]) if backend_result.get("ok") else "result_send_failed"
            existing["updated_at"] = _now()
            _write_json(_task_path(root, task_id), existing, force=True)
        _append_event(root, "TaskRun", {"task_id": task_id, "ok": bool(report["ok"]), "status": existing.get("status"), "report": str(report_path)})
        if args.json:
            print(json.dumps(report | {"backend": backend_result}, indent=2))
        else:
            print(f"Codee task run: ok={report['ok']} task_id={task_id} status={existing.get('status')}")
            print(f"fails={report['fail_count']} warnings={report['warn_count']}")
            print(f"report={report_path}")
            if backend_result:
                print(f"backend_ok={backend_result.get('ok')} backend_status={backend_result.get('status', '')}")
        return 0 if report["ok"] and (not backend_result or backend_result.get("ok")) else 1

    if action == "result":
        if args.result:
            existing["result"] = str(args.result).strip()
            existing["status"] = "result_saved"
            existing["updated_at"] = _now()
            _write_json(_task_path(root, task_id), existing, force=True)
            _write_text(_tasks_dir(root) / f"{task_id}.md", _task_markdown(existing), force=True)
            _append_event(root, "TaskResult", {"task_id": task_id, "status": existing.get("status")})
        if args.json:
            print(json.dumps(existing, indent=2))
        else:
            print(f"Codee task result: {task_id}")
            print(existing.get("result") or "Pending.")
        return 0

    print(f"Unknown task action: {action}")
    return 2


def command_room(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _load_manifest(root)
    service = str(args.service or "codee-support").strip()
    url = str(args.url or "").strip() or _delivery_room_url(manifest, service=service)
    payload = {
        "ok": True,
        "codee_user_id": str(manifest.get("codee_user_id") or ""),
        "workspace_id": str(manifest.get("client_id") or root.name),
        "business": str(manifest.get("business") or ""),
        "service": service,
        "delivery_room_url": url,
    }
    _write_report(root, "latest-delivery-room.json", payload)
    if args.json:
        print(json.dumps(payload, indent=2))
    else:
        print(f"Codee delivery room: {url}")
        print(f"codee_user_id={payload['codee_user_id']}")
        print(f"workspace_id={payload['workspace_id']}")
    if args.open:
        webbrowser.open(url)
    return 0


def command_account(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _load_manifest(root)
    service = str(args.service or "codee-support").strip()
    owner_email = str(args.email or manifest.get("owner_email") or "").strip().lower()
    codee_user_id = str(manifest.get("codee_user_id") or "").strip() or _codee_user_id(owner_email, str(manifest.get("client_id") or root.name))
    workspace_id = str(manifest.get("client_id") or root.name)
    license_payload = _read_json_if_exists(root / ".codee" / "license.json")
    skill_policy = _read_json_if_exists(root / ".codee" / "skills.json")
    skill_check = _read_json_if_exists(root / ".codee" / "reports" / "latest-skill-check.json")
    route_report = _read_json_if_exists(root / ".codee" / "reports" / "latest-route-scan.json")
    support_report = _read_json_if_exists(root / ".codee" / "reports" / "latest-support-request.json")
    delivery_room_url = _delivery_room_url(manifest | {"codee_user_id": codee_user_id}, service=service)
    workbench_url = _workbench_url(manifest | {"codee_user_id": codee_user_id}, service=service)
    next_commands = [
        "python3 codee.py money-map .",
        "python3 codee.py skills --access public",
        "python3 codee.py skill-policy . --preset operator --force",
        "python3 codee.py skill-check browser-scan .",
        "python3 codee.py courses",
        "python3 codee.py course-init ./qrcodee-course --course qrcodee --business \"My Business\" --target-url https://example.com --force",
        "python3 codee.py course-smoke ./qrcodee-course",
        "python3 codee.py browser-scan . --url https://example.com --full-page",
        f"python3 codee.py room . --service {service}",
        f"python3 codee.py support . --service {service} --message \"Describe the update Codee should make.\"",
        f"python3 codee.py upgrade . --plan pro --email {owner_email or 'owner@example.com'}",
    ]
    payload = {
        "ok": True,
        "created_at": _now(),
        "cli_version": VERSION,
        "workspace_root": str(root),
        "business": str(manifest.get("business") or ""),
        "owner": str(manifest.get("owner") or ""),
        "owner_email": owner_email,
        "codee_user_id": codee_user_id,
        "user_id": codee_user_id,
        "workspace_id": workspace_id,
        "client_id": workspace_id,
        "service": service,
        "delivery_room_url": delivery_room_url,
        "workbench_url": workbench_url,
        "license": license_payload if license_payload else {"exists": False},
        "skill_policy": {
            "exists": bool(skill_policy),
            "preset": skill_policy.get("preset") if skill_policy else "",
            "enabled": skill_policy.get("enabled") if skill_policy else [],
        },
        "latest_skill_check": {
            "exists": bool(skill_check),
            "ok": skill_check.get("ok") if skill_check else None,
            "skill_count": len(skill_check.get("skills") or []) if skill_check else None,
        },
        "latest_route_scan": {
            "exists": bool(route_report),
            "ok": route_report.get("ok") if route_report else None,
            "failed_count": len(route_report.get("failed") or []) if route_report else None,
        },
        "latest_support_request": {
            "exists": bool(support_report),
            "request_id": support_report.get("request_id") if support_report else "",
            "service": support_report.get("service") if support_report else "",
            "title": support_report.get("title") if support_report else "",
        },
        "next_commands": next_commands,
        "rule": "The Codee account is useful only when identity, payment proof, delivery room, route scans, and support packets stay tied to the same workspace id.",
    }
    report_path = _write_report(root, "latest-account.json", payload)
    if args.json:
        print(json.dumps(payload | {"report": str(report_path)}, indent=2))
    else:
        print("Codee account")
        print(f"business={payload['business'] or 'Codee Client'}")
        print(f"codee_user_id={codee_user_id}")
        print(f"workspace_id={workspace_id}")
        print(f"delivery_room={delivery_room_url}")
        print(f"workbench={workbench_url}")
        print(f"skill_policy={payload['skill_policy']['preset'] or 'missing'} enabled={len(payload['skill_policy']['enabled'] or [])}")
        print(f"license_paid={license_payload.get('paid') if license_payload else False}")
        print(f"latest_route_scan_ok={payload['latest_route_scan']['ok']}")
        print(f"report={report_path}")
    if args.open:
        webbrowser.open(workbench_url)
    return 0


def command_workbench(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _load_manifest(root)
    service = str(args.service or "codee-support").strip()
    url = str(args.url or "").strip() or _workbench_url(manifest, service=service)
    payload = {
        "ok": True,
        "created_at": _now(),
        "codee_user_id": str(manifest.get("codee_user_id") or ""),
        "workspace_id": str(manifest.get("client_id") or root.name),
        "business": str(manifest.get("business") or ""),
        "service": service,
        "workbench_url": url,
        "delivery_room_url": _delivery_room_url(manifest, service=service),
    }
    report_path = _write_report(root, "latest-workbench.json", payload)
    if args.json:
        print(json.dumps(payload | {"report": str(report_path)}, indent=2))
    else:
        print(f"Codee workbench: {url}")
        print(f"workspace_id={payload['workspace_id']}")
        print(f"delivery_room={payload['delivery_room_url']}")
        print(f"report={report_path}")
    if args.open:
        webbrowser.open(url)
    return 0


def _portal_url(manifest: dict[str, Any], *, service: str = "codee-support", plan: str = "") -> str:
    query = {
        "codee_user_id": str(manifest.get("codee_user_id") or ""),
        "workspace_id": str(manifest.get("client_id") or manifest.get("workspace_id") or ""),
        "client_id": str(manifest.get("client_id") or manifest.get("workspace_id") or ""),
        "business": str(manifest.get("business") or ""),
        "service": service,
        "plan": plan,
        "source": "codee-cli",
    }
    return f"{CODEE_PORTAL_URL}?{urllib.parse.urlencode({k: v for k, v in query.items() if v})}"


def _launch_workspace(root: Path, args: argparse.Namespace) -> dict[str, Any]:
    manifest = _load_manifest(root)
    business = str(getattr(args, "business", "") or manifest.get("business") or "Codee Client").strip()
    owner = str(getattr(args, "owner", "") or manifest.get("owner") or "Business Owner").strip()
    email = str(getattr(args, "email", "") or manifest.get("owner_email") or "").strip().lower()
    service = _normalize_service(str(getattr(args, "service", "") or manifest.get("service") or "codeeqr"))
    workspace_id = str(manifest.get("client_id") or manifest.get("workspace_id") or _slugify(business or root.name)).strip()
    codee_user_id = str(manifest.get("codee_user_id") or _codee_user_id(email, workspace_id)).strip()
    mini_manifest = {"client_id": workspace_id, "codee_user_id": codee_user_id, "business": business}
    return {
        "business": business,
        "owner": owner,
        "email": email,
        "service": service,
        "workspace_id": workspace_id,
        "codee_user_id": codee_user_id,
        "root": str(root),
        "portal_url": _portal_url(mini_manifest, service=service, plan=str(getattr(args, "plan", "") or "")),
        "delivery_room_url": _delivery_room_url(mini_manifest, service=service),
    }


def _launch_packet(root: Path, args: argparse.Namespace) -> dict[str, Any]:
    workspace = _launch_workspace(root, args)
    return {
        "ok": True,
        "schema": "codee.public-launch.v1",
        "version": VERSION,
        "created_at": _now(),
        "workspace": workspace,
        "public_pages": {
            "launch": CODEE_LAUNCH_URL,
            "launch_checklist": CODEE_LAUNCH_CHECKLIST_URL,
            "onboarding": CODEE_ONBOARDING_URL,
            "cli": f"{DEFAULT_API_BASE}/codee-cli.html",
            "portal": CODEE_PORTAL_URL,
            "proof_wall": CODEE_PROOF_WALL_URL,
            "saas": CODEE_SAAS_URL,
            "business_suite": f"{DEFAULT_API_BASE}/codee-chat.html?service=minicodeesite&tier=supported-build&source=codee-launch",
            "codeecpa": CODEE_CPA_URL,
            "codeecpa_workspace": CODEE_CPA_WORKSPACE_URL,
        },
        "moves": CODEE_PUBLIC_LAUNCH_20_MOVES,
        "acceptance": [
            "Every public page returns 200.",
            "The CLI can generate the launch packet and pass doctor.",
            "Preview is allowed before payment, but true hosting/deploy remains gated.",
            "Free veteran training and paid public customers stay separated in copy and records.",
            "Legal, tax, nonprofit, and investor claims are routed through professional review.",
        ],
        "next_commands": [
            f"python3 codee.py starter {root} --preset qrcodee --business \"{workspace['business']}\" --email {workspace['email'] or 'owner@example.com'} --force",
            f"python3 codee.py launch {root} --business \"{workspace['business']}\" --write --force",
            f"python3 codee.py codeecpa {root} --business \"{workspace['business']}\" --write --force",
            f"python3 codee.py doctor {root}",
            f"python3 codee.py portal {root} --service {workspace['service']}",
        ],
    }


def _launch_markdown(packet: dict[str, Any]) -> str:
    lines = [
        "# Codee Public Launch Packet",
        "",
        f"Generated: {packet.get('created_at')}",
        f"Version: {packet.get('version')}",
        "",
        "## Rule",
        "",
        "Codee can teach, preview, prove, activate after payment, and deliver through a returnable room. Hosted deploy, payments, external posting, and professional legal/tax conclusions stay gated.",
        "",
        "## One Through Twenty",
        "",
    ]
    for index, item in enumerate(packet.get("moves") or [], start=1):
        lines.append(f"{index}. {item.get('title')} - {item.get('status')} - proof: {item.get('proof')}")
    lines.extend(["", "## Acceptance", ""])
    lines.extend(f"- {item}" for item in packet.get("acceptance") or [])
    lines.extend(["", "## Next Commands", ""])
    lines.extend(f"```bash\n{item}\n```" for item in packet.get("next_commands") or [])
    return "\n".join(lines) + "\n"


def _lane_demo_scripts_markdown() -> str:
    lanes = [
        ("QRCodee", "One URL becomes a branded QR image, proof scan, and hosted delivery room."),
        ("CodeeFlyer100", "One image and one CTA become a hosted flyer with QR proof."),
        ("CodeeFlyer250", "Logo, event description, and CTA choices become a stronger flyer request packet."),
        ("CodeeApp250", "A guidebook becomes a no-scroll app-style page with checkout or download path."),
        ("CodeeCard", "A person or brand gets a profile card with booking, message, and proof path."),
        ("Codee Business Suite", "The smaller lanes combine into one business package and support room."),
    ]
    lines = ["# Codee Lane Demo Video Scripts", "", "Use 10 to 20 seconds per demo. Show the folder, preview, payment gate, delivery room, and proof.", ""]
    for name, copy in lanes:
        lines.extend([f"## {name}", "", "Visual: folder, live preview, QR or product output, delivery room.", f"Voiceover: {copy}", "CTA: Start with one lane at codee.chat.", ""])
    return "\n".join(lines)


def _veteran_access_rules_markdown() -> str:
    return """# Veteran Access Rules

Operational draft. Keep this simple and respectful.

## Free/Sponsored Path

- Homeless and disabled veterans get first access to open-source course training.
- Sponsored hosting or done-for-you services require owner-approved or sponsor-approved proof.
- Do not ask for unnecessary private medical, benefit, tax, or housing documents in public forms.
- Use large text, short lessons, simple buttons, and clear next steps.

## Paid Public Path

- Public customers pay for done-for-you services, hosting, support, or Business Suite.
- Paid public work helps fund operations and mission capacity.
- Do not promise income, housing, benefits, approvals, or guaranteed business outcomes.
"""


def _policy_review_markdown() -> str:
    return """# Codee Policy Review Queue

Operational draft for attorney, CPA, and owner review.

## Policies To Review

- Terms of service.
- Privacy policy.
- Refund and cancellation policy.
- Acceptable use policy.
- Support scope and response windows.
- Remote viewer and remote CLI consent rules.
- Stripe/Klarna/payment disclosure language.
- Earnings-claim and business-opportunity claim controls.
- Veteran free/sponsored access rules.
- Nonprofit/company separation language.
"""


def _case_study_slots_markdown() -> str:
    lines = ["# Codee Case Study Slots", "", "Create ten proof-backed case studies before investor/sponsor outreach.", ""]
    for index in range(1, 11):
        lines.extend([f"## Case Study {index}", "", "- Client/demo:", "- Service lane:", "- Problem:", "- Assets received:", "- What Codee generated:", "- Delivery room:", "- Payment or sponsor path:", "- Proof scan:", "- Result:", "- Mission connection:", ""])
    return "\n".join(lines)


def _weekly_proof_report_markdown() -> str:
    return f"""# Codee Weekly Proof Report

Week of: ______

## Platform Proof

- Route-loop result:
- CLI doctor result:
- Public launch page: {CODEE_LAUNCH_URL}
- Proof wall: {CODEE_PROOF_WALL_URL}
- Latest release: {CODEE_RELEASE_URL}

## Business Proof

- Paid conversions:
- MRR:
- One-time service revenue:
- Active hosting/support customers:
- Refund count:
- Average delivery time:

## Mission Proof

- Veteran trainees served:
- Free/sponsored services delivered:
- Mission dollars allocated:
- Sponsor or housing conversations:

## Next Week

- Post more:
- Fix:
- Build:
"""


def _valuation_metrics_template() -> dict[str, Any]:
    return {
        "schema": "codee.valuation-metrics.v1",
        "version": VERSION,
        "updated_at": _now(),
        "metrics": {
            "mrr": None,
            "one_time_revenue": None,
            "paid_conversions": None,
            "active_users": None,
            "active_hosted_workspaces": None,
            "repeat_purchase_rate": None,
            "refund_rate": None,
            "average_delivery_time_hours": None,
            "support_minutes_per_client": None,
            "route_scan_pass_rate": None,
            "gross_margin_estimate": None,
            "customer_acquisition_cost": None,
            "retention_30_day": None,
            "veteran_trainees_served": None,
            "mission_dollars_allocated": None,
        },
        "rule": "Do not use estimates as investor or fundraising proof unless they are labeled and reconciled.",
    }


def command_launch(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    packet = _launch_packet(root, args)
    writes: dict[str, bool] = {}
    if args.write:
        launch_dir = root / ".codee" / "launch"
        launch_dir.mkdir(parents=True, exist_ok=True)
        workspace = packet["workspace"]
        workspace_manifest = {
            "schema": "codee.launch-workspace.v1",
            "version": VERSION,
            "created_at": _now(),
            "business": workspace["business"],
            "owner": workspace["owner"],
            "owner_email": workspace["email"],
            "client_id": workspace["workspace_id"],
            "workspace_id": workspace["workspace_id"],
            "codee_user_id": workspace["codee_user_id"],
            "service": workspace["service"],
            "portal_url": workspace["portal_url"],
            "delivery_room_url": workspace["delivery_room_url"],
        }
        routes = [
            {"name": "launch", "url": CODEE_LAUNCH_URL, "expected": [200]},
            {"name": "launch-checklist", "url": CODEE_LAUNCH_CHECKLIST_URL, "expected": [200]},
            {"name": "onboarding", "url": CODEE_ONBOARDING_URL, "expected": [200]},
            {"name": "portal", "url": CODEE_PORTAL_URL, "expected": [200]},
            {"name": "proof-wall", "url": CODEE_PROOF_WALL_URL, "expected": [200]},
            {"name": "codeecpa", "url": CODEE_CPA_URL, "expected": [200]},
            {"name": "codeecpa-workspace", "url": CODEE_CPA_WORKSPACE_URL, "expected": [200]},
        ]
        writes = {
            "workspace_manifest": _write_json(root / ".codee" / "codee.json", workspace_manifest, force=args.force),
            "workspace_state": bool(_write_state(root, {"business": workspace["business"], "owner_email": workspace["email"], "client_id": workspace["workspace_id"], "codee_user_id": workspace["codee_user_id"], "service": workspace["service"], "updated_at": _now()})),
            "workspace_routes": _write_json(root / ".codee" / "routes.json", routes, force=args.force),
            "launch_json": _write_json(launch_dir / "public-launch-plan.json", packet, force=args.force),
            "launch_md": _write_text(launch_dir / "PUBLIC_LAUNCH_20.md", _launch_markdown(packet), force=args.force),
            "lane_demo_scripts": _write_text(launch_dir / "LANE_DEMO_SCRIPTS.md", _lane_demo_scripts_markdown(), force=args.force),
            "veteran_access_rules": _write_text(launch_dir / "VETERAN_ACCESS_RULES.md", _veteran_access_rules_markdown(), force=args.force),
            "policy_review": _write_text(launch_dir / "POLICY_REVIEW_QUEUE.md", _policy_review_markdown(), force=args.force),
            "case_study_slots": _write_text(launch_dir / "CASE_STUDY_SLOTS.md", _case_study_slots_markdown(), force=args.force),
            "weekly_proof_report": _write_text(launch_dir / "WEEKLY_PROOF_REPORT.md", _weekly_proof_report_markdown(), force=args.force),
            "valuation_metrics": _write_json(launch_dir / "valuation-metrics.json", _valuation_metrics_template(), force=args.force),
            "saas_manifest": _write_json(root / ".codee" / "saas-manifest.json", CODEE_SAAS_MANIFEST, force=args.force),
        }
        _append_event(root, "PublicLaunchConfigured", {"wrote": any(writes.values()), "moves": len(CODEE_PUBLIC_LAUNCH_20_MOVES), "business": workspace["business"]})
    if args.json:
        print(json.dumps(packet | {"writes": writes}, indent=2))
    else:
        print("Codee public launch packet")
        print(f"version={VERSION}")
        print(f"launch_page={CODEE_LAUNCH_URL}")
        print(f"launch_checklist={CODEE_LAUNCH_CHECKLIST_URL}")
        print(f"onboarding={CODEE_ONBOARDING_URL}")
        print(f"moves={len(CODEE_PUBLIC_LAUNCH_20_MOVES)}")
        if args.write:
            for name, wrote in writes.items():
                print(f"{name}: {'written' if wrote else 'exists'}")
    return 0


def command_saas(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = dict(CODEE_SAAS_MANIFEST)
    if args.write:
        _write_json(root / ".codee" / "saas-manifest.json", payload, force=args.force)
        _write_json(root / ".codee" / "entitlements.json", CODEE_SAAS_ENTITLEMENTS, force=args.force)
        _write_text(
            root / ".codee" / "SAAS.md",
            "\n".join(
                [
                    "# Codee Light SaaS",
                    "",
                    payload["positioning"],
                    "",
                    "## Public Pages",
                    "",
                    f"- SaaS: {CODEE_SAAS_URL}",
                    f"- Public launch: {CODEE_LAUNCH_URL}",
                    f"- Onboarding: {CODEE_ONBOARDING_URL}",
                    f"- Portal: {CODEE_PORTAL_URL}",
                    f"- Proof wall: {CODEE_PROOF_WALL_URL}",
                    f"- CODEECPA: {CODEE_CPA_URL}",
                    f"- Manifest: {CODEE_SAAS_MANIFEST_URL}",
                    "",
                    "## Core Loop",
                    "",
                    *[f"- {item}" for item in payload["core_loop"]],
                    "",
                    "## Proof Rule",
                    "",
                    "A workspace is not launch-ready until it has identity, entitlement, route proof, delivery room, and support path saved.",
                    "",
                ]
            ),
            force=args.force,
        )
        _append_event(root, "SaasManifestConfigured", {"version": VERSION, "moves": len(CODEE_LIGHT_SAAS_20_MOVES)})
    if args.json:
        print(json.dumps(payload, indent=2))
    else:
        print("Codee light SaaS")
        print(f"version={VERSION}")
        print(f"public_page={CODEE_SAAS_URL}")
        print(f"portal={CODEE_PORTAL_URL}")
        print(f"proof_wall={CODEE_PROOF_WALL_URL}")
        print("moves:")
        for item in CODEE_LIGHT_SAAS_20_MOVES:
            print(f"- {item['id']}: {item['status']} ({item['proof']})")
        if args.write:
            print(f"manifest={root / '.codee' / 'saas-manifest.json'}")
    return 0


def command_entitlements(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    plan = str(args.plan or "").strip()
    payload = CODEE_SAAS_ENTITLEMENTS
    selected = payload.get(plan) if plan else None
    output: dict[str, Any] = {
        "ok": True,
        "schema": "codee.entitlements.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "plan": plan,
        "selected": selected,
        "entitlements": payload,
        "rule": "Entitlements explain what a user can access; Stripe or sponsored proof still controls paid activation.",
    }
    if args.write:
        _write_json(root / ".codee" / "entitlements.json", output, force=args.force)
        _append_event(root, "EntitlementsConfigured", {"plan": plan or "all"})
    if args.json:
        print(json.dumps(output, indent=2))
    else:
        if selected:
            print(f"Codee entitlement: {plan}")
            print(f"name={selected['name']}")
            print(f"billing={selected['billing']}")
            for item in selected.get("unlocks") or []:
                print(f"- unlocks: {item}")
            for item in selected.get("limits") or []:
                print(f"- limit: {item}")
        else:
            print("Codee entitlements")
            for key, item in payload.items():
                print(f"- {key}: {item['name']} | {item['billing']}")
        if args.write:
            print(f"entitlements={root / '.codee' / 'entitlements.json'}")
    return 0


def command_portal(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _load_manifest(root)
    service = str(args.service or "codee-support").strip()
    plan = str(args.plan or "").strip()
    url = str(args.url or "").strip() or _portal_url(manifest, service=service, plan=plan)
    payload = {
        "ok": True,
        "schema": "codee.portal.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "workspace_id": str(manifest.get("client_id") or root.name),
        "codee_user_id": str(manifest.get("codee_user_id") or ""),
        "business": str(manifest.get("business") or ""),
        "service": service,
        "plan": plan,
        "portal_url": url,
        "delivery_room_url": _delivery_room_url(manifest, service=service),
        "workbench_url": _workbench_url(manifest, service=service),
        "proof_wall_url": CODEE_PROOF_WALL_URL,
    }
    report_path = _write_report(root, "latest-portal.json", payload)
    if args.json:
        print(json.dumps(payload | {"report": str(report_path)}, indent=2))
    else:
        print(f"Codee portal: {url}")
        print(f"delivery_room={payload['delivery_room_url']}")
        print(f"workbench={payload['workbench_url']}")
        print(f"report={report_path}")
    if args.open:
        webbrowser.open(url)
    return 0


def _course_by_id(course_id: str) -> dict[str, Any]:
    for course in COURSE_CATALOG.get("core", []):
        if str(course.get("id") or "") == course_id:
            return dict(course)
    return dict(COURSE_CATALOG["core"][0])


def command_starter(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    preset = str(args.preset or "qrcodee").strip()
    pack = dict(CODEE_STARTER_PACKS.get(preset) or CODEE_STARTER_PACKS["qrcodee"])
    service = str(args.service or pack["service"]).strip()
    course = _course_by_id(str(pack["course"]))
    business = str(args.business or "My Business").strip()
    owner = str(args.owner or "Business Owner").strip()
    email = str(args.email or "").strip().lower()
    target_url = str(args.target_url or "https://codee.chat").strip()
    client_id = str(args.client_id or _slugify(business)).strip()
    codee_user_id = _codee_user_id(email, f"{owner}:{business}:{client_id}")
    root.mkdir(parents=True, exist_ok=True)
    manifest = {
        "schema": "codee.light-saas.workspace.v1",
        "version": VERSION,
        "created_at": _now(),
        "business": business,
        "owner": owner,
        "owner_email": email,
        "client_id": client_id,
        "workspace_id": client_id,
        "codee_user_id": codee_user_id,
        "preset": preset,
        "service": service,
        "business_type": pack.get("business_type"),
        "portal_url": _portal_url({"client_id": client_id, "codee_user_id": codee_user_id, "business": business}, service=service, plan=args.plan),
        "delivery_room_url": _delivery_room_url({"client_id": client_id, "codee_user_id": codee_user_id, "business": business}, service=service),
        "workbench_url": _workbench_url({"client_id": client_id, "codee_user_id": codee_user_id, "business": business}, service=service),
        "target_url": target_url,
    }
    writes = {
        root / "index.html": _course_starter_html(course, business=business, target_url=target_url),
        root / "CODEE.md": "\n".join([
            "# Codee Starter Workspace",
            "",
            f"Business: {business}",
            f"Owner: {owner}",
            f"Service: {service}",
            f"Codee User ID: {codee_user_id}",
            "",
            "This folder is the business surface: `index.html`, `assets/`, and `.codee/` proof files.",
            "Run `python3 codee.py test lane . --service SERVICE --route-check` before launch.",
            "",
        ]),
        root / ".codee" / "STARTER.md": "\n".join([
            "# Starter Next Steps",
            "",
            f"1. Open `{root / 'index.html'}` locally and confirm the first page reads correctly.",
            f"2. Run `python3 codee.py entitlements . --plan {args.plan or 'free-trainee'} --write --force`.",
            f"3. Run `python3 codee.py portal . --service {service}`.",
            f"4. Run `python3 codee.py test lane . --service {service} --target-url {target_url} --route-check`.",
            "5. Use `codee preview` or `codee activate` only when the user wants hosted delivery.",
            "",
        ]),
    }
    written = []
    skipped = []
    for path, text in writes.items():
        if _write_text(path, text, force=args.force):
            written.append(str(path))
        else:
            skipped.append(str(path))
    json_writes = {
        root / ".codee" / "codee.json": manifest,
        root / ".codee" / "starter.json": {"ok": True, "preset": preset, "pack": pack, "course": course, "service": service},
        root / ".codee" / "saas-manifest.json": CODEE_SAAS_MANIFEST,
        root / ".codee" / "entitlements.json": CODEE_SAAS_ENTITLEMENTS,
        root / ".codee" / "tool-registry.json": CODEE_TOOL_REGISTRY,
        root / ".codee" / "release.json": CODEE_RELEASE_DISCIPLINE,
        root / ".codee" / "service-contract.json": CODEE_SERVICE_CONTRACTS.get(_normalize_service(service), {}),
        root / ".codee" / "routes.json": [{"name": "target", "url": target_url, "expected": [200, 301, 302, 307, 308]}],
    }
    for path, payload in json_writes.items():
        if _write_json(path, payload, force=args.force):
            written.append(str(path))
        else:
            skipped.append(str(path))
    _write_state(root, {"business": business, "owner_email": email, "client_id": client_id, "codee_user_id": codee_user_id, "service": service, "preset": preset, "updated_at": _now()})
    _append_event(root, "StarterWorkspaceCreated", {"preset": preset, "service": service, "client_id": client_id})
    report = {
        "ok": True,
        "schema": "codee.starter.v1",
        "created_at": _now(),
        "manifest": manifest,
        "written": written,
        "skipped": skipped,
        "next_commands": [
            f"python3 codee.py portal {root} --service {service}",
            f"python3 codee.py entitlements {root} --plan {args.plan or 'free-trainee'} --write --force",
            f"python3 codee.py test lane {root} --service {service} --target-url {target_url} --route-check",
            f"python3 codee.py preview {root} --service {service} --business \"{business}\" --email {email or 'owner@example.com'} --target-url {target_url} --dry-run",
        ],
    }
    report_path = _write_report(root, "latest-starter.json", report)
    if args.json:
        print(json.dumps(report | {"report": str(report_path)}, indent=2))
    else:
        print(f"Codee starter: ok=True preset={preset} service={service}")
        print(f"workspace={root}")
        print(f"portal={manifest['portal_url']}")
        print(f"delivery_room={manifest['delivery_room_url']}")
        print(f"report={report_path}")
    return 0


def command_remote(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    action = str(args.remote_action or "").strip()
    manifest = _load_manifest(root)
    root.mkdir(parents=True, exist_ok=True)
    if action == "plan":
        payload = dict(CODEE_REMOTE_ARCHITECTURE)
        payload["workspace"] = {
            "root": str(root),
            "business": str(manifest.get("business") or ""),
            "workspace_id": str(manifest.get("client_id") or root.name),
            "codee_user_id": str(manifest.get("codee_user_id") or ""),
            "portal_url": _portal_url(manifest, service=str(args.service or "codee-remote"), plan="pro"),
        }
        if args.write:
            _write_json(root / ".codee" / "remote-plan.json", payload, force=args.force)
            _write_text(
                root / ".codee" / "REMOTE.md",
                "\n".join(
                    [
                        "# Codee Remote Plan",
                        "",
                        payload["positioning"],
                        "",
                        "## Safe Build Order",
                        "",
                        "1. Remote Viewer: phone pairs to the user's own desktop and receives a consent-based screen stream.",
                        "2. Remote CLI Bridge: phone sends allowlisted Codee commands to the paired desktop agent.",
                        "3. Full desktop remote: pro-only native host with MFA, revocation, audit logs, and emergency lock.",
                        "",
                        "## Why not full desktop first?",
                        "",
                        "Remote desktop is security-sensitive. Codee should prove identity, pairing, consent, audit trail, and emergency stop before shipping unattended control.",
                        "",
                        f"Viewer page: {CODEE_REMOTE_VIEWER_URL}",
                        f"CLI bridge page: {CODEE_REMOTE_CLI_URL}",
                    ]
                ),
                force=args.force,
            )
            _append_event(root, "RemotePlanConfigured", {"phase": "viewer-and-cli-bridge"})
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            print("Codee Remote plan")
            print(f"page={CODEE_REMOTE_URL}")
            print(f"viewer={CODEE_REMOTE_VIEWER_URL}")
            print(f"cli_bridge={CODEE_REMOTE_CLI_URL}")
            print("first_phase=desktop-viewer-mvp")
            print("parallel_phase=remote-cli-bridge")
            if args.write:
                print(f"plan={root / '.codee' / 'remote-plan.json'}")
        return 0

    if action == "viewer":
        payload = {
            "ok": True,
            "schema": "codee.remote-viewer.v1",
            "created_at": _now(),
            "workspace": str(root),
            "viewer_page": CODEE_REMOTE_VIEWER_URL,
            "portal_url": _portal_url(manifest, service=str(args.service or "codee-remote"), plan="pro"),
            "mode": "phone-to-desktop-viewer",
            "capabilities": CODEE_REMOTE_ARCHITECTURE["viewer_capabilities"],
            "required_backend": ["signaling endpoint", "device registry", "session store", "TURN relay", "audit events"],
            "security_rules": [
                "Session must show a visible banner on the desktop.",
                "Device owner can stop sharing immediately.",
                "Pairing code expires before any screen stream starts.",
                "Input control stays disabled until explicitly approved.",
            ],
        }
        if args.write:
            _write_json(root / ".codee" / "remote-viewer.json", payload, force=args.force)
            _write_text(
                root / ".codee" / "REMOTE_VIEWER.md",
                "\n".join(
                    [
                        "# Codee Remote Viewer",
                        "",
                        "Goal: let a pro user see and control their own desktop from a phone with clear consent and revocation.",
                        "",
                        f"Viewer page: {CODEE_REMOTE_VIEWER_URL}",
                        "",
                        "Launch order:",
                        "1. Pair desktop host.",
                        "2. Open phone viewer.",
                        "3. Require visible consent on the desktop.",
                        "4. Start screen stream.",
                        "5. Enable touch/mouse input only after approval.",
                        "6. Save audit event and session proof.",
                        "",
                    ]
                ),
                force=args.force,
            )
            _append_event(root, "RemoteViewerConfigured", {"mode": "phone-to-desktop-viewer"})
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            print("Codee Remote Viewer")
            print(f"viewer={payload['viewer_page']}")
            print(f"portal={payload['portal_url']}")
            print("status=foundation-plan")
            if args.write:
                print(f"viewer_plan={root / '.codee' / 'remote-viewer.json'}")
        return 0

    if action == "bridge":
        payload = {
            "ok": True,
            "schema": "codee.remote-cli-bridge.v1",
            "created_at": _now(),
            "workspace": str(root),
            "bridge_page": CODEE_REMOTE_CLI_URL,
            "portal_url": _portal_url(manifest, service=str(args.service or "codee-remote"), plan="pro"),
            "mode": "allowlisted-command-bridge",
            "allowed_commands": CODEE_REMOTE_ARCHITECTURE["cli_bridge_capabilities"],
            "blocked_actions": ["unapproved shell", "secret export", "raw deploy credentials", "destructive cleanup", "background host without consent"],
            "audit_events": ["RemoteCommandQueued", "RemoteCommandStarted", "RemoteCommandCompleted", "RemoteCommandRejected"],
        }
        if args.write:
            _write_json(root / ".codee" / "remote-cli-bridge.json", payload, force=args.force)
            _write_text(
                root / ".codee" / "REMOTE_CLI_BRIDGE.md",
                "\n".join(
                    [
                        "# Codee Remote CLI Bridge",
                        "",
                        "Goal: let a phone send safe Codee commands to the paired desktop without opening full screen control.",
                        "",
                        f"Bridge page: {CODEE_REMOTE_CLI_URL}",
                        "",
                        "Allowed commands:",
                        *[f"- {cmd}" for cmd in payload["allowed_commands"]],
                        "",
                    ]
                ),
                force=args.force,
            )
            _append_event(root, "RemoteCliBridgeConfigured", {"allowed_commands": payload["allowed_commands"]})
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            print("Codee Remote CLI Bridge")
            print(f"bridge={payload['bridge_page']}")
            print(f"allowed_commands={','.join(payload['allowed_commands'])}")
            print("status=foundation-plan")
            if args.write:
                print(f"bridge_plan={root / '.codee' / 'remote-cli-bridge.json'}")
        return 0

    if action == "installer":
        payload = {
            "ok": True,
            "schema": "codee.remote-installer.v1",
            "created_at": _now(),
            "workspace": str(root),
            "installer_page": CODEE_REMOTE_INSTALLER_URL,
            "host_download_url": CODEE_REMOTE_HOST_DOWNLOAD_URL,
            "viewer_page": CODEE_REMOTE_VIEWER_URL,
            "cli_bridge_page": CODEE_REMOTE_CLI_URL,
            "install_steps": [
                "Download codee-remote-host.py from clients.codee.chat.",
                "Run `python3 codee-remote-host.py install . --write` inside the Codee workspace.",
                "Run `python3 codee.py remote pair . --write` to create a short-lived pairing packet.",
                "Run `python3 codee.py remote readiness . --write` before enabling pro viewer access.",
            ],
            "security_note": "The host skeleton does not ship owner credentials and does not start screen streaming by itself.",
        }
        if args.write:
            _write_json(root / ".codee" / "remote-installer.json", payload, force=args.force)
            _write_text(
                root / ".codee" / "REMOTE_INSTALLER.md",
                "\n".join(
                    [
                        "# Codee Remote Installer",
                        "",
                        f"Installer page: {CODEE_REMOTE_INSTALLER_URL}",
                        f"Host download: {CODEE_REMOTE_HOST_DOWNLOAD_URL}",
                        "",
                        "Commands:",
                        "curl -L https://clients.codee.chat/assets/downloads/codee-remote-host.py -o codee-remote-host.py",
                        "python3 codee-remote-host.py install . --write",
                        "python3 codee.py remote pair . --write",
                        "python3 codee.py remote readiness . --write",
                        "",
                    ]
                ),
                force=args.force,
            )
            _append_event(root, "RemoteInstallerConfigured", {"host_download_url": CODEE_REMOTE_HOST_DOWNLOAD_URL})
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            print("Codee Remote installer")
            print(f"installer={payload['installer_page']}")
            print(f"host_download={payload['host_download_url']}")
            if args.write:
                print(f"installer_plan={root / '.codee' / 'remote-installer.json'}")
        return 0

    if action == "host":
        default_device_name = os.uname().nodename if hasattr(os, "uname") else "Codee Desktop"
        device_name = str(args.device_name or default_device_name or "Codee Desktop").strip()
        payload = {
            "ok": True,
            "schema": "codee.remote-host.v1",
            "created_at": _now(),
            "workspace": str(root),
            "device_name": device_name,
            "host_download_url": CODEE_REMOTE_HOST_DOWNLOAD_URL,
            "host_state_path": ".codee/remote-host/host-state.json",
            "queue_path": ".codee/remote-host/command-queue.json",
            "allowlisted_commands": CODEE_REMOTE_ARCHITECTURE["cli_bridge_capabilities"],
            "blocked_actions": ["raw shell", "secret export", "destructive commands", "silent screen streaming", "owner credential access"],
            "desktop_viewer": {
                "status": "planned",
                "requires": ["visible consent banner", "WebRTC signaling", "TURN relay", "session revoke", "MFA/passkey"],
            },
        }
        if args.write:
            _write_json(root / ".codee" / "remote-host.json", payload, force=args.force)
            _write_json(
                root / ".codee" / "remote-host" / "host-state.json",
                {
                    "schema": "codee.remote-host-state.v1",
                    "created_at": _now(),
                    "device_name": device_name,
                    "status": "installed-foundation",
                    "screen_streaming": "disabled_until_viewer_security_gate_passes",
                    "cli_bridge": "ready_for_allowlisted_queue",
                },
                force=True,
            )
            _write_json(
                root / ".codee" / "remote-host" / "command-queue.json",
                {"schema": "codee.remote-command-queue.v1", "commands": []},
                force=args.force,
            )
            _append_event(root, "RemoteHostConfigured", {"device_name": device_name})
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            print("Codee Remote host skeleton")
            print(f"device_name={device_name}")
            print(f"host_download={CODEE_REMOTE_HOST_DOWNLOAD_URL}")
            print("status=installed-foundation")
            if args.write:
                print(f"host_profile={root / '.codee' / 'remote-host.json'}")
        return 0

    if action == "pair":
        default_device_name = os.uname().nodename if hasattr(os, "uname") else "Codee Desktop"
        device_name = str(args.device_name or default_device_name or "Codee Desktop").strip()
        seed = f"{root}:{device_name}:{time.time_ns()}"
        pairing_code = hashlib.sha256(seed.encode("utf-8")).hexdigest()[:10].upper()
        device_id = "cdev_" + hashlib.sha256(f"{device_name}:{root}".encode("utf-8")).hexdigest()[:16]
        expires_at = (dt.datetime.now(dt.timezone.utc) + dt.timedelta(minutes=int(args.expires_minutes))).isoformat()
        payload = {
            "ok": True,
            "schema": "codee.remote-device.v1",
            "created_at": _now(),
            "expires_at": expires_at,
            "device_id": device_id,
            "device_name": device_name,
            "pairing_code": pairing_code,
            "workspace_id": str(manifest.get("client_id") or root.name),
            "codee_user_id": str(manifest.get("codee_user_id") or ""),
            "remote_mode": "viewer-and-cli-bridge-foundation",
            "viewer_page": CODEE_REMOTE_VIEWER_URL,
            "cli_bridge_page": CODEE_REMOTE_CLI_URL,
            "portal_url": _portal_url(manifest, service=str(args.service or "codee-remote"), plan="pro"),
            "security_note": "This only creates a pairing packet. It does not open remote desktop access, stream the screen, or run a background host.",
        }
        if args.write:
            _write_json(root / ".codee" / "remote-device.json", payload, force=True)
            _append_event(root, "RemotePairingCreated", {"device_id": device_id, "expires_at": expires_at})
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            print("Codee Remote pairing packet")
            print(f"device_id={device_id}")
            print(f"pairing_code={pairing_code}")
            print(f"expires_at={expires_at}")
            print("status=packet-only")
        return 0

    if action == "session":
        session_action = str(args.session_action or "status").strip().lower()
        device = _read_json_if_exists(root / ".codee" / "remote-device.json")
        session_path = root / ".codee" / "remote-session.json"
        current = _read_json_if_exists(session_path)
        session_id = str(current.get("session_id") or ("crs_" + hashlib.sha256(f"{root}:{time.time_ns()}".encode("utf-8")).hexdigest()[:16]))
        payload = {
            "ok": True,
            "schema": "codee.remote-session.v1",
            "created_at": _now(),
            "session_id": session_id,
            "action": session_action,
            "device_id": str(device.get("device_id") or ""),
            "workspace_id": str(manifest.get("client_id") or root.name),
            "viewer_page": CODEE_REMOTE_VIEWER_URL,
            "cli_bridge_page": CODEE_REMOTE_CLI_URL,
            "status": "pending-host" if session_action == "start" else ("stopped" if session_action == "stop" else str(current.get("status") or "not_started")),
            "screen_streaming": "not_started_without_desktop_host_and_consent",
            "emergency_stop": True,
        }
        if args.write or session_action in {"start", "stop"}:
            _write_json(session_path, payload, force=True)
            _append_event(root, "RemoteSessionUpdated", {"session_id": session_id, "action": session_action, "status": payload["status"]})
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            print("Codee Remote session")
            print(f"session_id={session_id}")
            print(f"action={session_action}")
            print(f"status={payload['status']}")
            print(f"viewer={CODEE_REMOTE_VIEWER_URL}")
        return 0

    if action == "revoke":
        device = _read_json_if_exists(root / ".codee" / "remote-device.json")
        payload = {
            "ok": True,
            "schema": "codee.remote-revoke.v1",
            "created_at": _now(),
            "device_id": str(args.device_id or device.get("device_id") or "").strip(),
            "revoked": True,
            "reason": str(args.reason or "owner requested revoke").strip(),
            "effect": "Local pairing packet is marked revoked. Backend/device registry revoke must also run before active remote access.",
        }
        if args.write:
            _write_json(root / ".codee" / "remote-revocation.json", payload, force=True)
            _append_event(root, "RemoteDeviceRevoked", {"device_id": payload["device_id"], "reason": payload["reason"]})
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            print("Codee Remote revoke")
            print(f"device_id={payload['device_id']}")
            print("revoked=True")
            if args.write:
                print(f"revocation={root / '.codee' / 'remote-revocation.json'}")
        return 0

    if action == "security":
        payload = {
            "ok": True,
            "schema": "codee.remote-security-gate.v1",
            "created_at": _now(),
            "security_page": CODEE_REMOTE_SECURITY_URL,
            "required_before_public_active": CODEE_REMOTE_SECURITY_GATE,
            "current_release_position": "foundation-live, screen streaming disabled until host/WebRTC/TURN/MFA gate passes",
            "blocked_until_complete": ["unattended desktop control", "silent screen capture", "raw remote shell", "secret export"],
        }
        if args.write:
            _write_json(root / ".codee" / "remote-security-gate.json", payload, force=args.force)
            _write_text(
                root / ".codee" / "REMOTE_SECURITY.md",
                "\n".join(["# Codee Remote Security Gate", "", *[f"- {item}" for item in CODEE_REMOTE_SECURITY_GATE], ""]),
                force=args.force,
            )
            _append_event(root, "RemoteSecurityGateConfigured", {"checks": len(CODEE_REMOTE_SECURITY_GATE)})
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            print("Codee Remote security gate")
            print(f"security_page={CODEE_REMOTE_SECURITY_URL}")
            print(f"required_checks={len(CODEE_REMOTE_SECURITY_GATE)}")
            if args.write:
                print(f"security_gate={root / '.codee' / 'remote-security-gate.json'}")
        return 0

    if action == "demo":
        payload = {
            "ok": True,
            "schema": "codee.remote-demo.v1",
            "created_at": _now(),
            "demo_page": CODEE_REMOTE_DEMO_URL,
            "purpose": "Public demo mode explains the remote viewer and CLI bridge without opening a real desktop session.",
            "states": ["phone waiting", "desktop paired", "consent required", "viewer connected", "CLI command queued", "session stopped"],
        }
        if args.write:
            _write_json(root / ".codee" / "remote-demo.json", payload, force=args.force)
            _append_event(root, "RemoteDemoConfigured", {"demo_page": CODEE_REMOTE_DEMO_URL})
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            print("Codee Remote demo mode")
            print(f"demo={CODEE_REMOTE_DEMO_URL}")
            if args.write:
                print(f"demo_packet={root / '.codee' / 'remote-demo.json'}")
        return 0

    if action == "audit":
        event_path = root / ".codee" / "events.jsonl"
        remote_events: list[dict[str, Any]] = []
        if event_path.exists():
            for line in event_path.read_text(encoding="utf-8", errors="replace").splitlines()[-200:]:
                try:
                    item = json.loads(line)
                except Exception:
                    continue
                if str(item.get("event") or "").startswith("Remote"):
                    remote_events.append(item)
        files = [
            "remote-plan.json",
            "remote-viewer.json",
            "remote-cli-bridge.json",
            "remote-installer.json",
            "remote-host.json",
            "remote-device.json",
            "remote-session.json",
            "remote-security-gate.json",
            "remote-demo.json",
            "remote-revocation.json",
        ]
        payload = {
            "ok": True,
            "schema": "codee.remote-audit.v1",
            "created_at": _now(),
            "remote_event_count": len(remote_events),
            "latest_events": remote_events[-10:],
            "files": {name: (root / ".codee" / name).exists() for name in files},
        }
        report_path = _write_report(root, "latest-remote-audit.json", payload)
        if args.json:
            print(json.dumps(payload | {"report": str(report_path)}, indent=2))
        else:
            print("Codee Remote audit")
            print(f"remote_events={len(remote_events)}")
            print(f"report={report_path}")
        return 0

    if action == "readiness":
        required_files = {
            "plan": root / ".codee" / "remote-plan.json",
            "viewer": root / ".codee" / "remote-viewer.json",
            "bridge": root / ".codee" / "remote-cli-bridge.json",
            "installer": root / ".codee" / "remote-installer.json",
            "host": root / ".codee" / "remote-host.json",
            "device": root / ".codee" / "remote-device.json",
            "security": root / ".codee" / "remote-security-gate.json",
            "demo": root / ".codee" / "remote-demo.json",
        }
        file_checks = {name: path.exists() for name, path in required_files.items()}
        route_targets = [
            {"name": "remote-hub", "url": CODEE_REMOTE_URL, "expected": [200]},
            {"name": "remote-viewer", "url": CODEE_REMOTE_VIEWER_URL, "expected": [200]},
            {"name": "remote-cli", "url": CODEE_REMOTE_CLI_URL, "expected": [200]},
            {"name": "remote-installer", "url": CODEE_REMOTE_INSTALLER_URL, "expected": [200]},
            {"name": "remote-demo", "url": CODEE_REMOTE_DEMO_URL, "expected": [200]},
            {"name": "remote-security", "url": CODEE_REMOTE_SECURITY_URL, "expected": [200]},
            {"name": "remote-manifest", "url": CODEE_REMOTE_MANIFEST_URL, "expected": [200]},
            {"name": "remote-host-download", "url": CODEE_REMOTE_HOST_DOWNLOAD_URL, "expected": [200]},
        ]
        route_checks = [] if args.local_only else [_route_check(item, float(args.timeout or 20)) for item in route_targets]
        payload = {
            "ok": all(file_checks.values()) and all(item.get("ok") for item in route_checks),
            "schema": "codee.remote-readiness.v1",
            "created_at": _now(),
            "file_checks": file_checks,
            "route_checks": route_checks,
            "remote_moves": CODEE_REMOTE_20_MOVES,
            "next": [
                "Run remote audit after each pairing/session change.",
                "Do not enable active screen control until the security page and host gate pass.",
                "Use the demo page for public promotion before real WebRTC control is live.",
            ],
        }
        report_path = _write_report(root, "latest-remote-readiness.json", payload)
        if args.write:
            _write_json(root / ".codee" / "remote-readiness.json", payload, force=True)
            _append_event(root, "RemoteReadinessChecked", {"ok": payload["ok"]})
        if args.json:
            print(json.dumps(payload | {"report": str(report_path)}, indent=2))
        else:
            print(f"Codee Remote readiness: ok={payload['ok']}")
            print(f"files_ok={sum(1 for value in file_checks.values() if value)}/{len(file_checks)}")
            print(f"routes_ok={sum(1 for item in route_checks if item.get('ok'))}/{len(route_checks)}")
            print(f"report={report_path}")
        return 0 if payload["ok"] else 1

    if action == "status":
        plan = _read_json_if_exists(root / ".codee" / "remote-plan.json")
        viewer = _read_json_if_exists(root / ".codee" / "remote-viewer.json")
        bridge = _read_json_if_exists(root / ".codee" / "remote-cli-bridge.json")
        installer = _read_json_if_exists(root / ".codee" / "remote-installer.json")
        host = _read_json_if_exists(root / ".codee" / "remote-host.json")
        device = _read_json_if_exists(root / ".codee" / "remote-device.json")
        security = _read_json_if_exists(root / ".codee" / "remote-security-gate.json")
        payload = {
            "ok": True,
            "schema": "codee.remote-status.v1",
            "created_at": _now(),
            "has_plan": bool(plan),
            "has_viewer_plan": bool(viewer),
            "has_cli_bridge_plan": bool(bridge),
            "has_installer_plan": bool(installer),
            "has_host_profile": bool(host),
            "has_device_pairing": bool(device),
            "has_security_gate": bool(security),
            "device_id": device.get("device_id") if device else "",
            "expires_at": device.get("expires_at") if device else "",
            "remote_page": CODEE_REMOTE_URL,
            "viewer_page": CODEE_REMOTE_VIEWER_URL,
            "cli_bridge_page": CODEE_REMOTE_CLI_URL,
            "installer_page": CODEE_REMOTE_INSTALLER_URL,
            "demo_page": CODEE_REMOTE_DEMO_URL,
            "security_page": CODEE_REMOTE_SECURITY_URL,
            "next": [
                "Build Codee desktop host agent with visible consent and stop controls.",
                "Add backend command queue, signaling, and device registry.",
                "Add WebRTC signaling and TURN after pairing and audit pass.",
                "Keep CLI bridge allowlisted until the viewer has MFA/passkey and session revoke.",
            ],
        }
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            print("Codee Remote status")
            print(f"has_plan={payload['has_plan']}")
            print(f"has_viewer_plan={payload['has_viewer_plan']}")
            print(f"has_cli_bridge_plan={payload['has_cli_bridge_plan']}")
            print(f"has_installer_plan={payload['has_installer_plan']}")
            print(f"has_host_profile={payload['has_host_profile']}")
            print(f"has_device_pairing={payload['has_device_pairing']}")
            print(f"has_security_gate={payload['has_security_gate']}")
            print(f"device_id={payload['device_id']}")
            print(f"page={payload['remote_page']}")
        return 0

    print("Unknown remote action. Use `codee remote plan`, `viewer`, `bridge`, `installer`, `host`, `pair`, `session`, `revoke`, `security`, `demo`, `audit`, `readiness`, or `status`.")
    return 2


def command_support(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _load_manifest(root)
    message = str(args.message or "").strip()
    if not message:
        print("A support request needs --message so Codee knows what to update.")
        return 2
    service = str(args.service or "codee-support").strip()
    title = str(args.title or "").strip() or f"{service} update request"
    created_at = _now()
    codee_user_id = str(manifest.get("codee_user_id") or "").strip() or _codee_user_id(args.email, str(manifest.get("client_id") or root.name))
    workspace_id = str(manifest.get("client_id") or root.name)
    request_seed = f"{codee_user_id}:{workspace_id}:{title}:{created_at}"
    request_id = f"csup_{hashlib.sha256(request_seed.encode('utf-8')).hexdigest()[:16]}"
    delivery_room_url = str(args.delivery_room_url or "").strip() or _delivery_room_url(manifest | {"codee_user_id": codee_user_id}, service=service)
    blocked_attachments: list[str] = []
    clean_attachments: list[str] = []
    for item in (args.attachment or []):
        value = str(item).strip()
        if not value:
            continue
        if value.startswith(("http://", "https://")):
            clean_attachments.append(value)
            continue
        candidate = Path(value).expanduser()
        if candidate.exists() and _is_sensitive_path(candidate):
            blocked_attachments.append(value)
        else:
            clean_attachments.append(value)
    if blocked_attachments:
        print("Blocked sensitive support attachment(s). Do not upload secrets, private keys, .env files, or OAuth tokens.")
        for item in blocked_attachments:
            print(f"blocked={item}")
        return 2
    payload = {
        "request_id": request_id,
        "created_at": created_at,
        "cli_version": VERSION,
        "source_surface": "codee-cli",
        "codee_user_id": codee_user_id,
        "user_id": codee_user_id,
        "workspace_id": workspace_id,
        "client_id": workspace_id,
        "account_email": str(args.email or manifest.get("owner_email") or "").strip().lower(),
        "business": str(args.business or manifest.get("business") or ""),
        "owner": str(args.owner or manifest.get("owner") or ""),
        "service": service,
        "request_type": str(args.type or "site-update").strip(),
        "priority": str(args.priority or "normal").strip(),
        "title": title,
        "message": message,
        "route": str(args.route or "").strip(),
        "attachments": clean_attachments,
        "delivery_room_url": delivery_room_url,
        "dry_run": bool(args.dry_run),
    }
    request_dir = root / ".codee" / "support-requests"
    request_dir.mkdir(parents=True, exist_ok=True)
    request_path = request_dir / f"{request_id}.json"
    request_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
    _write_report(root, "latest-support-request.json", payload)

    result: dict[str, Any] = {
        "ok": True,
        "local_only": not bool(args.submit),
        "request_id": request_id,
        "request_path": str(request_path),
        "delivery_room_url": delivery_room_url,
        "message": "Saved local support packet. Use --submit to send it to Codee backend.",
    }
    if args.submit:
        try:
            result = _request_json("POST", _api_url(args.api_base, "/api/stripe/codee-cli/support-request"), payload, timeout=float(args.timeout))
            if args.dry_run and not result.get("ok"):
                result = {"ok": True, "dry_run": True, "request_id": request_id, "remote_error": result, "delivery_room_url": delivery_room_url}
        except Exception as exc:
            if args.dry_run:
                result = {"ok": True, "dry_run": True, "request_id": request_id, "local_error": f"{type(exc).__name__}: {exc}", "delivery_room_url": delivery_room_url}
            else:
                raise
        _write_report(root, "latest-support-submit.json", result | {"request": payload})
    if args.json:
        print(json.dumps(result | {"request": payload}, indent=2))
    else:
        print(f"Codee support request: ok={result.get('ok')} request_id={result.get('request_id') or request_id}")
        print(f"delivery_room={result.get('delivery_room_url') or delivery_room_url}")
        print(f"request={request_path}")
        if result.get("archive_path"):
            print(f"archive={result.get('archive_path')}")
        if result.get("error"):
            print(f"error={result.get('error')}")
    if args.open:
        webbrowser.open(str(result.get("delivery_room_url") or delivery_room_url))
    return 0 if result.get("ok") else 1


def command_courses(args: argparse.Namespace) -> int:
    payload = {
        "ok": True,
        "model": "open-source-course-plus-paid-support",
        "core": COURSE_CATALOG["core"],
        "advanced": COURSE_CATALOG["advanced"],
        "rule": "Teach the lane first. Sell hosting, scans, delivery rooms, and done-for-you support only after the student understands the output.",
        "free_priority": "Homeless and disabled veterans get first access to the practical training path.",
    }
    if args.json:
        print(json.dumps(payload, indent=2))
        return 0

    print("Codee open-source courses")
    print("Core courses:")
    for item in COURSE_CATALOG["core"]:
        print(f"- {item['name']} ({item['id']})")
        print(f"  lesson: {item['lesson']}")
        print(f"  output: {item['student_output']}")
        print(f"  paid path: {item['paid_path']}")
    print("\nAdvanced service courses:")
    for item in COURSE_CATALOG["advanced"]:
        print(f"- {item['name']} ({item['id']})")
        print(f"  why: {item['why']}")
        print(f"  paid path: {item['paid_path']}")
    print("\nRule: teach the lane first, then offer Codee hosting, scans, delivery room, and support.")
    return 0


def command_contracts(args: argparse.Namespace) -> int:
    service = _normalize_service(str(args.service or "").strip()) if args.service else ""
    contracts: dict[str, Any] = CODEE_SERVICE_CONTRACTS
    payload: dict[str, Any] = {
        "ok": True,
        "schema": "codee.service-contracts.v1",
        "updated_at": "2026-05-27",
        "contracts": contracts,
    }
    if service:
        payload = {
            "ok": service in CODEE_SERVICE_CONTRACTS,
            "schema": "codee.service-contracts.v1",
            "updated_at": "2026-05-27",
            "service": service,
            "contract": _service_contract(service),
        }
    if args.write:
        root = Path(args.path).expanduser().resolve()
        name = "service-contract.json" if service else "service-contracts.json"
        _write_json(root / ".codee" / name, payload, force=args.force)
        payload["written_to"] = str(root / ".codee" / name)
    if args.json:
        print(json.dumps(payload, indent=2))
        return 0
    if service:
        contract = payload.get("contract") if isinstance(payload.get("contract"), dict) else {}
        print(f"Codee contract: {contract.get('public_name')} ({contract.get('service')})")
        print(f"promise: {contract.get('promise')}")
        print("client gets:")
        for item in contract.get("client_gets") or []:
            print(f"- {item}")
        print("required inputs:")
        for item in contract.get("required_inputs") or []:
            print(f"- {item}")
        if payload.get("written_to"):
            print(f"written_to={payload['written_to']}")
        return 0 if payload.get("ok") else 1
    print("Codee service contracts")
    for key, contract in contracts.items():
        print(f"- {contract.get('public_name')} ({key}): {contract.get('promise')}")
    if payload.get("written_to"):
        print(f"written_to={payload['written_to']}")
    return 0


def command_course_init(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    course = _course_by_id(args.course)
    course_id = str(course["id"])
    business = str(args.business or "My Business").strip()
    target_url = str(args.target_url or "https://codee.chat").strip()
    _append_event(root, "PreGenerate", {"course_id": course_id, "business": business, "target_url": target_url})
    packet = {
        "course_id": course_id,
        "course_name": course.get("name"),
        "business": business,
        "target_url": target_url,
        "lesson": course.get("lesson") or course.get("why"),
        "student_output": course.get("student_output", ""),
        "paid_path": course.get("paid_path", ""),
        "created_at": _now(),
        "source": "codee-cli-course-init",
    }
    activation_packet = _course_activation_packet(course=course, business=business, target_url=target_url, root=root)
    readme = f"""# {course.get('name')}

Business: {business}

Target route: {target_url}

## Lesson

{course.get('lesson') or course.get('why')}

## Student Output

{course.get('student_output') or 'A hosted-ready course folder with proof files.'}

## Paid Codee Path

{course.get('paid_path')}

## Activation Model

This course creates the local client site first. Payment and hosted activation happen only after the user has the needed upload assets and chooses the Codee paid path.

Activation URL: {_course_paid_intake_url(course, business=business, target_url=target_url)}

## Proof Checklist

- The target route opens.
- The index file explains the offer clearly.
- The folder includes a `codee-course.json` packet.
- The student can choose self-hosting, Codee hosting, or Codee support.
- The `.codee/course-activation.json` packet explains what must be uploaded and paid before the hosted link is unlocked.
"""
    wrote = {
        "readme": _write_text(root / "README.md", readme, force=args.force),
        "index": _write_text(root / "index.html", _course_starter_html(course, business=business, target_url=target_url), force=args.force),
        "packet": _write_json(root / "codee-course.json", packet, force=args.force),
        "activation": _write_json(root / ".codee" / "course-activation.json", activation_packet, force=args.force),
    }
    _append_event(root, "PostGenerate", {"course_id": course_id, "service": activation_packet.get("service"), "wrote": wrote})
    if args.json:
        print(json.dumps({"ok": True, "course": packet, "activation": activation_packet, "root": str(root), "wrote": wrote}, indent=2))
    else:
        print(f"Codee course workspace: {root}")
        print(f"course={course_id}")
        for name, did_write in wrote.items():
            print(f"{name}: {'written' if did_write else 'exists'}")
        print(f"paid_intake={activation_packet['paid_intake_url']}")
        print("Next: run codee verify, add assets, run codee connect, then run codee activate when payment/hosting is needed.")
    return 0


def command_loops(args: argparse.Namespace) -> int:
    if bool(getattr(args, "proof_scan", False)):
        api_base = str(getattr(args, "api_base", DEFAULT_API_BASE) or DEFAULT_API_BASE).rstrip("/")
        client_id = str(getattr(args, "client_id", "aik9-metri") or "aik9-metri").strip()
        payload = _request_json(
            "POST",
            f"{api_base}/api/codee/loops/proof-scan?client_id={urllib.parse.quote(client_id)}&source=codee_cli",
            {},
            timeout=float(getattr(args, "timeout", "30") or 30),
        )
        if args.json:
            print(json.dumps(payload, indent=2))
            return 0 if payload.get("ok") else 1
        print(f"Codee loop proof scan: ok={bool(payload.get('ok'))} run_id={payload.get('run_id', '')}")
        queue = payload.get("metricool_queue") if isinstance(payload.get("metricool_queue"), dict) else {}
        counts = queue.get("counts") if isinstance(queue.get("counts"), dict) else {}
        if counts:
            print(
                "Metricool queue: "
                f"queued={counts.get('queued', 0)} scheduled={counts.get('scheduled', 0)} "
                f"posted={counts.get('posted', 0)} failed={counts.get('failed', 0)} held={counts.get('held', 0)}"
            )
        print("Proof scan guardrail: no social post, payment, email send, or destructive cleanup runs from this command.")
        return 0 if payload.get("ok") else 1

    if bool(getattr(args, "live", False)):
        api_base = str(getattr(args, "api_base", DEFAULT_API_BASE) or DEFAULT_API_BASE).rstrip("/")
        client_id = str(getattr(args, "client_id", "aik9-metri") or "aik9-metri").strip()
        payload = _request_json(
            "GET",
            f"{api_base}/api/codee/loops/command-center?client_id={urllib.parse.quote(client_id)}",
            timeout=float(getattr(args, "timeout", "30") or 30),
        )
        if args.json:
            print(json.dumps(payload, indent=2))
            return 0 if payload.get("coverage", {}).get("ok") else 1
        print(f"Codee loop command center: loops={payload.get('loop_count', 0)} alerts={len(payload.get('alerts') or [])}")
        for item in payload.get("loops") or []:
            heartbeat = item.get("heartbeat") if isinstance(item.get("heartbeat"), dict) else {}
            print(
                f"- {item.get('display_name') or item.get('id')}: "
                f"status={heartbeat.get('status') or item.get('status') or 'not recorded'} "
                f"failures={heartbeat.get('consecutive_failures', 0)} "
                f"last={heartbeat.get('last_run_at') or 'no heartbeat yet'}"
            )
        queue = payload.get("metricool_queue") if isinstance(payload.get("metricool_queue"), dict) else {}
        counts = queue.get("counts") if isinstance(queue.get("counts"), dict) else {}
        if counts:
            print(
                "Metricool queue: "
                f"queued={counts.get('queued', 0)} scheduled={counts.get('scheduled', 0)} "
                f"posted={counts.get('posted', 0)} failed={counts.get('failed', 0)} held={counts.get('held', 0)}"
            )
        return 0 if payload.get("coverage", {}).get("ok") else 1

    payload = {
        "ok": True,
        "model": "codee-agent-platform-loops",
        "inspiration": {
            "source": "Anthropic's Boris Cherny: Why Coding Is Solved, and What Comes Next",
            "url": "https://www.youtube.com/watch?v=SlGRN8jh2RI",
            "translation": "Use the product internally, run repeatable loops, and make proof inspectable.",
        },
        "loops": CODEE_LOOPS,
        "rule": "A Codee loop is not complete until it writes proof that a user or support operator can inspect later.",
    }
    if args.json:
        print(json.dumps(payload, indent=2))
        return 0
    print("Codee loops")
    print("Inspired by the Claude Code operating pattern: internal use, parallel sessions, loops, and proof.")
    print("")
    for item in CODEE_LOOPS:
        print(f"- {item['name']} ({item['id']})")
        print(f"  purpose: {item['purpose']}")
        print(f"  proof: {item['proof']}")
    print("")
    print("Rule: every loop must write inspectable proof.")
    print("Live status: run `codee loops --live`.")
    print("Proof pass: run `codee loops --proof-scan`.")
    return 0


def _filtered_skills(access: str) -> list[dict[str, Any]]:
    clean = str(access or "public").strip().lower()
    if clean == "all":
        return list(SKILL_CATALOG)
    if clean == "public":
        return [
            item for item in SKILL_CATALOG
            if str(item.get("access") or "").startswith("public") or str(item.get("access") or "") == "backend"
        ]
    if clean == "owner":
        return [item for item in SKILL_CATALOG if str(item.get("access") or "").startswith(("owner", "backend", "public"))]
    return [item for item in SKILL_CATALOG if str(item.get("access") or "") == clean]


def command_skills(args: argparse.Namespace) -> int:
    skills = _filtered_skills(args.access)
    payload = {
        "ok": True,
        "created_at": _now(),
        "cli_version": VERSION,
        "access_filter": args.access,
        "rule": "Public Codee skills must be safe without private credentials. Owner and server skills are visible but gated.",
        "skills": skills,
    }
    if args.json:
        print(json.dumps(payload, indent=2))
        return 0
    print("Codee skills")
    print("Rule: public skills ship safely; owner/server skills stay credential-gated.")
    print("")
    for item in skills:
        print(f"- {item['id']}: {item['name']} [{item['access']}]")
        print(f"  {item['summary']}")
        print(f"  commands: {', '.join(item.get('commands') or [])}")
        print(f"  proof: {item.get('proof')}")
    return 0


def command_skill_check(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    selected = SKILL_CATALOG if args.skill == "all" else [_skill_by_id(args.skill)]
    statuses = [_skill_status(item) for item in selected]
    payload = {
        "ok": all(item.get("available") or item.get("credential_gated") for item in statuses),
        "created_at": _now(),
        "cli_version": VERSION,
        "workspace_root": str(root),
        "skills": statuses,
        "note": "Credential-gated means the skill belongs on Codee owner/backend infrastructure, not inside a public CLI download.",
    }
    report_path = _write_report(root, "latest-skill-check.json", payload)
    if args.json:
        print(json.dumps(payload | {"report": str(report_path)}, indent=2))
    else:
        print(f"Codee skill check: ok={payload['ok']} skills={len(statuses)}")
        for item in statuses:
            status = "available" if item.get("available") else "credential-gated" if item.get("credential_gated") else "missing"
            print(f"{item['id']}: {status}")
            for check in item.get("checks") or []:
                if not check.get("ok") and check.get("install_hint"):
                    print(f"  install_hint={check['install_hint']}")
                elif not check.get("ok") and check.get("note"):
                    print(f"  note={check['note']}")
        print(f"report={report_path}")
    return 0 if payload["ok"] else 1


def command_skill_policy(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    root.mkdir(parents=True, exist_ok=True)
    policy = _build_skill_policy(preset=args.preset, enabled_extra=list(args.enable or []), disabled=list(args.disable or []))
    policy_path = root / ".codee" / "skills.json"
    markdown_path = root / ".codee" / "SKILLS.md"
    wrote_policy = _write_json(policy_path, policy, force=bool(args.force))
    wrote_md = _write_text(markdown_path, _skill_policy_markdown(policy), force=bool(args.force))
    statuses = [_skill_status(_skill_by_id(skill_id)) for skill_id in policy.get("enabled") or []]
    payload = {
        "ok": bool(wrote_policy or policy_path.exists()),
        "created_at": _now(),
        "workspace_root": str(root),
        "policy_path": str(policy_path),
        "markdown_path": str(markdown_path),
        "wrote_policy": wrote_policy,
        "wrote_markdown": wrote_md,
        "policy": policy,
        "enabled_status": statuses,
    }
    report_path = _write_report(root, "latest-skill-policy.json", payload)
    if args.json:
        print(json.dumps(payload | {"report": str(report_path)}, indent=2))
    else:
        print(f"Codee skill policy: ok={payload['ok']} preset={policy['preset']}")
        print(f"enabled={', '.join(policy.get('enabled') or [])}")
        print(f"policy={policy_path}")
        print(f"markdown={markdown_path}")
        print(f"report={report_path}")
        if not wrote_policy:
            print("Use --force to overwrite the existing policy.")
    return 0 if payload["ok"] else 1


def command_browser_scan(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    url = str(args.url or "").strip()
    if not url.startswith(("http://", "https://")):
        print("browser-scan requires --url https://example.com")
        return 2
    timeout = float(args.timeout)
    route = _route_check({"name": "browser-scan-url", "url": url, "expected": [int(code) for code in args.expected.split(",") if code.strip()]}, timeout)
    screenshot_path = Path(args.screenshot).expanduser() if args.screenshot else root / ".codee" / "screenshots" / f"browser-scan-{_safe_time_slug()}.png"
    screenshot_path = screenshot_path.resolve()
    screenshot_path.parent.mkdir(parents=True, exist_ok=True)
    playwright_check = _requirement_status("playwright")
    screenshot_result: dict[str, Any] = {
        "ok": False,
        "skipped": bool(args.no_screenshot),
        "path": str(screenshot_path),
        "skill_check": playwright_check,
    }
    if not args.no_screenshot and playwright_check.get("ok"):
        npx_path = shutil.which("npx") or "npx"
        command = [npx_path, "--no-install", "playwright", "screenshot"]
        if args.full_page:
            command.append("--full-page")
        command.extend([url, str(screenshot_path)])
        try:
            proc = subprocess.run(command, text=True, capture_output=True, timeout=timeout + 30)
            screenshot_result.update({
                "ok": proc.returncode == 0 and screenshot_path.exists(),
                "returncode": proc.returncode,
                "command": command,
                "stdout": (proc.stdout or "").strip()[:500],
                "stderr": (proc.stderr or "").strip()[:800],
            })
        except Exception as exc:
            screenshot_result.update({"ok": False, "error": f"{type(exc).__name__}: {str(exc)[:180]}", "command": command})
    elif not args.no_screenshot:
        screenshot_result["install_hint"] = playwright_check.get("install_hint") or "Install Node.js/npm and Playwright before browser screenshots."
    payload = {
        "ok": bool(route.get("ok") and (args.no_screenshot or screenshot_result.get("ok"))),
        "created_at": _now(),
        "cli_version": VERSION,
        "url": url,
        "route_check": route,
        "screenshot": screenshot_result,
    }
    report_path = _write_report(root, "latest-browser-scan.json", payload)
    if args.json:
        print(json.dumps(payload | {"report": str(report_path)}, indent=2))
    else:
        print(f"Codee browser scan: ok={payload['ok']} status={route.get('status')} screenshot_ok={screenshot_result.get('ok')}")
        if screenshot_result.get("path"):
            print(f"screenshot={screenshot_result.get('path')}")
        if screenshot_result.get("install_hint"):
            print(f"install_hint={screenshot_result.get('install_hint')}")
        if route.get("error"):
            print(f"route_error={route.get('error')}")
        if screenshot_result.get("stderr"):
            print(f"screenshot_error={screenshot_result.get('stderr')}")
        print(f"report={report_path}")
    return 0 if payload["ok"] else 1


def _course_suite_targets(api_base: str) -> list[dict[str, Any]]:
    qr_query = {
        "target": f"{str(api_base or DEFAULT_API_BASE).rstrip('/')}/index2income/qrcodee/",
        "color": "#5b3a20",
        "back": "#f5efe4",
        "logo": "1",
    }
    return [
        {"name": "codee-toolkit", "url": _api_url(api_base, "/codee-toolkit.html"), "expected": [200]},
        {"name": "codee-admin-training", "url": _api_url(api_base, "/codee-admin-training.html"), "expected": [200]},
        {"name": "codee-folder-domain", "url": _api_url(api_base, "/codee-folder-domain.html"), "expected": [200]},
        {"name": "codee-business-types", "url": _api_url(api_base, "/codee-business-types.html"), "expected": [200]},
        {"name": "codee-course-teacher", "url": _api_url(api_base, "/codee-course-teacher.html"), "expected": [200]},
        {"name": "codee-business-types-json", "url": _api_url(api_base, "/assets/codee/codee-business-types.json"), "expected": [200]},
        {"name": "course-hub", "url": _api_url(api_base, "/index2income/"), "expected": [200]},
        {"name": "course-catalog", "url": _api_url(api_base, "/index2income/course-catalog.json"), "expected": [200]},
        {"name": "course-qrcodee", "url": _api_url(api_base, "/index2income/qrcodee/"), "expected": [200]},
        {"name": "course-codeeflyer", "url": _api_url(api_base, "/index2income/codeeflyer/"), "expected": [200]},
        {"name": "course-codeeapp", "url": _api_url(api_base, "/index2income/codeeapp/"), "expected": [200]},
        {"name": "codee-workbench", "url": _api_url(api_base, "/codee-workbench.html"), "expected": [200]},
        {"name": "codee-skills", "url": _api_url(api_base, "/codee-skills.html"), "expected": [200]},
        {"name": "codee-skills-catalog", "url": _api_url(api_base, "/assets/codee/codee-skills-catalog.json"), "expected": [200]},
        {"name": "codee-loop-inspiration", "url": _api_url(api_base, "/assets/codee/codee-platform-inspiration.json"), "expected": [200]},
        {"name": "qrcodee-image-endpoint", "url": _api_url(api_base, "/api/stripe/qr/codee.png", qr_query), "expected": [200]},
    ]


def command_course_smoke(args: argparse.Namespace) -> int:
    api_base = str(args.api_base or DEFAULT_API_BASE).strip().rstrip("/")
    checks = [_route_check(target, float(args.timeout)) for target in _course_suite_targets(api_base)]
    catalog_result = _request_json("GET", _api_url(api_base, "/index2income/course-catalog.json"), timeout=float(args.timeout))
    catalog_courses = catalog_result.get("core_courses") if isinstance(catalog_result, dict) else []
    if not isinstance(catalog_courses, list):
        catalog_courses = []
    catalog_ids = {
        str(item.get("id") or "").strip()
        for item in catalog_courses
        if isinstance(item, dict)
    }
    expected_ids = {"qrcodee", "codeeflyer", "codeeapp"}
    catalog_check = {
        "name": "catalog-core-course-ids",
        "ok": bool(expected_ids.issubset(catalog_ids)),
        "expected": sorted(expected_ids),
        "actual": sorted(catalog_ids),
        "http_status": catalog_result.get("http_status") if isinstance(catalog_result, dict) else 0,
        "error": catalog_result.get("error", "") if isinstance(catalog_result, dict) else "catalog_not_object",
    }
    local_check: dict[str, Any] | None = None
    report_path = None
    if args.path:
        root = Path(args.path).expanduser().resolve()
        packet_path = root / "codee-course.json"
        index_path = root / "index.html"
        packet: dict[str, Any] = {}
        packet_error = ""
        if packet_path.exists():
            try:
                parsed = json.loads(packet_path.read_text(encoding="utf-8"))
                if isinstance(parsed, dict):
                    packet = parsed
            except Exception as exc:
                packet_error = f"{type(exc).__name__}: {str(exc)[:160]}"
        course_id = str(packet.get("course_id") or "").strip()
        target_url = str(packet.get("target_url") or "").strip()
        local_check = {
            "name": "local-course-folder",
            "root": str(root),
            "index_exists": index_path.exists(),
            "packet_exists": packet_path.exists(),
            "course_id": course_id,
            "target_url": target_url,
            "packet_error": packet_error,
            "ok": bool(index_path.exists() and packet_path.exists() and course_id in expected_ids and target_url.startswith(("http://", "https://")) and not packet_error),
        }
        report_path = _write_report(root, "latest-course-suite-smoke.json", {
            "ok": False,
            "created_at": _now(),
            "remote_checks": checks,
            "catalog_check": catalog_check,
            "local_check": local_check,
        })
    payload = {
        "ok": bool(all(item["ok"] for item in checks) and catalog_check["ok"] and (local_check is None or local_check["ok"])),
        "created_at": _now(),
        "api_base": api_base,
        "remote_checks": checks,
        "catalog_check": catalog_check,
        "local_check": local_check,
        "failed": [item for item in checks if not item["ok"]] + ([] if catalog_check["ok"] else [catalog_check]) + ([] if local_check is None or local_check["ok"] else [local_check]),
        "report": str(report_path) if report_path else "",
    }
    if report_path:
        report_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
    if args.json:
        print(json.dumps(payload, indent=2))
    else:
        print(f"ok={payload['ok']} remote_checks={len(checks)} failed={len(payload['failed'])}")
        for item in payload["failed"]:
            print(f"{item.get('name')} error={item.get('error', '')} status={item.get('status', item.get('http_status', ''))}")
        if report_path:
            print(f"report={report_path}")
    return 0 if payload["ok"] else 1


def command_doctor(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    tool_checks = {
        "python3": _requirement_status("python3"),
        "curl": {"ok": bool(shutil.which("curl")), "path": shutil.which("curl") or "", "kind": "command"},
        "node": _requirement_status("node"),
        "npx": _requirement_status("npx"),
        "playwright": _requirement_status("playwright"),
    }
    file_checks = {
        "codee_manifest": (root / ".codee" / "codee.json").exists(),
        "state_json": (root / ".codee" / "state.json").exists(),
        "route_manifest": (root / ".codee" / "routes.json").exists(),
        "permissions": (root / ".codee" / "permissions.json").exists(),
        "hooks": (root / ".codee" / "hooks.json").exists(),
        "tool_registry": (root / ".codee" / "tool-registry.json").exists(),
        "saas_manifest": (root / ".codee" / "saas-manifest.json").exists(),
        "public_launch_packet": (root / ".codee" / "launch" / "public-launch-plan.json").exists(),
        "codeeadmin_packet": (root / ".codee" / "codeeadmin.json").exists(),
        "codeeadmin_daily_digest": (root / ".codee" / "reports" / "codeeadmin-daily-digest.json").exists(),
        "codeeadmin_state_playbook": (root / ".codee" / "codeeadmin" / "state-by-state-playbook.json").exists(),
        "codeeadmin_state_packets": (root / ".codee" / "codeeadmin" / "state-packets.json").exists(),
        "codeeadmin_next20": (root / ".codee" / "codeeadmin" / "next20-execution.json").exists(),
        "landee_mission_packet": (root / ".codee" / "landee" / "landee-mission-packet.json").exists(),
        "codeecpa_packet": (root / ".codee" / "codeecpa" / "codeecpa-intake.json").exists(),
        "company_alignment": (root / ".codee" / "company-alignment.json").exists(),
        "company_packet_alignment": (root / ".codee" / "company" / "company-alignment.json").exists(),
        "company_data_room": (root / ".codee" / "company" / "DATA_ROOM_INDEX.md").exists(),
        "company_monthly_impact": (root / ".codee" / "company" / f"MONTHLY_IMPACT_REPORT_{_company_month('')}.md").exists(),
        "codee_md": (root / "CODEE.md").exists(),
    }
    sensitive_hits = _scan_sensitive_files(root)
    routes = [
        {"name": "codee-cli-page", "url": f"{DEFAULT_API_BASE}/codee-cli.html", "expected": [200]},
        {"name": "codee-cli-download", "url": CODEE_DOWNLOAD_URL, "expected": [200]},
        {"name": "tool-registry", "url": CODEE_TOOL_REGISTRY_URL, "expected": [200]},
        {"name": "release", "url": CODEE_RELEASE_URL, "expected": [200]},
        {"name": "launch-page", "url": CODEE_LAUNCH_URL, "expected": [200]},
        {"name": "launch-checklist-page", "url": CODEE_LAUNCH_CHECKLIST_URL, "expected": [200]},
        {"name": "onboarding-page", "url": CODEE_ONBOARDING_URL, "expected": [200]},
        {"name": "light-saas-page", "url": CODEE_SAAS_URL, "expected": [200]},
        {"name": "customer-portal", "url": CODEE_PORTAL_URL, "expected": [200]},
        {"name": "proof-wall", "url": CODEE_PROOF_WALL_URL, "expected": [200]},
        {"name": "saas-manifest", "url": CODEE_SAAS_MANIFEST_URL, "expected": [200]},
        {"name": "codeeadmin-page", "url": CODEEADMIN_URL, "expected": [200]},
        {"name": "codeeadmin-manifest", "url": CODEEADMIN_MANIFEST_URL, "expected": [200]},
        {"name": "codeeadmin-daily-page", "url": CODEEADMIN_DAILY_DIGEST_URL, "expected": [200]},
        {"name": "codeeadmin-daily-digest", "url": CODEEADMIN_DAILY_DIGEST_MANIFEST_URL, "expected": [200]},
        {"name": "codeeadmin-states-page", "url": CODEEADMIN_STATES_URL, "expected": [200]},
        {"name": "codeeadmin-state-playbook", "url": CODEEADMIN_STATES_MANIFEST_URL, "expected": [200]},
        {"name": "codeeadmin-state-packet-page", "url": f"{CODEEADMIN_STATE_PACKET_URL}?state=OH", "expected": [200]},
        {"name": "codeeadmin-state-packets", "url": CODEEADMIN_STATE_PACKET_MANIFEST_URL, "expected": [200]},
        {"name": "codeeadmin-next20-page", "url": CODEEADMIN_NEXT20_URL, "expected": [200]},
        {"name": "codeeadmin-next20-manifest", "url": CODEEADMIN_NEXT20_MANIFEST_URL, "expected": [200]},
        {"name": "landee-mission-packet-page", "url": LANDEE_MISSION_PACKET_URL, "expected": [200]},
        {"name": "landee-mission-packet-manifest", "url": LANDEE_MISSION_PACKET_MANIFEST_URL, "expected": [200]},
        {"name": "remote-page", "url": CODEE_REMOTE_URL, "expected": [200]},
        {"name": "remote-viewer-page", "url": CODEE_REMOTE_VIEWER_URL, "expected": [200]},
        {"name": "remote-cli-page", "url": CODEE_REMOTE_CLI_URL, "expected": [200]},
        {"name": "remote-installer-page", "url": CODEE_REMOTE_INSTALLER_URL, "expected": [200]},
        {"name": "remote-demo-page", "url": CODEE_REMOTE_DEMO_URL, "expected": [200]},
        {"name": "remote-security-page", "url": CODEE_REMOTE_SECURITY_URL, "expected": [200]},
        {"name": "remote-manifest", "url": CODEE_REMOTE_MANIFEST_URL, "expected": [200]},
        {"name": "remote-host-download", "url": CODEE_REMOTE_HOST_DOWNLOAD_URL, "expected": [200]},
        {"name": "company-alignment-page", "url": CODEE_COMPANY_ALIGNMENT_URL, "expected": [200]},
        {"name": "ip-register-page", "url": CODEE_IP_REGISTER_URL, "expected": [200]},
        {"name": "investor-readiness-page", "url": CODEE_INVESTOR_READINESS_URL, "expected": [200]},
        {"name": "impact-model-page", "url": CODEE_IMPACT_MODEL_URL, "expected": [200]},
        {"name": "business-with-a-mission-page", "url": CODEE_BUSINESS_MISSION_URL, "expected": [200]},
        {"name": "impact-report-template-page", "url": CODEE_IMPACT_REPORT_TEMPLATE_URL, "expected": [200]},
        {"name": "data-room-checklist-page", "url": CODEE_DATA_ROOM_CHECKLIST_URL, "expected": [200]},
        {"name": "codeecpa-page", "url": CODEE_CPA_URL, "expected": [200]},
        {"name": "codeecpa-workspace-page", "url": CODEE_CPA_WORKSPACE_URL, "expected": [200]},
        {"name": "company-alignment-json", "url": CODEE_COMPANY_ALIGNMENT_JSON_URL, "expected": [200]},
    ]
    route_checks: list[dict[str, Any]] = []
    if not bool(getattr(args, "local_only", False)):
        route_checks = [_route_check(item, float(getattr(args, "timeout", 20) or 20)) for item in routes]
    ok = (
        file_checks["codee_manifest"]
        and all(item.get("ok") or key in {"node", "npx", "playwright"} for key, item in tool_checks.items())
        and not sensitive_hits
        and all(item.get("ok") for item in route_checks)
    )
    payload = {
        "ok": ok,
        "schema": "codee.doctor.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "root": str(root),
        "file_checks": file_checks,
        "tool_checks": tool_checks,
        "sensitive_files": sensitive_hits,
        "route_checks": route_checks,
        "next_commands": [
            f"python3 codee.py login {root} --email owner@example.com --business \"My Business\" --write",
            f"python3 codee.py permissions {root} --mode workspace --write --force",
            f"python3 codee.py registry {root} --write --force",
            f"python3 codee.py launch {root} --write --force",
            f"python3 codee.py codeecpa {root} --write --force",
            f"python3 codee.py company {root} --write --force",
            f"python3 codee.py checkpoint {root} --label before-next-build",
            f"python3 codee.py test lane {root} --service codeeqr --route-check",
        ],
    }
    report_path = _write_report(root, "latest-doctor.json", payload)
    if getattr(args, "json", False):
        print(json.dumps(payload | {"report": str(report_path)}, indent=2))
        return 0 if ok else 1
    print(f"Codee doctor: ok={ok} version={VERSION}")
    for name, passed in file_checks.items():
        print(f"{name}: {'ok' if passed else 'missing'}")
    for name, check in tool_checks.items():
        print(f"{name}: {'ok' if check.get('ok') else 'optional-missing' if name in {'node', 'npx', 'playwright'} else 'missing'}")
    if sensitive_hits:
        print("sensitive_files:")
        for item in sensitive_hits[:10]:
            print(f"- {item['path']}")
    for item in route_checks:
        print(f"route {item.get('name')}: {'ok' if item.get('ok') else 'fail'} status={item.get('status')}")
    print(f"report={report_path}")
    return 0 if ok else 1


def command_install(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    root.mkdir(parents=True, exist_ok=True)
    codee_dir = root / ".codee"
    codee_dir.mkdir(parents=True, exist_ok=True)
    source = Path(__file__).resolve()
    cli_path = root / "codee.py"
    launcher_path = root / "codee"
    notes_path = codee_dir / "INSTALL.md"
    if args.write:
        if source.exists() and source != cli_path:
            _checkpoint_existing_path(cli_path, reason="install-cli-copy")
            cli_path.write_text(source.read_text(encoding="utf-8"), encoding="utf-8")
        launcher = "\n".join(
            [
                "#!/usr/bin/env bash",
                "set -euo pipefail",
                'DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"',
                'python3 "$DIR/codee.py" "$@"',
                "",
            ]
        )
        _write_text(launcher_path, launcher, force=True)
        try:
            launcher_path.chmod(0o755)
        except Exception:
            pass
        _write_json(codee_dir / "tool-registry.json", CODEE_TOOL_REGISTRY, force=True)
        _write_json(codee_dir / "release.json", CODEE_RELEASE_DISCIPLINE, force=True)
        _write_text(
            notes_path,
            "\n".join(
                [
                    "# Codee CLI Install",
                    "",
                    f"Version: {VERSION}",
                    "",
                    "Use:",
                    "",
                    "```bash",
                    "./codee doctor .",
                    "./codee login . --email owner@example.com --business \"My Business\" --write",
                    "./codee permissions . --mode workspace --write --force",
                    "./codee heartbeat . --service codeeqr",
                    "```",
                    "",
                    "Upgrade:",
                    "",
                    "```bash",
                    "./codee self-update . --target ./codee.py --write",
                    "```",
                    "",
                ]
            ),
            force=True,
        )
    payload = {
        "ok": True,
        "schema": "codee.install.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "root": str(root),
        "download_url": CODEE_DOWNLOAD_URL,
        "cli_path": str(cli_path),
        "launcher_path": str(launcher_path),
        "notes_path": str(notes_path),
        "wrote": bool(args.write),
        "next_commands": [
            f"python3 {cli_path} doctor {root}",
            f"{launcher_path} login {root} --email owner@example.com --business \"My Business\" --write",
            f"{launcher_path} platform {root} --mode workspace --write --force",
        ],
    }
    report_path = _write_report(root, "latest-install.json", payload)
    if args.json:
        print(json.dumps(payload | {"report": str(report_path)}, indent=2))
    else:
        print(f"Codee install: ok=True wrote={bool(args.write)}")
        print(f"cli={cli_path}")
        print(f"launcher={launcher_path}")
        print(f"report={report_path}")
    return 0


def command_self_update(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    target = Path(args.target or Path(__file__)).expanduser().resolve()
    url = str(args.url or CODEE_DOWNLOAD_URL).strip()
    result = _curl_fetch("GET", url, timeout=float(args.timeout))
    body = str(result.get("body") or "")
    ok_body = bool(result.get("ok") and "VERSION" in body and "Codee" in body[:5000])
    wrote = False
    checkpoint = ""
    if args.write and ok_body:
        checkpoint = _checkpoint_existing_path(target, reason="self-update")
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(body, encoding="utf-8")
        wrote = True
    payload = {
        "ok": bool(ok_body),
        "schema": "codee.self-update.v1",
        "created_at": _now(),
        "current_version": VERSION,
        "url": url,
        "target": str(target),
        "http_status": result.get("status"),
        "wrote": wrote,
        "checkpoint": checkpoint,
        "message": "Downloaded latest CLI. Use --write to replace the target file." if ok_body and not args.write else "",
        "error": result.get("error") if not ok_body else "",
    }
    report_path = _write_report(root, "latest-self-update.json", payload)
    if args.json:
        print(json.dumps(payload | {"report": str(report_path)}, indent=2))
    else:
        print(f"Codee self-update: ok={payload['ok']} wrote={wrote} status={payload['http_status']}")
        print(f"target={target}")
        if checkpoint:
            print(f"checkpoint={checkpoint}")
        if payload.get("error"):
            print(f"error={payload['error']}")
        print(f"report={report_path}")
    return 0 if payload["ok"] else 1


def command_login(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    root.mkdir(parents=True, exist_ok=True)
    manifest = _load_manifest(root) if (root / ".codee" / "codee.json").exists() else {}
    email = str(args.email or manifest.get("owner_email") or "").strip().lower()
    if "@" not in email:
        print("login requires --email owner@example.com")
        return 2
    business = str(args.business or manifest.get("business") or "Codee Client").strip()
    owner = str(args.owner or manifest.get("owner") or "Business Owner").strip()
    client_id = str(args.client_id or manifest.get("client_id") or _slugify(business)).strip()
    codee_user_id = str(manifest.get("codee_user_id") or _codee_user_id(email, f"{owner}:{business}:{client_id}"))
    login_payload = {
        "ok": True,
        "schema": "codee.login.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "email": email,
        "business": business,
        "owner": owner,
        "client_id": client_id,
        "workspace_id": client_id,
        "codee_user_id": codee_user_id,
        "auth_model": "local-identity-plus-optional-backend",
        "privacy": "No password, card, OAuth refresh token, or owner deploy credential is stored by this command.",
    }
    result: dict[str, Any] = {"ok": True, "local_only": True}
    if args.submit:
        result = _request_json("POST", _api_url(args.api_base, "/api/codee/cli/login"), login_payload, timeout=float(args.timeout))
    if args.write:
        updated = {
            **manifest,
            "schema": str(manifest.get("schema") or "codee.platform.v0"),
            "version": VERSION,
            "updated_at": _now(),
            "business": business,
            "owner": owner,
            "owner_email": email,
            "client_id": client_id,
            "codee_user_id": codee_user_id,
            "identity": login_payload,
        }
        _write_json(root / ".codee" / "codee.json", updated, force=True)
        _write_json(root / ".codee" / "login.json", login_payload | {"backend": result}, force=True)
        state = _load_state(root)
        state.update({"business": business, "owner_email": email, "client_id": client_id, "codee_user_id": codee_user_id})
        _write_state(root, state)
        _append_event(root, "LoginConfigured", {"codee_user_id": codee_user_id, "client_id": client_id, "submitted": bool(args.submit)})
    report_path = _write_report(root, "latest-login.json", login_payload | {"backend": result})
    if args.json:
        print(json.dumps(login_payload | {"backend": result, "report": str(report_path)}, indent=2))
    else:
        print(f"Codee login: ok={bool(result.get('ok'))} user={codee_user_id}")
        print(f"workspace_id={client_id}")
        print(f"report={report_path}")
    return 0 if result.get("ok") else 1


def command_registry(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    payload = dict(CODEE_TOOL_REGISTRY)
    release = dict(CODEE_RELEASE_DISCIPLINE)
    if args.write:
        _write_json(root / ".codee" / "tool-registry.json", payload, force=args.force)
        _write_json(root / ".codee" / "release.json", release, force=args.force)
        _append_event(root, "RegistryConfigured", {"tool_count": len(payload.get("commands") or []), "version": VERSION})
    if args.json:
        print(json.dumps({"ok": True, "registry": payload, "release": release}, indent=2))
    else:
        print("Codee tool registry")
        print(f"version={VERSION}")
        for item in payload.get("commands") or []:
            print(f"- {item['name']}: {item['purpose']}")
        if args.write:
            print(f"registry={root / '.codee' / 'tool-registry.json'}")
            print(f"release={root / '.codee' / 'release.json'}")
    return 0


def command_checkpoint(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    label = _slugify(args.label or "manual-checkpoint")
    stamp = _safe_time_slug()
    checkpoint_dir = root / ".codee" / "checkpoints" / f"{stamp}-{label}"
    checkpoint_dir.mkdir(parents=True, exist_ok=True)
    files: list[Path] = []
    for raw in args.file or []:
        candidate = Path(raw).expanduser()
        if not candidate.is_absolute():
            candidate = root / candidate
        if candidate.exists() and candidate.is_file():
            files.append(candidate)
    if not files:
        for candidate in [
            root / "index.html",
            root / "CODEE.md",
            root / "AGENTS.md",
            root / "codee-course.json",
            root / ".codee" / "codee.json",
            root / ".codee" / "state.json",
            root / ".codee" / "permissions.json",
            root / ".codee" / "hooks.json",
            root / ".codee" / "service-contract.json",
        ]:
            if candidate.exists() and candidate.is_file():
                files.append(candidate)
    copied: list[dict[str, str]] = []
    for source in files:
        try:
            rel = source.resolve().relative_to(root.resolve())
        except Exception:
            rel = Path(source.name)
        target = checkpoint_dir / "__".join(rel.parts)
        shutil.copy2(source, target)
        copied.append({"source": str(source), "checkpoint": str(target)})
    manifest = {
        "ok": True,
        "schema": "codee.checkpoint.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "root": str(root),
        "label": label,
        "checkpoint_dir": str(checkpoint_dir),
        "files": copied,
    }
    _write_json(checkpoint_dir / "checkpoint.json", manifest, force=True)
    _write_report(root, "latest-checkpoint.json", manifest)
    _append_event(root, "CheckpointCreated", {"label": label, "file_count": len(copied), "checkpoint_dir": str(checkpoint_dir)})
    if args.json:
        print(json.dumps(manifest, indent=2))
    else:
        print(f"Codee checkpoint: {checkpoint_dir}")
        print(f"files={len(copied)}")
    return 0


def _eval_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee Eval Report",
        "",
        f"Status: {'PASS' if payload.get('ok') else 'NEEDS REPAIR'}",
        f"Created: {payload.get('created_at')}",
        f"Workspace: {payload.get('root')}",
        "",
        "## Findings",
        "",
    ]
    for item in payload.get("findings") or []:
        lines.append(f"- {item.get('severity').upper()}: {item.get('source')} - {item.get('message')}")
    lines.extend(["", "## Recommended Harness Changes", ""])
    for item in payload.get("recommendations") or []:
        lines.append(f"- {item}")
    lines.append("")
    return "\n".join(lines)


def command_eval(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    report_names = [
        "latest-doctor.json",
        "latest-heartbeat.json",
        "latest-codee-verify.json",
        "latest-route-scan.json",
        "latest-browser-scan.json",
        "latest-task-run.json",
        "latest-admin-certification.json",
    ]
    findings: list[dict[str, str]] = []
    for name in report_names:
        report = _read_json_if_exists(root / ".codee" / "reports" / name)
        if not report:
            findings.append({"source": name, "severity": "warn", "message": "Report missing. Run the related proof command before launch."})
            continue
        if not bool(report.get("ok")):
            findings.append({"source": name, "severity": "fail", "message": str(report.get("status") or report.get("error") or "Report is not passing.")})
        for item in report.get("checks") or report.get("pulse") or []:
            if isinstance(item, dict) and not item.get("ok"):
                findings.append({"source": name, "severity": str(item.get("severity") or "warn"), "message": f"{item.get('label') or item.get('name')}: {item.get('copy') or item.get('summary') or 'needs attention'}"})
        for item in report.get("failed") or []:
            if isinstance(item, dict):
                findings.append({"source": name, "severity": "fail", "message": f"{item.get('name') or item.get('id')}: {item.get('error') or item.get('summary') or 'failed'}"})
    sensitive_hits = _scan_sensitive_files(root)
    for item in sensitive_hits:
        findings.append({"source": "sensitive-scan", "severity": "warn", "message": f"Sensitive file found: {item['path']}"})
    recommendations = [
        "Run `codee doctor` first so local tools, sensitive files, registry, and public routes are checked.",
        "Run `codee permissions --mode workspace --write --force` before generating client files.",
        "Run `codee checkpoint --label before-repair` before changing a client folder.",
        "Run `codee verify --route-check` before payment activation or public promotion.",
        "Use `codee support` to create a repair packet when a finding is not locally fixable.",
    ]
    ok = not any(item["severity"] == "fail" for item in findings)
    payload = {
        "ok": ok,
        "schema": "codee.eval.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "root": str(root),
        "finding_count": len(findings),
        "findings": findings,
        "recommendations": recommendations,
        "source_reports": report_names,
    }
    report_path = _write_report(root, "latest-eval.json", payload)
    _write_text(root / ".codee" / "EVAL_REPORT.md", _eval_markdown(payload), force=True)
    _append_event(root, "EvalGenerated", {"ok": ok, "finding_count": len(findings)})
    if args.json:
        print(json.dumps(payload | {"report": str(report_path)}, indent=2))
    else:
        print(f"Codee eval: ok={ok} findings={len(findings)}")
        for item in findings[:12]:
            print(f"{item['severity'].upper()}: {item['source']} - {item['message']}")
        print(f"report={report_path}")
    return 0 if ok else 1


def command_preview(args: argparse.Namespace) -> int:
    preview_args = argparse.Namespace(**vars(args))
    preview_args.command = "client"
    preview_args.submit = bool(args.submit)
    preview_args.dry_run = bool(args.dry_run)
    preview_args.connect_wordpress = bool(getattr(args, "connect_wordpress", False))
    preview_args.wordpress_site = str(getattr(args, "wordpress_site", "") or "")
    preview_args.connect_google = bool(getattr(args, "connect_google", False))
    preview_args.drive_folder = str(getattr(args, "drive_folder", "") or "")
    preview_args.gmail_query = str(getattr(args, "gmail_query", "") or "")
    preview_args.ask = bool(getattr(args, "ask", False))
    preview_args.api_fallback_base = list(getattr(args, "api_fallback_base", []) or [])
    return command_client(preview_args)


def command_test(args: argparse.Namespace) -> int:
    action = str(getattr(args, "test_action", "") or "")
    if action != "lane":
        print("Unknown test action. Use `codee test lane ...`.")
        return 2
    root = Path(args.path).expanduser().resolve()
    checkpoint_args = argparse.Namespace(path=str(root), label=f"before-{args.service}-lane-test", file=[], json=False)
    command_checkpoint(checkpoint_args)
    verify_args = argparse.Namespace(
        path=str(root),
        service=args.service,
        business=getattr(args, "business", ""),
        owner=getattr(args, "owner", ""),
        email=getattr(args, "email", ""),
        target_url=getattr(args, "target_url", ""),
        api_base=args.api_base,
        timeout=args.timeout,
        strict=bool(args.strict),
        live=bool(args.live),
        route_check=bool(args.route_check),
        json=False,
    )
    verify_code = command_verify(verify_args)
    eval_args = argparse.Namespace(path=str(root), json=False)
    eval_code = command_eval(eval_args)
    payload = {
        "ok": verify_code == 0 and eval_code == 0,
        "schema": "codee.lane-test.v1",
        "created_at": _now(),
        "service": _normalize_service(args.service),
        "verify_exit_code": verify_code,
        "eval_exit_code": eval_code,
        "reports": {
            "verify": str(root / ".codee" / "reports" / "latest-codee-verify.json"),
            "eval": str(root / ".codee" / "reports" / "latest-eval.json"),
            "checkpoint": str(root / ".codee" / "reports" / "latest-checkpoint.json"),
        },
    }
    report_path = _write_report(root, "latest-lane-test.json", payload)
    if args.json:
        print(json.dumps(payload | {"report": str(report_path)}, indent=2))
    else:
        print(f"Codee lane test: ok={payload['ok']} service={payload['service']}")
        print(f"report={report_path}")
    return 0 if payload["ok"] else 1


def _heartbeat_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee Heartbeat",
        "",
        f"Status: {'PASS' if payload.get('ok') else 'NEEDS ATTENTION'}",
        f"Created: {payload.get('created_at')}",
        f"Business: {payload.get('business')}",
        f"Workspace: {payload.get('workspace_id')}",
        f"Service: {payload.get('service')}",
        "",
        "## Pulse",
        "",
    ]
    for item in payload.get("pulse") or []:
        marker = "PASS" if item.get("ok") else str(item.get("severity") or "warn").upper()
        lines.append(f"- {marker}: {item.get('label')} - {item.get('copy')}")
    route_results = payload.get("route_results") if isinstance(payload.get("route_results"), list) else []
    if route_results:
        lines.extend(["", "## Route Proof", ""])
        for item in route_results:
            marker = "PASS" if item.get("ok") else "FAIL"
            lines.append(f"- {marker}: {item.get('url')} status={item.get('status')} transport={item.get('transport')}")
    task = payload.get("live_task") if isinstance(payload.get("live_task"), dict) else {}
    if task:
        lines.extend(["", "## Live Task", ""])
        lines.append(f"- Task: {task.get('task_id')}")
        lines.append(f"- Status: {task.get('status')}")
        for step in task.get("task_steps") or []:
            lines.append(f"- {step.get('label')}: {step.get('status')}")
    lines.extend(["", "## Hardcoded User Tools", ""])
    for item in payload.get("download_tools") or []:
        lines.append(f"- {item.get('command')}: {item.get('purpose')}")
    lines.extend(["", "## Next Commands", ""])
    for command in payload.get("next_commands") or []:
        lines.append(f"```bash\n{command}\n```")
    return "\n".join(lines) + "\n"


def _heartbeat_once(root: Path, args: argparse.Namespace) -> tuple[dict[str, Any], Path]:
    manifest = _load_manifest(root)
    service = _normalize_service(str(getattr(args, "service", "") or "codee-support"))
    inventory = _folder_inventory(root)
    latest_verify = _read_json_if_exists(root / ".codee" / "reports" / "latest-codee-verify.json")
    latest_task_run = _read_json_if_exists(root / ".codee" / "reports" / "latest-task-run.json")
    latest_scan = _read_json_if_exists(root / ".codee" / "reports" / "latest-route-scan.json")
    latest_support = _read_json_if_exists(root / ".codee" / "reports" / "latest-support-request.json")
    latest_connection = _read_json_if_exists(root / ".codee" / "backend-connection.json")
    latest_user_memory = _read_json_if_exists(root / ".codee" / "user-memory.json")
    latest_accessibility = _read_json_if_exists(root / ".codee" / "accessibility.json")
    state = _load_state(root)
    sensitive_hits = _scan_sensitive_files(root)
    tasks = _list_tasks(root)
    pulse: list[dict[str, Any]] = []

    def add(key: str, label: str, ok: bool, copy: str, *, severity: str = "warn") -> None:
        pulse.append({"id": key, "label": label, "ok": bool(ok), "copy": copy, "severity": severity})

    add("folder", "Folder exists", bool(inventory.get("exists")), "Codee can inspect this workspace.", severity="fail")
    add("index", "index.html exists", bool(inventory.get("has_index")), "The business has a public entry file.", severity="fail")
    add("identity", "Codee identity", bool(manifest.get("codee_user_id") and manifest.get("client_id")), "The workspace has a Codee user ID and client ID.")
    add("state", "Workspace state", bool(state.get("schema") == "codee.state.v1"), ".codee/state.json keeps latest command, service, status, and history.")
    add("platform", "Platform layer", (root / ".codee" / "platform-parity.json").exists(), "Tasks, agents, permissions, memory, hooks, and connectors can be installed with `codee platform --write`.")
    add("agent-core", "Governed agent core", (root / ".codee" / "agent-core.json").exists(), "AGI-style goals, tools, verification, heartbeat, and guardrails can be installed with `codee agent-core --write`.")
    add("user-memory", "User memory vault", bool(latest_user_memory.get("codee_user_id") or latest_user_memory.get("journal")), "Long-term user memory can be installed with `codee memory-vault init`.")
    add("accessibility", "Veteran accessibility rules", bool(latest_accessibility.get("course_rules")), "Short text, large controls, and proof-first course rules can be installed with `codee accessibility --write`.")
    add("verify", "Latest verify", bool(latest_verify.get("ok")), "The last service verification report is saved.")
    add("task-run", "Latest task run", bool(latest_task_run.get("ok")), "The last task-run proof report is saved.")
    add("backend", "Backend connection", bool(latest_connection.get("ok") or latest_connection.get("connection_id")), "Codee backend can attach delivery room, workbench, and activation status.")
    add("support", "Support path", bool(latest_support.get("request_id")), "A support/update packet exists for this workspace.")
    add("sensitive-files", "Sensitive files blocked", not sensitive_hits, "Secrets, .env files, private keys, OAuth tokens, and Stripe secrets should not be uploaded.", severity="warn")
    if latest_scan:
        add("route-scan", "Latest route scan", bool(latest_scan.get("ok")), f"Route scan checked {len(latest_scan.get('checks') or [])} targets.")

    route_results: list[dict[str, Any]] = []
    route_urls = [str(item).strip() for item in (getattr(args, "url", None) or []) if str(item).strip()]
    for url in _default_route_urls_from_reports(root):
        if url not in route_urls:
            route_urls.append(url)
    for url in route_urls:
        if url.startswith(("http://", "https://")):
            route_results.append(_route_check({"name": "heartbeat-url", "url": url, "expected": [200, 301, 302, 307, 308]}, float(getattr(args, "timeout", 20) or 20)))
    if route_results:
        add("heartbeat-routes", "Heartbeat route check", all(item.get("ok") for item in route_results), "Routes passed from this heartbeat command.", severity="fail")

    live_task: dict[str, Any] = {}
    task_id = str(getattr(args, "task_id", "") or "").strip()
    if task_id and bool(getattr(args, "live", False)):
        live_task = _request_json("GET", _api_url(args.api_base, f"/api/codee/cli/tasks/{task_id}"), timeout=float(getattr(args, "timeout", 20) or 20))
        add("live-task", "Live task status", bool(live_task.get("ok")), f"Backend status: {live_task.get('status') or live_task.get('error') or 'unknown'}.", severity="fail")

    download_tools = [
        {"command": "heartbeat", "purpose": "Show the user a one-command pulse of folder health, proof, task status, and next steps."},
        {"command": "launch", "purpose": "Write the one-through-twenty public launch packet, demo scripts, policy queue, case studies, weekly proof, and valuation metrics."},
        {"command": "codeecpa", "purpose": "Prepare a guarded legal/tax/CPA review packet without replacing licensed professional advice."},
        {"command": "agent-core / agi", "purpose": "Install the governed AGI-style operating loop without claiming unrestricted AGI."},
        {"command": "memory-vault / remember", "purpose": "Save and search user-specific preferences, service history, proof, and next steps."},
        {"command": "doctor", "purpose": "Check the workspace basics before a user gets lost."},
        {"command": "platform", "purpose": "Install tasks, agents, permissions, memory, hooks, and connector maps."},
        {"command": "task create/send/run/status", "purpose": "Track a business request from local folder to backend delivery room proof."},
        {"command": "verify", "purpose": "Confirm the service lane is launch-ready before activation."},
        {"command": "scan / browser-scan", "purpose": "Catch 404s and visual route issues before public promotion."},
        {"command": "money-map", "purpose": "Turn the folder into audience, offer, CTA, payment path, delivery path, and proof."},
        {"command": "support", "purpose": "Create an update packet the client can send without explaining everything again."},
        {"command": "upgrade / pricing / license", "purpose": "Keep paid hosting and support behind Stripe-hosted payment proof."},
        {"command": "loops --live", "purpose": "Show owner-side loop status when backend access is available."},
    ]
    fail_count = sum(1 for item in pulse if not item.get("ok") and item.get("severity") == "fail")
    warn_count = sum(1 for item in pulse if not item.get("ok") and item.get("severity") != "fail")
    ok = fail_count == 0
    business = str(getattr(args, "business", "") or manifest.get("business") or "Codee Client").strip()
    payload = {
        "ok": ok,
        "schema": "codee.heartbeat.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "business": business,
        "service": service,
        "workspace_id": str(manifest.get("client_id") or root.name),
        "codee_user_id": str(manifest.get("codee_user_id") or ""),
        "root": str(root),
        "folder_inventory": inventory,
        "pulse": pulse,
        "fail_count": fail_count,
        "warn_count": warn_count,
        "route_results": route_results,
        "state": {
            "last_command": state.get("last_command"),
            "last_status": state.get("last_status"),
            "history_count": len(state.get("history") or []),
        },
        "sensitive_files": sensitive_hits,
        "live_task": live_task,
        "latest_reports": {
            "verify": bool(latest_verify),
            "task_run": bool(latest_task_run),
            "route_scan": bool(latest_scan),
            "support": bool(latest_support),
            "backend_connection": bool(latest_connection),
            "user_memory": bool(latest_user_memory),
            "accessibility": bool(latest_accessibility),
        },
        "task_count": len(tasks),
        "latest_task_id": tasks[0].get("task_id") if tasks else "",
        "download_tools": download_tools,
        "next_commands": [
            f"python3 codee.py memory-vault init {root} --business \"{business}\" --service {service} --force",
            f"python3 codee.py accessibility {root} --business \"{business}\" --service {service} --write --force",
            f"python3 codee.py platform {root} --business \"{business}\" --service {service} --write --force",
            f"python3 codee.py verify {root} --service {service}",
            f"python3 codee.py task create {root} --title \"Make {business} live\" --service {service} --prompt \"Verify this folder and prepare activation.\" --send",
            f"python3 codee.py task run {root} --task-id <TASK_ID> --write-platform --send-result",
            f"python3 codee.py support {root} --service {service} --message \"Review this heartbeat and tell me the next activation step.\"",
        ],
    }
    report_path = _write_report(root, "latest-heartbeat.json", payload)
    _write_text(root / ".codee" / "HEARTBEAT.md", _heartbeat_markdown(payload), force=True)
    _append_event(root, "Heartbeat", {"ok": ok, "fail_count": fail_count, "warn_count": warn_count, "task_id": task_id})
    return payload | {"report": str(report_path)}, report_path


def command_heartbeat(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    count = max(1, min(int(getattr(args, "count", 1) or 1), 60))
    interval = max(1.0, min(float(getattr(args, "interval", 30) or 30), 3600.0))
    latest: dict[str, Any] = {}
    latest_path = root / ".codee" / "reports" / "latest-heartbeat.json"
    for index in range(count):
        latest, latest_path = _heartbeat_once(root, args)
        if not bool(getattr(args, "json", False)):
            stamp = str(latest.get("created_at") or "")
            print(f"Codee heartbeat {index + 1}/{count}: ok={latest.get('ok')} fails={latest.get('fail_count')} warnings={latest.get('warn_count')} {stamp}")
            for item in latest.get("pulse") or []:
                if item.get("ok"):
                    continue
                print(f"{str(item.get('severity') or 'warn').upper()}: {item.get('label')} - {item.get('copy')}")
            print(f"report={latest_path}")
        if index < count - 1:
            time.sleep(interval)
    if bool(getattr(args, "json", False)):
        print(json.dumps(latest, indent=2))
    return 0 if latest.get("ok") else 1


def _recommendation_root(args: argparse.Namespace) -> str:
    value = getattr(args, "path", ".")
    if not value:
        return "."
    return str(value)


def _recommendation_business(args: argparse.Namespace) -> str:
    return str(getattr(args, "business", "") or "My Business").strip()


def _codee_next_recommendations(args: argparse.Namespace, exit_code: int) -> list[str]:
    command = str(getattr(args, "command", "") or "")
    root = _recommendation_root(args)
    business = _recommendation_business(args)
    if exit_code != 0:
        return [
            f"Stabilize the failed `{command}` result before moving forward.",
            f"Run `python3 codee.py folder-plan {root} --business \"{business}\" --service codee-course --write --force` to inspect the workspace.",
            f"Run `python3 codee.py support {root} --service codee-cli-intake --message \"Help me fix the failed {command} step before course delivery.\"` if the next fix is not obvious.",
        ]
    if command == "init":
        return [
            f"Run `python3 codee.py money-map {root} --business \"{business}\"` to turn the intake into a first offer.",
            "Run `python3 codee.py courses` and choose QRCodee, Codee Flyer, or Codee App as the first course lane.",
            f"Run `python3 codee.py folder-plan {root} --business \"{business}\" --service codee-course --write --force` so the folder is teachable.",
        ]
    if command == "money-map":
        return [
            f"Pick one course lane and run `python3 codee.py course-init {root}/course --course qrcodee --business \"{business}\" --target-url https://example.com --force`.",
            f"Run `python3 codee.py folder-plan {root} --business \"{business}\" --service intake-course --write --force` to keep the workspace clean.",
            "Write the CTA in one sentence before adding images, checkout, or hosting.",
        ]
    if command in {"courses", "course-init"}:
        return [
            f"Run `python3 codee.py folder-plan {root} --business \"{business}\" --service codee-course --write --force` before hosting the course output.",
            f"Run `python3 codee.py scan {root} --url https://clients.codee.chat/index2income/` to prove the live course route.",
            "Keep the next lesson focused on one output: QR image, flyer folder, or app-style guide page.",
        ]
    if command in {"folder-plan", "domain-plan"}:
        return [
            f"Run `python3 codee.py course-smoke {root}` after the folder and domain plan are saved.",
            f"Run `python3 codee.py scan {root} --url https://clients.codee.chat/codee-folder-domain.html` to prove the teaching page still opens.",
            "Use the saved `.codee` plan as the next intake checklist before taking payment or promising hosting.",
        ]
    if command in {"scan", "browser-scan", "course-smoke", "toolkit-smoke"}:
        return [
            f"If the scan passed, run `python3 codee.py support {root} --service codee-course --message \"Course output passed proof and is ready for delivery-room review.\"`.",
            f"If the scan failed, run `python3 codee.py folder-plan {root} --business \"{business}\" --service codee-course --write --force` and fix the missing route.",
            "Do not start the next course lesson until the current intake/course route has proof saved.",
        ]
    if command == "heartbeat":
        return [
            f"Run `python3 codee.py agent-core {root} --business \"{business}\" --service codeeqr --write --force` if the heartbeat says the governed agent core is missing.",
            f"Run `python3 codee.py platform {root} --business \"{business}\" --service codee-support --write --force` if the heartbeat says the platform layer is missing.",
            f"Run `python3 codee.py verify {root} --service codeeqr --route-check` before asking Codee to activate or host the lane.",
            f"Run `python3 codee.py task run {root} --task-id <TASK_ID> --write-platform --send-result` when a task exists and the delivery room needs proof.",
        ]
    if command in {"agent-core", "agi"}:
        return [
            f"Run `python3 codee.py heartbeat {root} --service codeeqr` to see the workspace pulse after installing the governed agent core.",
            f"Run `python3 codee.py platform {root} --business \"{business}\" --service codeeqr --write --force` to install the full task, memory, connector, hook, and permission layer.",
            f"Run `python3 codee.py task create {root} --title \"Make my first Codee lane live\" --service codeeqr --prompt \"Use the governed agent core to create, verify, and prepare activation.\"`.",
        ]
    if command in {"memory-vault", "remember"}:
        return [
            f"Run `python3 codee.py heartbeat {root} --service codeeqr` to confirm the user memory vault is visible to Codee.",
            f"Run `python3 codee.py memory-vault add {root} --kind preference --text \"Remember my preferred offer, colors, and delivery style.\" --tag preference` when the user gives stable context.",
            f"Run `python3 codee.py memory-vault search {root} --query \"preferred offer colors delivery\"` before repeating intake questions.",
        ]
    if command == "accessibility":
        return [
            f"Run `python3 codee.py course-init {root}/qrcodee-course --course qrcodee --business \"{business}\" --target-url https://example.com --force` to generate a short-text learner page.",
            f"Run `python3 codee.py heartbeat {root} --service codeeqr` to confirm accessibility rules are present.",
            "Keep the next lesson to one action, three or four checks, and a proof command.",
        ]
    if command in {"toolkit", "toolkit-init", "skills", "skill-policy", "skill-check"}:
        return [
            f"Run `python3 codee.py init {root} --business \"{business}\" --force` if the workspace does not have a Codee identity yet.",
            f"Run `python3 codee.py folder-plan {root} --business \"{business}\" --service codee-toolkit --write --force` so the toolkit folder can be taught.",
            f"Run `python3 codee.py course-init {root}/courses/qrcodee --course qrcodee --business \"{business}\" --target-url https://example.com --force` as the first intake/course exercise.",
        ]
    if command in {"platform", "permissions", "agents", "memory", "mcp", "task"}:
        return [
            f"Run `python3 codee.py memory-vault init {root} --business \"{business}\" --service codeeqr --force` so the user has long-term recall.",
            f"Run `python3 codee.py accessibility {root} --business \"{business}\" --service codeeqr --write --force` so disabled-veteran training stays readable.",
            f"Run `python3 codee.py verify {root} --service codeeqr` so the platform files still tie back to a real lane.",
            f"Run `python3 codee.py task create {root} --title \"Make my first Codee lane live\" --service codeeqr --prompt \"Create, verify, connect, and prepare hosted activation for the first QRCodee lane.\"` to start a tracked task thread.",
            f"Run `python3 codee.py connect {root} --service codeeqr --email owner@example.com` when the folder is ready to bind to Codee backend.",
        ]
    if command in {"saas", "portal", "entitlements", "starter", "remote", "company", "codeeadmin"}:
        return [
            f"Run `python3 codee.py doctor {root}` to prove the SaaS page, portal, proof wall, registry, and release routes.",
            f"Run `python3 codee.py codeeadmin {root} --business \"{business}\" --write --force` so the owner view stays reduced to the next three moves.",
            f"Run `python3 codee.py portal {root} --service codeeqr --plan free-trainee` to show the customer-facing account room.",
            f"Run `python3 codee.py company {root} --write --force` to keep the IP, investor, and impact packets current.",
            f"Run `python3 codee.py test lane {root} --service codeeqr --target-url https://codee.chat --route-check` before public promotion.",
        ]
    return [
        f"Run `python3 codee.py init {root} --business \"{business}\" --force` to create or refresh the intake workspace.",
        f"Run `python3 codee.py courses` to choose the next course lane.",
        f"Run `python3 codee.py folder-plan {root} --business \"{business}\" --service codee-course --write --force` to keep the folder teachable.",
    ]


def _print_codee_recommendations(args: argparse.Namespace, exit_code: int) -> None:
    if bool(getattr(args, "json", False)):
        return
    if os.getenv("CODEE_RECOMMENDATIONS", "1").strip().lower() in {"0", "false", "off", "no"}:
        return
    started = dt.datetime.now(dt.timezone.utc)
    ends = started + dt.timedelta(hours=48)
    print("")
    print("Next Codee CLI intake/course recommendations")
    print(f"48-hour focus window: {started.strftime('%Y-%m-%d %H:%M UTC')} to {ends.strftime('%Y-%m-%d %H:%M UTC')}")
    for index, item in enumerate(_codee_next_recommendations(args, exit_code), start=1):
        print(f"{index}. {item}")


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="codee", description="Codee Platform CLI v1")
    parser.add_argument("--version", action="version", version=VERSION)
    public_commands = (
        "explain,install,self-update,login,registry,checkpoint,eval,preview,test,launch,saas,portal,entitlements,starter,remote,company,codeeadmin,codeecpa,init,scan,money-map,toolkit,folder-plan,domain-plan,admin-training,"
        "admin-certify,business-types,business-assistant-init,toolkit-init,toolkit-smoke,"
        "courses,contracts,course-init,loops,heartbeat,agent-core,agi,memory-vault,remember,accessibility,skills,skill-check,skill-policy,browser-scan,course-smoke,"
        "pricing,upgrade,invoice,license,client,connect,activate,verify,hooks,connectors,platform,"
        "permissions,agents,memory,mcp,task,room,delivery,account,workbench,support,doctor"
    )
    sub = parser.add_subparsers(dest="command", required=True, metavar="{" + public_commands + "}")

    explain = sub.add_parser("explain", help="Explain the Codee platform model.")
    explain.set_defaults(func=command_explain)

    install = sub.add_parser("install", help="Install Codee CLI into a workspace with a launcher, registry, and release notes.")
    install.add_argument("path", nargs="?", default=".")
    install.add_argument("--write", action="store_true", help="Copy this CLI to codee.py and write a ./codee launcher.")
    install.add_argument("--json", action="store_true")
    install.set_defaults(func=command_install)

    self_update = sub.add_parser("self-update", aliases=["upgrade-cli"], help="Fetch the latest public Codee CLI and optionally replace a local codee.py.")
    self_update.add_argument("path", nargs="?", default=".")
    self_update.add_argument("--target", default="", help="CLI file to replace. Defaults to this running file.")
    self_update.add_argument("--url", default=CODEE_DOWNLOAD_URL)
    self_update.add_argument("--timeout", default="30")
    self_update.add_argument("--write", action="store_true", help="Actually replace --target after a checkpoint.")
    self_update.add_argument("--json", action="store_true")
    self_update.set_defaults(func=command_self_update)

    login = sub.add_parser("login", help="Bind this folder to a Codee user ID without storing passwords or third-party secrets.")
    login.add_argument("path", nargs="?", default=".")
    login.add_argument("--email", required=True)
    login.add_argument("--business", default="")
    login.add_argument("--owner", default="")
    login.add_argument("--client-id", default="")
    login.add_argument("--submit", action="store_true", help="Optionally register the login identity with Codee backend.")
    login.add_argument("--api-base", default=DEFAULT_API_BASE)
    login.add_argument("--timeout", default="30")
    login.add_argument("--write", action="store_true")
    login.add_argument("--json", action="store_true")
    login.set_defaults(func=command_login)

    registry = sub.add_parser("registry", help="Show or write the public Codee tool registry and release discipline files.")
    registry.add_argument("path", nargs="?", default=".")
    registry.add_argument("--write", action="store_true")
    registry.add_argument("--force", action="store_true")
    registry.add_argument("--json", action="store_true")
    registry.set_defaults(func=command_registry)

    checkpoint = sub.add_parser("checkpoint", help="Create a local Codee checkpoint before edits, tests, or deploy work.")
    checkpoint.add_argument("path", nargs="?", default=".")
    checkpoint.add_argument("--label", default="manual-checkpoint")
    checkpoint.add_argument("--file", action="append", help="Specific file to include. Can be passed more than once.")
    checkpoint.add_argument("--json", action="store_true")
    checkpoint.set_defaults(func=command_checkpoint)

    eval_cmd = sub.add_parser("eval", aliases=["evals"], help="Convert failed scans and proof reports into an improvement report.")
    eval_cmd.add_argument("path", nargs="?", default=".")
    eval_cmd.add_argument("--json", action="store_true")
    eval_cmd.set_defaults(func=command_eval)

    preview = sub.add_parser("preview", help="Create or submit a locked Codee preview using the same client intake path.")
    preview.add_argument("path", nargs="?", default=".")
    preview.add_argument("--service", default="codeeqr")
    preview.add_argument("--business", default="")
    preview.add_argument("--owner", default="")
    preview.add_argument("--email", default="")
    preview.add_argument("--target-url", default="")
    preview.add_argument("--goal", default="")
    preview.add_argument("--connect-wordpress", action="store_true")
    preview.add_argument("--wordpress-site", default="")
    preview.add_argument("--connect-google", action="store_true")
    preview.add_argument("--drive-folder", default="")
    preview.add_argument("--gmail-query", default="")
    preview.add_argument("--ask", action="store_true")
    preview.add_argument("--submit", action="store_true")
    preview.add_argument("--dry-run", action="store_true")
    preview.add_argument("--api-base", default=DEFAULT_API_BASE)
    preview.add_argument("--api-fallback-base", action="append", default=[])
    preview.add_argument("--timeout", default="30")
    preview.add_argument("--json", action="store_true")
    preview.set_defaults(func=command_preview)

    test = sub.add_parser("test", help="Run Codee proof tests.")
    test_sub = test.add_subparsers(dest="test_action", required=True)
    test_lane = test_sub.add_parser("lane", help="Run checkpoint, verify, and eval for one service lane.")
    test_lane.add_argument("path", nargs="?", default=".")
    test_lane.add_argument("--service", default="codeeqr")
    test_lane.add_argument("--business", default="")
    test_lane.add_argument("--owner", default="")
    test_lane.add_argument("--email", default="")
    test_lane.add_argument("--target-url", default="")
    test_lane.add_argument("--api-base", default=DEFAULT_API_BASE)
    test_lane.add_argument("--timeout", default="30")
    test_lane.add_argument("--strict", action="store_true")
    test_lane.add_argument("--live", action="store_true")
    test_lane.add_argument("--route-check", action="store_true")
    test_lane.add_argument("--json", action="store_true")
    test_lane.set_defaults(func=command_test)

    saas = sub.add_parser("saas", help="Show or write the Codee light SaaS manifest and 20-move operating map.")
    saas.add_argument("path", nargs="?", default=".")
    saas.add_argument("--write", action="store_true")
    saas.add_argument("--force", action="store_true")
    saas.add_argument("--json", action="store_true")
    saas.set_defaults(func=command_saas)

    launch = sub.add_parser("launch", help="Write the 20-move Codee public launch packet and proof templates.")
    launch.add_argument("path", nargs="?", default=".")
    launch.add_argument("--business", default="")
    launch.add_argument("--owner", default="")
    launch.add_argument("--email", default="")
    launch.add_argument("--service", default="")
    launch.add_argument("--plan", default="")
    launch.add_argument("--write", action="store_true")
    launch.add_argument("--force", action="store_true")
    launch.add_argument("--json", action="store_true")
    launch.set_defaults(func=command_launch)

    portal = sub.add_parser("portal", help="Show the customer portal URL for a Codee workspace.")
    portal.add_argument("path", nargs="?", default=".")
    portal.add_argument("--service", default="codee-support")
    portal.add_argument("--plan", default="")
    portal.add_argument("--url", default="", help="Override the generated portal URL.")
    portal.add_argument("--open", action="store_true")
    portal.add_argument("--json", action="store_true")
    portal.set_defaults(func=command_portal)

    entitlements = sub.add_parser("entitlements", help="Show what each Codee SaaS plan unlocks.")
    entitlements.add_argument("path", nargs="?", default=".")
    entitlements.add_argument("--plan", default="", choices=["", *CODEE_SAAS_ENTITLEMENTS.keys()])
    entitlements.add_argument("--write", action="store_true")
    entitlements.add_argument("--force", action="store_true")
    entitlements.add_argument("--json", action="store_true")
    entitlements.set_defaults(func=command_entitlements)

    company = sub.add_parser("company", help="Write Codee company alignment, IP, investor, and impact packets.")
    company.add_argument("path", nargs="?", default=".")
    company.add_argument("--business", default="Codee")
    company.add_argument("--owner", default="Owner")
    company.add_argument("--packet", default="all", choices=["all", "governance", "ip", "investor", "impact", "data-room", "case-study"])
    company.add_argument("--month", default="")
    company.add_argument("--public-safe", action="store_true")
    company.add_argument("--write", action="store_true")
    company.add_argument("--force", action="store_true")
    company.add_argument("--open", action="store_true")
    company.add_argument("--json", action="store_true")
    company.set_defaults(func=command_company)

    codeeadmin = sub.add_parser("codeeadmin", aliases=["admin-ops"], help="Write the CodeeAdmin owner operating packet and AI K9 routing plan.")
    codeeadmin.add_argument("path", nargs="?", default=".")
    codeeadmin.add_argument("--business", default="AI K9 / Invest In Vets")
    codeeadmin.add_argument("--owner", default="Sean")
    codeeadmin.add_argument("--focus", default="land housing mission")
    codeeadmin.add_argument("--month", default="")
    codeeadmin.add_argument("--state", action="append", default=[], help="Active state code or name. Can be repeated or comma-separated. Defaults to NY and OH.")
    codeeadmin.add_argument("--all-states", action="store_true", help="Generate the state-by-state playbook with all states marked active.")
    codeeadmin.add_argument("--write", action="store_true")
    codeeadmin.add_argument("--force", action="store_true")
    codeeadmin.add_argument("--open", action="store_true")
    codeeadmin.add_argument("--json", action="store_true")
    codeeadmin.set_defaults(func=command_codeeadmin)

    codeecpa = sub.add_parser("codeecpa", aliases=["cpa"], help="Write a guarded legal/tax/CPA consultation-prep packet.")
    codeecpa.add_argument("path", nargs="?", default=".")
    codeecpa.add_argument("--business", default="")
    codeecpa.add_argument("--owner", default="")
    codeecpa.add_argument("--topic", default="")
    codeecpa.add_argument("--jurisdiction", default="United States / Ohio")
    codeecpa.add_argument("--entity", default="")
    codeecpa.add_argument("--tax-year", default="")
    codeecpa.add_argument("--public-safe", action="store_true")
    codeecpa.add_argument("--write", action="store_true")
    codeecpa.add_argument("--force", action="store_true")
    codeecpa.add_argument("--json", action="store_true")
    codeecpa.set_defaults(func=command_codeecpa)

    starter = sub.add_parser("starter", help="Create a one-command Codee starter workspace for a business type and service lane.")
    starter.add_argument("path", nargs="?", default="./codee-starter")
    starter.add_argument("--preset", default="qrcodee", choices=list(CODEE_STARTER_PACKS.keys()))
    starter.add_argument("--service", default="")
    starter.add_argument("--business", default="My Business")
    starter.add_argument("--owner", default="Business Owner")
    starter.add_argument("--email", default="")
    starter.add_argument("--client-id", default="")
    starter.add_argument("--target-url", default="https://codee.chat")
    starter.add_argument("--plan", default="free-trainee")
    starter.add_argument("--force", action="store_true")
    starter.add_argument("--json", action="store_true")
    starter.set_defaults(func=command_starter)

    remote = sub.add_parser("remote", help="Plan Codee Remote Viewer, Remote CLI bridge, pairing, and status.")
    remote_sub = remote.add_subparsers(dest="remote_action", required=True)
    remote_plan = remote_sub.add_parser("plan", help="Write the safe Codee Remote architecture plan.")
    remote_plan.add_argument("path", nargs="?", default=".")
    remote_plan.add_argument("--service", default="codee-remote")
    remote_plan.add_argument("--write", action="store_true")
    remote_plan.add_argument("--force", action="store_true")
    remote_plan.add_argument("--json", action="store_true")
    remote_plan.set_defaults(func=command_remote)
    remote_viewer = remote_sub.add_parser("viewer", help="Write the Codee Remote Viewer phone-to-desktop plan.")
    remote_viewer.add_argument("path", nargs="?", default=".")
    remote_viewer.add_argument("--service", default="codee-remote")
    remote_viewer.add_argument("--write", action="store_true")
    remote_viewer.add_argument("--force", action="store_true")
    remote_viewer.add_argument("--json", action="store_true")
    remote_viewer.set_defaults(func=command_remote)
    remote_bridge = remote_sub.add_parser("bridge", help="Write the Codee Remote CLI bridge allowlist plan.")
    remote_bridge.add_argument("path", nargs="?", default=".")
    remote_bridge.add_argument("--service", default="codee-remote")
    remote_bridge.add_argument("--write", action="store_true")
    remote_bridge.add_argument("--force", action="store_true")
    remote_bridge.add_argument("--json", action="store_true")
    remote_bridge.set_defaults(func=command_remote)
    remote_installer = remote_sub.add_parser("installer", help="Write the Codee Remote installer and host download plan.")
    remote_installer.add_argument("path", nargs="?", default=".")
    remote_installer.add_argument("--service", default="codee-remote")
    remote_installer.add_argument("--write", action="store_true")
    remote_installer.add_argument("--force", action="store_true")
    remote_installer.add_argument("--json", action="store_true")
    remote_installer.set_defaults(func=command_remote)
    remote_host = remote_sub.add_parser("host", help="Write the desktop host skeleton profile and local queue files.")
    remote_host.add_argument("path", nargs="?", default=".")
    remote_host.add_argument("--device-name", default="")
    remote_host.add_argument("--write", action="store_true")
    remote_host.add_argument("--force", action="store_true")
    remote_host.add_argument("--json", action="store_true")
    remote_host.set_defaults(func=command_remote)
    remote_pair = remote_sub.add_parser("pair", help="Create a local pairing packet for a future remote host agent.")
    remote_pair.add_argument("path", nargs="?", default=".")
    remote_pair.add_argument("--device-name", default="")
    remote_pair.add_argument("--service", default="codee-remote")
    remote_pair.add_argument("--expires-minutes", default="10")
    remote_pair.add_argument("--write", action="store_true")
    remote_pair.add_argument("--json", action="store_true")
    remote_pair.set_defaults(func=command_remote)
    remote_session = remote_sub.add_parser("session", help="Create or update a local Codee Remote session packet.")
    remote_session.add_argument("path", nargs="?", default=".")
    remote_session.add_argument("--session-action", default="status", choices=["start", "stop", "status"])
    remote_session.add_argument("--write", action="store_true")
    remote_session.add_argument("--json", action="store_true")
    remote_session.set_defaults(func=command_remote)
    remote_revoke = remote_sub.add_parser("revoke", help="Mark a local remote pairing as revoked.")
    remote_revoke.add_argument("path", nargs="?", default=".")
    remote_revoke.add_argument("--device-id", default="")
    remote_revoke.add_argument("--reason", default="")
    remote_revoke.add_argument("--write", action="store_true")
    remote_revoke.add_argument("--json", action="store_true")
    remote_revoke.set_defaults(func=command_remote)
    remote_security = remote_sub.add_parser("security", help="Write the Codee Remote security review gate.")
    remote_security.add_argument("path", nargs="?", default=".")
    remote_security.add_argument("--write", action="store_true")
    remote_security.add_argument("--force", action="store_true")
    remote_security.add_argument("--json", action="store_true")
    remote_security.set_defaults(func=command_remote)
    remote_demo = remote_sub.add_parser("demo", help="Write the public Codee Remote demo mode packet.")
    remote_demo.add_argument("path", nargs="?", default=".")
    remote_demo.add_argument("--write", action="store_true")
    remote_demo.add_argument("--force", action="store_true")
    remote_demo.add_argument("--json", action="store_true")
    remote_demo.set_defaults(func=command_remote)
    remote_audit = remote_sub.add_parser("audit", help="Summarize Codee Remote events and files.")
    remote_audit.add_argument("path", nargs="?", default=".")
    remote_audit.add_argument("--json", action="store_true")
    remote_audit.set_defaults(func=command_remote)
    remote_readiness = remote_sub.add_parser("readiness", help="Run the Codee Remote readiness gate.")
    remote_readiness.add_argument("path", nargs="?", default=".")
    remote_readiness.add_argument("--write", action="store_true")
    remote_readiness.add_argument("--force", action="store_true")
    remote_readiness.add_argument("--local-only", action="store_true")
    remote_readiness.add_argument("--timeout", default="20")
    remote_readiness.add_argument("--json", action="store_true")
    remote_readiness.set_defaults(func=command_remote)
    remote_status = remote_sub.add_parser("status", help="Show local Codee Remote readiness.")
    remote_status.add_argument("path", nargs="?", default=".")
    remote_status.add_argument("--json", action="store_true")
    remote_status.set_defaults(func=command_remote)

    init = sub.add_parser("init", help="Create a local Codee workspace.")
    init.add_argument("path", nargs="?", default=".")
    init.add_argument("--business", default="Codee Client")
    init.add_argument("--owner", default="Business Owner")
    init.add_argument("--email", default="", help="Optional account email used to create a stable Codee user id.")
    init.add_argument("--client-id", default="")
    init.add_argument("--mission", default="")
    init.add_argument("--force", action="store_true")
    init.set_defaults(func=command_init)

    scan = sub.add_parser("scan", help="Scan routes and fail on 404s.")
    scan.add_argument("path", nargs="?", default=".")
    scan.add_argument("--url", action="append", help="Route to scan. Can be passed more than once.")
    scan.add_argument("--expected", default="200", help="Comma-separated acceptable status codes.")
    scan.add_argument("--timeout", default=str(DEFAULT_ROUTE_TIMEOUT))
    scan.add_argument("--json", action="store_true")
    scan.set_defaults(func=command_scan)

    verify = sub.add_parser("verify", help="Verify a generated Codee service folder before backend activation or launch.")
    verify.add_argument("path", nargs="?", default=".")
    verify.add_argument("--service", default="", help="Service lane, e.g. codeeqr, codeeflyer, codeeflyer250, codeeapp250.")
    verify.add_argument("--business", default="")
    verify.add_argument("--owner", default="")
    verify.add_argument("--email", default="")
    verify.add_argument("--target-url", default="")
    verify.add_argument("--api-base", default=DEFAULT_API_BASE)
    verify.add_argument("--timeout", default="30")
    verify.add_argument("--strict", action="store_true", help="Treat warnings as failures.")
    verify.add_argument("--live", action="store_true", help="Check the saved backend connection through Codee API.")
    verify.add_argument("--route-check", action="store_true", help="Check the target URL route.")
    verify.add_argument("--json", action="store_true")
    verify.set_defaults(func=command_verify)

    money_map = sub.add_parser("money-map", help="Create a first-offer income path and proof checklist.")
    money_map.add_argument("path", nargs="?", default=".")
    money_map.add_argument("--business", default="", help="Override business name from .codee/codee.json.")
    money_map.add_argument("--audience", default="", help="Who the first offer should target.")
    money_map.add_argument("--service", default="", help="The first service to package.")
    money_map.add_argument("--offer", default="", help="Override the generated first-offer sentence.")
    money_map.add_argument("--json", action="store_true")
    money_map.set_defaults(func=command_money_map)

    toolkit = sub.add_parser("toolkit", help="Show the Codee open-source toolkit stack.")
    toolkit.add_argument("--json", action="store_true")
    toolkit.set_defaults(func=command_toolkit)

    folder_plan = sub.add_parser("folder-plan", help="Inspect a service folder and write Codee folder teaching/proof notes.")
    folder_plan.add_argument("path", nargs="?", default=".")
    folder_plan.add_argument("--business", default="")
    folder_plan.add_argument("--service", default="codee-service")
    folder_plan.add_argument("--domain", default="")
    folder_plan.add_argument("--write", action="store_true")
    folder_plan.add_argument("--force", action="store_true")
    folder_plan.add_argument("--json", action="store_true")
    folder_plan.set_defaults(func=command_folder_plan)

    domain_plan = sub.add_parser("domain-plan", help="Create a plain-English DNS, hosting, SSL, and route-proof plan.")
    domain_plan.add_argument("path", nargs="?", default=".")
    domain_plan.add_argument("--business", default="")
    domain_plan.add_argument("--domain", default="")
    domain_plan.add_argument("--target-url", default="")
    domain_plan.add_argument("--registrar", default="GoDaddy")
    domain_plan.add_argument("--hosting", default="Codee hosting")
    domain_plan.add_argument("--timeout", default="20")
    domain_plan.add_argument("--no-scan", action="store_true")
    domain_plan.add_argument("--write", action="store_true")
    domain_plan.add_argument("--force", action="store_true")
    domain_plan.add_argument("--json", action="store_true")
    domain_plan.set_defaults(func=command_domain_plan)

    admin_training = sub.add_parser("admin-training", help="Show or write the Codee admin platform and tier training playbook.")
    admin_training.add_argument("path", nargs="?", default=".")
    admin_training.add_argument("--write", action="store_true", help="Write .codee/admin-training.json and .codee/ADMIN_TRAINING.md.")
    admin_training.add_argument("--force", action="store_true")
    admin_training.add_argument("--json", action="store_true")
    admin_training.set_defaults(func=command_admin_training)

    admin_guidebook = sub.add_parser("admin-guidebook", help="Owner/internal guidebook generator.")
    admin_guidebook.add_argument("path", nargs="?", default=".")
    admin_guidebook.add_argument("--write", action="store_true", help="Write .codee/admin-guidebook.json and .codee/ADMIN_GUIDEBOOK.md.")
    admin_guidebook.add_argument("--force", action="store_true")
    admin_guidebook.add_argument("--json", action="store_true")
    admin_guidebook.set_defaults(func=command_admin_guidebook)
    sub._choices_actions = [item for item in sub._choices_actions if getattr(item, "dest", "") != "admin-guidebook"]

    admin_certify = sub.add_parser("admin-certify", help="Certify a Codee admin workspace with local and live proof checks.")
    admin_certify.add_argument("path", nargs="?", default=".")
    admin_certify.add_argument("--url", action="append", help="Extra live URL to include in certification. Can be passed more than once.")
    admin_certify.add_argument("--timeout", default="30")
    admin_certify.add_argument("--local-only", action="store_true")
    admin_certify.add_argument("--json", action="store_true")
    admin_certify.set_defaults(func=command_admin_certify)

    business_types = sub.add_parser("business-types", help="List Codee business-type assistant templates.")
    business_types.add_argument("--json", action="store_true")
    business_types.set_defaults(func=command_business_types)

    business_assistant = sub.add_parser("business-assistant-init", help="Create a Codee assistant template for one business type.")
    business_assistant.add_argument("path", nargs="?", default="./codee-business-assistant")
    business_assistant.add_argument("--business-type", required=True, choices=[str(item["id"]) for item in BUSINESS_ASSISTANT_TYPES])
    business_assistant.add_argument("--business", default="")
    business_assistant.add_argument("--owner", default="Business Owner")
    business_assistant.add_argument("--email", default="")
    business_assistant.add_argument("--client-id", default="")
    business_assistant.add_argument("--force", action="store_true")
    business_assistant.add_argument("--json", action="store_true")
    business_assistant.set_defaults(func=command_business_assistant_init)

    toolkit_init = sub.add_parser("toolkit-init", help="Create a full Codee open-source toolkit workspace.")
    toolkit_init.add_argument("path", nargs="?", default="./codee-open-source-toolkit")
    toolkit_init.add_argument("--business", default="My Business")
    toolkit_init.add_argument("--owner", default="Business Owner")
    toolkit_init.add_argument("--email", default="")
    toolkit_init.add_argument("--client-id", default="")
    toolkit_init.add_argument("--target-base", default=f"{DEFAULT_API_BASE}/index2income")
    toolkit_init.add_argument("--preset", default="operator", choices=["public", "operator", "owner"])
    toolkit_init.add_argument("--force", action="store_true")
    toolkit_init.add_argument("--json", action="store_true")
    toolkit_init.set_defaults(func=command_toolkit_init)

    toolkit_smoke = sub.add_parser("toolkit-smoke", help="Validate a Codee toolkit workspace.")
    toolkit_smoke.add_argument("path", nargs="?", default="./codee-open-source-toolkit")
    toolkit_smoke.add_argument("--timeout", default="30")
    toolkit_smoke.add_argument("--local-only", action="store_true")
    toolkit_smoke.add_argument("--json", action="store_true")
    toolkit_smoke.set_defaults(func=command_toolkit_smoke)

    courses = sub.add_parser("courses", help="List Codee open-source courses and advanced service-course lanes.")
    courses.add_argument("--json", action="store_true")
    courses.set_defaults(func=command_courses)

    contracts = sub.add_parser("contracts", help="Print or write Codee service contracts used by Codee Chat and Codee CLI.")
    contracts.add_argument("path", nargs="?", default=".")
    contracts.add_argument("--service", default="", help="Optional service lane, e.g. codeeqr, codeeflyer250, codeeapp250.")
    contracts.add_argument("--write", action="store_true", help="Write the contract payload under .codee/.")
    contracts.add_argument("--force", action="store_true")
    contracts.add_argument("--json", action="store_true")
    contracts.set_defaults(func=command_contracts)

    course_init = sub.add_parser("course-init", help="Create a starter folder for a Codee open-source course.")
    course_init.add_argument("path", nargs="?", default=".")
    course_init.add_argument("--course", required=True, choices=["qrcodee", "codeeflyer", "codeeapp"], help="Core course id to scaffold.")
    course_init.add_argument("--business", default="My Business")
    course_init.add_argument("--target-url", default="https://codee.chat")
    course_init.add_argument("--force", action="store_true")
    course_init.add_argument("--json", action="store_true")
    course_init.set_defaults(func=command_course_init)

    loops = sub.add_parser("loops", help="List Codee agent loops and required proof files.")
    loops.add_argument("--live", action="store_true", help="Fetch the hosted Codee loop command-center report.")
    loops.add_argument("--proof-scan", action="store_true", help="Run a hosted loop proof pass and print queue buckets.")
    loops.add_argument("--client-id", default="aik9-metri")
    loops.add_argument("--api-base", default=DEFAULT_API_BASE)
    loops.add_argument("--timeout", default="30")
    loops.add_argument("--json", action="store_true")
    loops.set_defaults(func=command_loops)

    heartbeat = sub.add_parser("heartbeat", help="Show a Codee workspace pulse with identity, proof, task status, routes, and next steps.")
    heartbeat.add_argument("path", nargs="?", default=".")
    heartbeat.add_argument("--service", default="codee-support")
    heartbeat.add_argument("--business", default="")
    heartbeat.add_argument("--url", action="append", help="Live route to check. Can be passed more than once.")
    heartbeat.add_argument("--task-id", default="", help="Optional Codee task id to check when --live is used.")
    heartbeat.add_argument("--live", action="store_true", help="Fetch live task status from Codee backend.")
    heartbeat.add_argument("--api-base", default=DEFAULT_API_BASE)
    heartbeat.add_argument("--timeout", default="20")
    heartbeat.add_argument("--count", default="1", help="Number of heartbeat pulses to run, up to 60.")
    heartbeat.add_argument("--interval", default="30", help="Seconds between heartbeat pulses when --count is greater than 1.")
    heartbeat.add_argument("--json", action="store_true")
    heartbeat.set_defaults(func=command_heartbeat)

    agent_core = sub.add_parser("agent-core", aliases=["agi"], help="Install or inspect Codee's governed AGI-style agent core.")
    agent_core.add_argument("path", nargs="?", default=".")
    agent_core.add_argument("--business", default="")
    agent_core.add_argument("--service", default="codee-service")
    agent_core.add_argument("--mode", default="suggest", choices=[str(item["id"]) for item in CODEE_PERMISSION_MODES])
    agent_core.add_argument("--api-base", default=DEFAULT_API_BASE)
    agent_core.add_argument("--write", action="store_true")
    agent_core.add_argument("--force", action="store_true")
    agent_core.add_argument("--json", action="store_true")
    agent_core.set_defaults(func=command_agent_core)

    skills = sub.add_parser("skills", help="List Codee built-in, optional, owner, and backend skills.")
    skills.add_argument("--access", default="public", choices=["public", "owner", "all"], help="Skill visibility filter.")
    skills.add_argument("--json", action="store_true")
    skills.set_defaults(func=command_skills)

    skill_check = sub.add_parser("skill-check", help="Check whether local tools for a Codee skill are available.")
    skill_check.add_argument("skill", nargs="?", default="all", help="Skill id or all.")
    skill_check.add_argument("path", nargs="?", default=".")
    skill_check.add_argument("--json", action="store_true")
    skill_check.set_defaults(func=command_skill_check)

    skill_policy = sub.add_parser("skill-policy", help="Write a workspace skill policy manifest and markdown guardrail file.")
    skill_policy.add_argument("path", nargs="?", default=".")
    skill_policy.add_argument("--preset", default="public", choices=["public", "operator", "owner"], help="Policy preset.")
    skill_policy.add_argument("--enable", action="append", help="Enable an extra skill id. Can be passed more than once.")
    skill_policy.add_argument("--disable", action="append", help="Disable a skill id. Can be passed more than once.")
    skill_policy.add_argument("--force", action="store_true")
    skill_policy.add_argument("--json", action="store_true")
    skill_policy.set_defaults(func=command_skill_policy)

    browser_scan = sub.add_parser("browser-scan", help="Run a public route check and optional Playwright screenshot proof.")
    browser_scan.add_argument("path", nargs="?", default=".")
    browser_scan.add_argument("--url", required=True)
    browser_scan.add_argument("--expected", default="200", help="Comma-separated acceptable status codes.")
    browser_scan.add_argument("--timeout", default="30")
    browser_scan.add_argument("--screenshot", default="", help="Optional screenshot output path.")
    browser_scan.add_argument("--full-page", action="store_true")
    browser_scan.add_argument("--no-screenshot", action="store_true", help="Only run the HTTP route check.")
    browser_scan.add_argument("--json", action="store_true")
    browser_scan.set_defaults(func=command_browser_scan)

    course_smoke = sub.add_parser("course-smoke", help="Smoke test the Codee open-source course suite.")
    course_smoke.add_argument("path", nargs="?", default="", help="Optional local course folder to validate.")
    course_smoke.add_argument("--api-base", default=DEFAULT_API_BASE)
    course_smoke.add_argument("--timeout", default="30")
    course_smoke.add_argument("--json", action="store_true")
    course_smoke.set_defaults(func=command_course_smoke)

    pricing = sub.add_parser("pricing", help="Show Codee CLI upgrade plans.")
    pricing.add_argument("--api-base", default=DEFAULT_API_BASE)
    pricing.add_argument("--timeout", default="30")
    pricing.add_argument("--local", action="store_true", help="Use the bundled local pricing table.")
    pricing.add_argument("--json", action="store_true")
    pricing.set_defaults(func=command_pricing)

    upgrade = sub.add_parser("upgrade", help="Create a Stripe-hosted checkout link for a Codee CLI plan.")
    upgrade.add_argument("path", nargs="?", default=".")
    upgrade.add_argument("--plan", default="pro", help="Plan id: pro, partner, or business-suite.")
    upgrade.add_argument("--email", required=True)
    upgrade.add_argument("--business", default="")
    upgrade.add_argument("--owner", default="")
    upgrade.add_argument("--ref", default="codee-cli")
    upgrade.add_argument("--api-base", default=DEFAULT_API_BASE)
    upgrade.add_argument("--timeout", default="30")
    upgrade.add_argument("--dry-run", action="store_true")
    upgrade.add_argument("--open", action="store_true", help="Open the Stripe-hosted checkout URL in the default browser.")
    upgrade.set_defaults(func=command_upgrade)

    invoice = sub.add_parser("invoice", help="Create a Stripe-hosted invoice for invoice-supported plans.")
    invoice.add_argument("path", nargs="?", default=".")
    invoice.add_argument("--plan", default="business-suite", help="Invoice-supported plan id.")
    invoice.add_argument("--email", required=True)
    invoice.add_argument("--business", default="")
    invoice.add_argument("--owner", default="")
    invoice.add_argument("--ref", default="codee-cli-invoice")
    invoice.add_argument("--days-until-due", default="7")
    invoice.add_argument("--api-base", default=DEFAULT_API_BASE)
    invoice.add_argument("--timeout", default="30")
    invoice.add_argument("--dry-run", action="store_true")
    invoice.add_argument("--open", action="store_true", help="Open the Stripe-hosted invoice URL in the default browser.")
    invoice.set_defaults(func=command_invoice)

    license_cmd = sub.add_parser("license", help="Check or save a local Codee CLI license proof.")
    license_cmd.add_argument("path", nargs="?", default=".")
    license_cmd.add_argument("--session-id", default="")
    license_cmd.add_argument("--invoice-id", default="")
    license_cmd.add_argument("--api-base", default=DEFAULT_API_BASE)
    license_cmd.add_argument("--timeout", default="30")
    license_cmd.add_argument("--save-unpaid", action="store_true")
    license_cmd.add_argument("--json", action="store_true")
    license_cmd.set_defaults(func=command_license)

    client = sub.add_parser("client", help="Create a chat-style client intake packet with preview paywall, Stripe unlock, and optional WordPress/Google connect guidance.")
    client.add_argument("path", nargs="?", default=".")
    client.add_argument("--service", default="", help="Service lane, e.g. codeeqr, codeeflyer100, codeeflyer250, codeeapp250.")
    client.add_argument("--business", default="")
    client.add_argument("--owner", default="")
    client.add_argument("--email", default="")
    client.add_argument("--target-url", default="")
    client.add_argument("--goal", default="")
    client.add_argument("--connect-wordpress", action="store_true", help="Include WordPress draft connector questions and secure handoff links.")
    client.add_argument("--wordpress-site", default="", help="Client WordPress site URL for probe/connect planning.")
    client.add_argument("--connect-google", action="store_true", help="Include temporary Google Drive/Gmail OAuth handoff links.")
    client.add_argument("--drive-folder", default="", help="Client Drive folder URL for asset organization or cleanup planning.")
    client.add_argument("--gmail-query", default="", help="Gmail search query for temporary inbox help, e.g. newer_than:30d.")
    client.add_argument("--ask", action="store_true", help="Ask for missing fields in the terminal.")
    client.add_argument("--submit", action="store_true", help="Submit the client intake to Codee backend and receive preview/checkout links.")
    client.add_argument("--dry-run", action="store_true")
    client.add_argument("--api-base", default=DEFAULT_API_BASE)
    client.add_argument("--api-fallback-base", action="append", default=[], help="Extra Codee API base to try if submit hits DNS, timeout, or 5xx transport failure.")
    client.add_argument("--timeout", default="30")
    client.add_argument("--json", action="store_true")
    client.set_defaults(func=command_client)

    connect = sub.add_parser("connect", help="Register this local folder with Codee backend without unlocking hosted delivery until payment.")
    connect.add_argument("path", nargs="?", default=".")
    connect.add_argument("--service", default="", help="Service lane, e.g. codeeqr, codeeflyer, codeeapp250.")
    connect.add_argument("--business", default="")
    connect.add_argument("--owner", default="")
    connect.add_argument("--email", default="")
    connect.add_argument("--target-url", default="")
    connect.add_argument("--connect-wordpress", action="store_true", help="Attach a WordPress connector request to this backend connection.")
    connect.add_argument("--wordpress-site", default="", help="Client WordPress site URL for guided connect.")
    connect.add_argument("--connect-google", action="store_true", help="Attach a temporary Google Drive/Gmail connector request to this backend connection.")
    connect.add_argument("--drive-folder", default="", help="Client Google Drive folder URL.")
    connect.add_argument("--gmail-query", default="", help="Client Gmail search query for temporary inbox help.")
    connect.add_argument("--api-base", default=DEFAULT_API_BASE)
    connect.add_argument("--timeout", default="30")
    connect.add_argument("--dry-run", action="store_true")
    connect.add_argument("--open", action="store_true")
    connect.add_argument("--json", action="store_true")
    connect.set_defaults(func=command_connect)

    activate = sub.add_parser("activate", help="Ask Codee backend for the locked activation path for a generated course/client site.")
    activate.add_argument("path", nargs="?", default=".")
    activate.add_argument("--service", default="", help="Service lane, e.g. codeeqr, codeeflyer, codeeapp250.")
    activate.add_argument("--plan", default="single-lane-hosting")
    activate.add_argument("--business", default="")
    activate.add_argument("--owner", default="")
    activate.add_argument("--email", default="")
    activate.add_argument("--target-url", default="")
    activate.add_argument("--connection-id", default="")
    activate.add_argument("--activation-token", default="")
    activate.add_argument("--checkout-session-id", default="")
    activate.add_argument("--invoice-id", default="")
    activate.add_argument("--api-base", default=DEFAULT_API_BASE)
    activate.add_argument("--timeout", default="30")
    activate.add_argument("--dry-run", action="store_true")
    activate.add_argument("--open", action="store_true")
    activate.add_argument("--json", action="store_true")
    activate.set_defaults(func=command_activate)

    hooks = sub.add_parser("hooks", help="List or write safe Codee lifecycle hook events for this workspace.")
    hooks.add_argument("path", nargs="?", default=".")
    hooks.add_argument("--write", action="store_true")
    hooks.add_argument("--force", action="store_true")
    hooks.add_argument("--json", action="store_true")
    hooks.set_defaults(func=command_hooks)

    connectors = sub.add_parser("connectors", help="List or write the Codee connector registry for this workspace.")
    connectors.add_argument("path", nargs="?", default=".")
    connectors.add_argument("--write", action="store_true")
    connectors.add_argument("--force", action="store_true")
    connectors.add_argument("--public-only", action="store_true")
    connectors.add_argument("--json", action="store_true")
    connectors.set_defaults(func=command_connectors)

    platform = sub.add_parser("platform", help="Write the Codex/Claude-inspired Codee platform layer into a workspace.")
    platform.add_argument("path", nargs="?", default=".")
    platform.add_argument("--mode", default="suggest", choices=[str(item["id"]) for item in CODEE_PERMISSION_MODES])
    platform.add_argument("--business", default="")
    platform.add_argument("--service", default="codee-service")
    platform.add_argument("--api-base", default=DEFAULT_API_BASE)
    platform.add_argument("--write", action="store_true")
    platform.add_argument("--force", action="store_true")
    platform.add_argument("--json", action="store_true")
    platform.set_defaults(func=command_platform)

    permissions = sub.add_parser("permissions", help="List or write Codee permission modes for a workspace.")
    permissions.add_argument("path", nargs="?", default=".")
    permissions.add_argument("--mode", default="suggest", choices=[str(item["id"]) for item in CODEE_PERMISSION_MODES])
    permissions.add_argument("--write", action="store_true")
    permissions.add_argument("--force", action="store_true")
    permissions.add_argument("--json", action="store_true")
    permissions.set_defaults(func=command_permissions)

    agents = sub.add_parser("agents", help="List or write Codee focused agent profiles for a workspace.")
    agents.add_argument("path", nargs="?", default=".")
    agents.add_argument("--mode", default="suggest", choices=[str(item["id"]) for item in CODEE_PERMISSION_MODES])
    agents.add_argument("--write", action="store_true")
    agents.add_argument("--force", action="store_true")
    agents.add_argument("--json", action="store_true")
    agents.set_defaults(func=command_agents)

    memory = sub.add_parser("memory", help="Write CODEE.md, AGENTS.md, and Codee project memory/rules.")
    memory.add_argument("path", nargs="?", default=".")
    memory.add_argument("--business", default="")
    memory.add_argument("--service", default="codee-service")
    memory.add_argument("--mode", default="suggest", choices=[str(item["id"]) for item in CODEE_PERMISSION_MODES])
    memory.add_argument("--write", action="store_true")
    memory.add_argument("--force", action="store_true")
    memory.add_argument("--json", action="store_true")
    memory.set_defaults(func=command_memory)

    memory_vault = sub.add_parser("memory-vault", aliases=["remember"], help="Manage each Codee user's local-first long-term memory vault.")
    memory_vault_sub = memory_vault.add_subparsers(dest="memory_action", required=True)

    memory_vault_init = memory_vault_sub.add_parser("init", help="Initialize the user-scoped memory vault.")
    memory_vault_init.add_argument("path", nargs="?", default=".")
    memory_vault_init.add_argument("--business", default="")
    memory_vault_init.add_argument("--owner", default="")
    memory_vault_init.add_argument("--email", default="")
    memory_vault_init.add_argument("--service", default="codee-service")
    memory_vault_init.add_argument("--force", action="store_true")
    memory_vault_init.add_argument("--json", action="store_true")
    memory_vault_init.set_defaults(func=command_memory_vault)

    memory_vault_add = memory_vault_sub.add_parser("add", help="Save a user-specific memory record.")
    memory_vault_add.add_argument("path", nargs="?", default=".")
    memory_vault_add.add_argument("--text", required=True)
    memory_vault_add.add_argument("--kind", default="note")
    memory_vault_add.add_argument("--service", default="codee-service")
    memory_vault_add.add_argument("--business", default="")
    memory_vault_add.add_argument("--owner", default="")
    memory_vault_add.add_argument("--email", default="")
    memory_vault_add.add_argument("--tag", action="append")
    memory_vault_add.add_argument("--importance", default="normal")
    memory_vault_add.add_argument("--source", default="codee-cli")
    memory_vault_add.add_argument("--json", action="store_true")
    memory_vault_add.set_defaults(func=command_memory_vault)

    memory_vault_search = memory_vault_sub.add_parser("search", help="Search the user memory vault.")
    memory_vault_search.add_argument("path", nargs="?", default=".")
    memory_vault_search.add_argument("--query", required=True)
    memory_vault_search.add_argument("--service", default="codee-service")
    memory_vault_search.add_argument("--limit", default="10")
    memory_vault_search.add_argument("--json", action="store_true")
    memory_vault_search.set_defaults(func=command_memory_vault)

    memory_vault_recall = memory_vault_sub.add_parser("recall", help="Alias-style recall search for user memory.")
    memory_vault_recall.add_argument("path", nargs="?", default=".")
    memory_vault_recall.add_argument("--query", required=True)
    memory_vault_recall.add_argument("--service", default="codee-service")
    memory_vault_recall.add_argument("--limit", default="10")
    memory_vault_recall.add_argument("--json", action="store_true")
    memory_vault_recall.set_defaults(func=command_memory_vault)

    memory_vault_list = memory_vault_sub.add_parser("list", help="List recent user memories.")
    memory_vault_list.add_argument("path", nargs="?", default=".")
    memory_vault_list.add_argument("--service", default="codee-service")
    memory_vault_list.add_argument("--limit", default="10")
    memory_vault_list.add_argument("--json", action="store_true")
    memory_vault_list.set_defaults(func=command_memory_vault)

    memory_vault_export = memory_vault_sub.add_parser("export", help="Export the user memory vault to JSON.")
    memory_vault_export.add_argument("path", nargs="?", default=".")
    memory_vault_export.add_argument("--service", default="codee-service")
    memory_vault_export.add_argument("--output", default="")
    memory_vault_export.add_argument("--json", action="store_true")
    memory_vault_export.set_defaults(func=command_memory_vault)

    accessibility = sub.add_parser("accessibility", help="Write veteran-first accessibility rules for Codee courses and workspaces.")
    accessibility.add_argument("path", nargs="?", default=".")
    accessibility.add_argument("--business", default="")
    accessibility.add_argument("--service", default="codee-service")
    accessibility.add_argument("--write", action="store_true")
    accessibility.add_argument("--force", action="store_true")
    accessibility.add_argument("--json", action="store_true")
    accessibility.set_defaults(func=command_accessibility)

    mcp = sub.add_parser("mcp", help="List or write the Codee MCP-style connector blueprint.")
    mcp.add_argument("path", nargs="?", default=".")
    mcp.add_argument("--api-base", default=DEFAULT_API_BASE)
    mcp.add_argument("--public-only", action="store_true")
    mcp.add_argument("--write", action="store_true")
    mcp.add_argument("--force", action="store_true")
    mcp.add_argument("--json", action="store_true")
    mcp.set_defaults(func=command_mcp)

    task = sub.add_parser("task", help="Create, send, run, inspect, or finish a Codee task thread.")
    task_sub = task.add_subparsers(dest="task_action", required=True)
    task_create = task_sub.add_parser("create", help="Create a local Codee task thread.")
    task_create.add_argument("path", nargs="?", default=".")
    task_create.add_argument("--title", required=True)
    task_create.add_argument("--prompt", required=True)
    task_create.add_argument("--service", default="codee-cli")
    task_create.add_argument("--agent", default="builder")
    task_create.add_argument("--priority", default="normal")
    task_create.add_argument("--mode", default="suggest", choices=[str(item["id"]) for item in CODEE_PERMISSION_MODES])
    task_create.add_argument("--business", default="")
    task_create.add_argument("--owner", default="")
    task_create.add_argument("--email", default="")
    task_create.add_argument("--api-base", default=DEFAULT_API_BASE)
    task_create.add_argument("--timeout", default="30")
    task_create.add_argument("--send", action="store_true")
    task_create.add_argument("--json", action="store_true")
    task_create.set_defaults(func=command_task)

    task_list = task_sub.add_parser("list", help="List local Codee task threads.")
    task_list.add_argument("path", nargs="?", default=".")
    task_list.add_argument("--json", action="store_true")
    task_list.set_defaults(func=command_task)

    task_status = task_sub.add_parser("status", help="Show a task thread status.")
    task_status.add_argument("path", nargs="?", default=".")
    task_status.add_argument("--task-id", required=True)
    task_status.add_argument("--api-base", default=DEFAULT_API_BASE)
    task_status.add_argument("--timeout", default="30")
    task_status.add_argument("--live", action="store_true")
    task_status.add_argument("--json", action="store_true")
    task_status.set_defaults(func=command_task)

    task_send = task_sub.add_parser("send", help="Send a local Codee task thread to Codee backend.")
    task_send.add_argument("path", nargs="?", default=".")
    task_send.add_argument("--task-id", required=True)
    task_send.add_argument("--api-base", default=DEFAULT_API_BASE)
    task_send.add_argument("--timeout", default="30")
    task_send.add_argument("--json", action="store_true")
    task_send.set_defaults(func=command_task)

    task_run = task_sub.add_parser("run", help="Run local task proof checks and optionally send the result to Codee backend.")
    task_run.add_argument("path", nargs="?", default=".")
    task_run.add_argument("--task-id", required=True)
    task_run.add_argument("--mode", default="suggest", choices=[str(item["id"]) for item in CODEE_PERMISSION_MODES])
    task_run.add_argument("--target-url", default="")
    task_run.add_argument("--url", action="append", help="Route to check. Can be passed more than once.")
    task_run.add_argument("--route-check", action="store_true")
    task_run.add_argument("--strict", action="store_true")
    task_run.add_argument("--write-platform", action="store_true", help="Install/update the platform files before proof checks.")
    task_run.add_argument("--force", action="store_true")
    task_run.add_argument("--send-result", action="store_true", help="Send the run report back to Codee backend.")
    task_run.add_argument("--api-base", default=DEFAULT_API_BASE)
    task_run.add_argument("--timeout", default="30")
    task_run.add_argument("--json", action="store_true")
    task_run.set_defaults(func=command_task)

    task_result = task_sub.add_parser("result", help="Read or save the result for a Codee task thread.")
    task_result.add_argument("path", nargs="?", default=".")
    task_result.add_argument("--task-id", required=True)
    task_result.add_argument("--result", default="")
    task_result.add_argument("--json", action="store_true")
    task_result.set_defaults(func=command_task)

    room = sub.add_parser("room", aliases=["delivery"], help="Show the client's Codee delivery/support room URL.")
    room.add_argument("path", nargs="?", default=".")
    room.add_argument("--service", default="codee-support")
    room.add_argument("--url", default="", help="Override the generated room URL.")
    room.add_argument("--open", action="store_true")
    room.add_argument("--json", action="store_true")
    room.set_defaults(func=command_room)

    account = sub.add_parser("account", aliases=["whoami"], help="Show the local Codee user, workspace, delivery room, and latest proof.")
    account.add_argument("path", nargs="?", default=".")
    account.add_argument("--service", default="codee-support")
    account.add_argument("--email", default="", help="Optional email fallback when the workspace has no owner email.")
    account.add_argument("--open", action="store_true", help="Open the Codee workbench for this workspace.")
    account.add_argument("--json", action="store_true")
    account.set_defaults(func=command_account)

    workbench = sub.add_parser("workbench", help="Show the Codee hosted workbench URL for this workspace.")
    workbench.add_argument("path", nargs="?", default=".")
    workbench.add_argument("--service", default="codee-support")
    workbench.add_argument("--url", default="", help="Override the generated workbench URL.")
    workbench.add_argument("--open", action="store_true")
    workbench.add_argument("--json", action="store_true")
    workbench.set_defaults(func=command_workbench)

    support = sub.add_parser("support", help="Create or submit a Codee support update request.")
    support.add_argument("path", nargs="?", default=".")
    support.add_argument("--service", default="codee-support")
    support.add_argument("--type", default="site-update", help="Request type: site-update, link-update, image-update, copy-update, payment-path, or scan.")
    support.add_argument("--title", default="")
    support.add_argument("--message", required=True)
    support.add_argument("--route", default="")
    support.add_argument("--attachment", action="append", help="File path or public URL to attach. Can be passed more than once.")
    support.add_argument("--priority", default="normal")
    support.add_argument("--email", default="")
    support.add_argument("--business", default="")
    support.add_argument("--owner", default="")
    support.add_argument("--delivery-room-url", default="")
    support.add_argument("--api-base", default=DEFAULT_API_BASE)
    support.add_argument("--timeout", default="30")
    support.add_argument("--submit", action="store_true", help="Send the request to Codee backend.")
    support.add_argument("--dry-run", action="store_true")
    support.add_argument("--open", action="store_true")
    support.add_argument("--json", action="store_true")
    support.set_defaults(func=command_support)

    doctor = sub.add_parser("doctor", help="Check a Codee workspace.")
    doctor.add_argument("path", nargs="?", default=".")
    doctor.add_argument("--timeout", default="20")
    doctor.add_argument("--local-only", action="store_true")
    doctor.add_argument("--json", action="store_true")
    doctor.set_defaults(func=command_doctor)
    return parser


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)
    exit_code = int(args.func(args))
    _record_command_state(args, exit_code)
    _print_codee_recommendations(args, exit_code)
    return exit_code


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
