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

import argparse
import base64
import datetime as dt
import html
import hashlib
import hmac
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

import re as _re


VERSION = "2026.08.30-remote-browser-bridge-v7"
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_BACKEND_API_BASE = os.getenv("CODEE_BACKEND_API_BASE", "https://ai-k9-codee-digiapp-437923042920.us-central1.run.app").rstrip("/")
CODEE_DOWNLOAD_URL = f"{DEFAULT_API_BASE}/api/downloads/codee-cli.py"
CODEE_ORIGIN_DOWNLOAD_URL = "https://storage.googleapis.com/clients.codee.chat/assets/downloads/codee-cli-20260830-remote-browser-bridge-v7.py"
CODEE_ALPHA_PACK_URL = f"{DEFAULT_API_BASE}/aik9-codee-alpha-pack-intelligence.html"
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_PUBLIC_CATALOG_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-public-catalog.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"
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}/api/remote/viewer"
CODEE_REMOTE_CLI_URL = f"{DEFAULT_API_BASE}/codee-remote-cli.html"
CODEE_REMOTE_INSTALLER_URL = f"{DEFAULT_API_BASE}/api/remote/installer"
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_OWNER_CLI_URL = f"{DEFAULT_API_BASE}/codee-owner-cli.html"
CODEE_OWNER_CLI_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-owner-cli.json"
CODEE_SOCIAL_CONNECT_URL = f"{DEFAULT_API_BASE}/client-connect/"
CODEE_OWNER_DEV_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-owner-dev.json"
CODEE_CODEX_BRIDGE_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-codex-bridge.json"
CODEE_CODEX_PARITY_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-codex-parity.json"
CODEE_PROMOTION_GREENLIGHT_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-promotion-greenlight.json"
CODEE_HEEL_TEACHER_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-heel-teacher.json"
CODEE_HEAL_TEACHER_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-heal-teacher.json"
CODEE_AUDIT_LADDER_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-audit-ladder.json"
CODEE_CHAT_SERVICES_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-chat-services.json"
CODEE_VETERAN_MISSION_QRCODEE_URL = f"{DEFAULT_API_BASE}/veteran-qrcodee.html"
CODEE_VETERAN_MISSION_QRCODEE_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/veteran-mission-qrcodee.json"
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"
CODEE_HUMAN_PROOF_URL = f"{DEFAULT_API_BASE}/codee-human-proof.html"
CODEE_HUMAN_PROOF_MANIFEST_URL = f"{DEFAULT_API_BASE}/assets/codee/codee-human-proof.json"
CODEE_LIVE_PROOF_PROMO_CODE = ""
CODEE_SUPPORT_WINDOW_DAYS = 30
CODEE_RENEWAL_REMINDER_DAY = 25
CODEE_RELEASE_RSA_MODULUS = int(
    "CA3FE6BCED31CB935222FEA52D28277E7B96C8531AF3222DCBA76C84E15F5D2BF83C408AF226D9694267D037FA1710860BE55E7CF9CA1E536EAD9503C90107E841E2951DA2F66AE3AF75DA20E7D61401CF02F71A882C31CB518D293228437834ACF90146AD73161BF916E30DDC8EACFAD153C6B7AE9AF5AE8BA911E74B297F06D851B4F0939E372F4A083F088D4BD2B10D05B48F2347BADE72245AE23477359FA416C2CE1CE9A9A9301EEFABC2647713FDED9F156EB86B40F4D1385F0DA425FA86612EDF6F09F76178A6D4DBD44ED2F6A18BD2A0A6B41B7E9751F80B5125BCC3273A8A3A8B6382AF05C0DADA7564A248DB3909D93FFA5C839DEB767C4FA142DCBEAAEAB6D031ED54389EBDA3EF327CC0036EA57BCDD3233B26BC6E2836C9AA1CB8DA219B4BB380A401B847A6C9A27A4709A8829561652F1A9A1EBB439D0CAF4213E6A1AF3FEBB7F22A0A92289652F7275CCFD93A566637815D20B87B1BE527CDB10EBCEECE5ED3AFAEA07F04E8E2E5ADC18F0A65209387CC8A7C73238F73EE51",
    16,
)
CODEE_RELEASE_RSA_EXPONENT = 65537

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"}


def _normalize_cli_argv(argv: list[str]) -> list[str]:
    normalized = [str(item) for item in (argv or []) if str(item)]
    if normalized and Path(normalized[0]).name in {"codee", "codee.py", "codee_cli.py", "codee-cli"}:
        normalized = normalized[1:]
    if not normalized:
        return normalized
    first = str(normalized[0]).strip()
    if not first or first.startswith("-"):
        return normalized
    if first.startswith("(") and first.endswith(")") and len(first) > 2:
        first = first[1:-1].strip()
    if first.startswith("/") and len(first) > 1:
        first = first[1:].strip()
    if first.startswith(":") and len(first) > 1:
        first = first[1:].strip()
    return [first.lower(), *normalized[1:]]

def _nlu_interpret(text: str) -> dict:
    t = (text or "").strip()
    lt = t.lower()
    intent = None
    params: dict[str, str] = {}

    # URL detection
    url_m = _re.search(r"https?://[^\s]+", t)
    if url_m:
        params['url'] = url_m.group(0)

    # Stripe rotate/add/remove
    if _re.search(r"\brotate\b.*\bstripe\b|\brotate\b.*\bkey\b", lt):
        intent = 'stripe_rotate'
        # try to capture a key name
        m = _re.search(r"(?:key|stripe)[\s:_-]*([a-z0-9_\-]+)", lt)
        if m:
            params['key_name'] = m.group(1)
        else:
            params['key_name'] = 'stripe_live'
        return {'intent': intent, 'params': params, 'text': t}

    if _re.search(r"\badd\b.*\bstripe\b|\badd key\b|\bcreate key\b", lt):
        intent = 'stripe_add'
        m = _re.search(r"--name\s+([a-z0-9_\-]+)", t)
        if m: params['key_name'] = m.group(1)
        return {'intent': intent, 'params': params, 'text': t}

    if _re.search(r"\bremove\b.*\bstripe\b|\bdelete key\b|\brm key\b", lt):
        intent = 'stripe_remove'
        m = _re.search(r"--name\s+([a-z0-9_\-]+)", t)
        if m: params['key_name'] = m.group(1)
        return {'intent': intent, 'params': params, 'text': t}

    # Audit
    if _re.search(r"\baudit\b|site audit|readiness|score", lt):
        intent = 'run_audit'
        if 'url' not in params:
            m = _re.search(r"([\w\-]+\.[a-z]{2,6}(?:/[^\s]*)?)", t)
            if m: params['url'] = m.group(0)
        return {'intent': intent, 'params': params, 'text': t}

    # Flyers
    if _re.search(r"\bflyer\b", lt):
        intent = 'create_flyer'
        # tier detection
        if _re.search(r"\b300\b|\b250\b|premium|advanced|ai[- ]generated", lt): params['tier'] = '300'
        else: params['tier'] = '100'
        # name and cashapp extraction
        name_m = _re.search(r"for\s+([\w\s'\-]+)\s*(?:\$|cash.app|$)", t, _re.I)
        if name_m: params['owner_name'] = name_m.group(1).strip()
        cash_m = _re.search(r"\$[a-zA-Z0-9_\-]+|cash.app/([a-zA-Z0-9_\-]+)", t)
        if cash_m:
            params['cashapp'] = cash_m.group(0) if cash_m.group(0).startswith('$') else ('$' + cash_m.group(1))
        return {'intent': intent, 'params': params, 'text': t}

    # Veteran flyer explicit
    if _re.search(r"veteran", lt) and _re.search(r"flyer|support|cashapp|cash app|tag", lt):
        intent = 'veteran_flyer'
        name_m = _re.search(r"for\s+([\w\s'\-]+)", t, _re.I)
        if name_m: params['name'] = name_m.group(1).strip()
        cash_m = _re.search(r"\$[a-zA-Z0-9_\-]+|cash.app/([a-zA-Z0-9_\-]+)", t)
        if cash_m:
            params['cashapp'] = cash_m.group(0) if cash_m.group(0).startswith('$') else ('$' + cash_m.group(1))
        return {'intent': intent, 'params': params, 'text': t}

    # Deploy
    if _re.search(r"\bdeploy\b|publish site|push site|serve site", lt):
        intent = 'deploy_site'
        m = _re.search(r"to\s+([\w\-]+)", lt)
        if m: params['target'] = m.group(1)
        return {'intent': intent, 'params': params, 'text': t}

    # default fallback
    return {'intent': 'unknown', 'params': {}, 'text': t}


def _nlu_suggest_commands(nlu: dict) -> dict:
    intent = nlu.get('intent')
    p = nlu.get('params', {})
    suggestions = {'admin': '', 'public': ''}
    if intent == 'stripe_rotate':
        name = p.get('key_name') or 'stripe_live'
        suggestions['admin'] = f"codee-cli stripe key rotate --name {name}"
        suggestions['public'] = f"(admin only) request rotation via admin panel"
    elif intent == 'stripe_add':
        suggestions['admin'] = "codee-cli stripe key add --name stripe_live --value <SECRET>"
        suggestions['public'] = "(admin only) request admin to add key"
    elif intent == 'stripe_remove':
        name = p.get('key_name') or 'stripe_live'
        suggestions['admin'] = f"codee-cli stripe key remove --name {name}"
        suggestions['public'] = "(admin only)"
    elif intent == 'run_audit':
        url = p.get('url') or '<URL>'
        suggestions['admin'] = f"codee-cli audit --url {url} --out ./output"
        suggestions['public'] = f"codee run-audit {url}"
    elif intent == 'create_flyer':
        tier = p.get('tier','100')
        name = p.get('owner_name','Business')
        suggestions['admin'] = f"codee-cli flyer create --tier {tier} --name \"{name}\""
        suggestions['public'] = f"codee ask \"Create a flyer for {name}\""
    elif intent == 'veteran_flyer':
        name = p.get('name','Anonymous Veteran')
        cash = p.get('cashapp','$aik9codee')
        suggestions['admin'] = f"codee-cli veteran flyer --name \"{name}\" --cashapp {cash}"
        suggestions['public'] = f"codee ask \"Create a veteran flyer for {name} using {cash}\""
    elif intent == 'deploy_site':
        suggestions['admin'] = "codee-cli deploy --target production"
        suggestions['public'] = "(admin only)"
    else:
        suggestions['admin'] = "(unknown intent)"
        suggestions['public'] = "(unknown intent)"
    return suggestions


def _manage_nlu_cli(argv: list[str]) -> None:
    import argparse
    parser = argparse.ArgumentParser(prog='codee-cli nl', description='Natural language interpreter for admin suggestions')
    parser.add_argument('mode', choices=['interpret', 'suggest', 'run'], help='interpret: parse; suggest: show CLI suggestions; run: attempt safe local action')
    parser.add_argument('text', nargs='+', help='Natural language input (quote it)')
    args = parser.parse_args(argv)
    text = ' '.join(args.text)
    nlu = _nlu_interpret(text)
    if args.mode == 'interpret':
        print(json.dumps(nlu, indent=2))
        return
    suggestions = _nlu_suggest_commands(nlu)
    if args.mode == 'suggest':
        print('Suggested admin command:', suggestions['admin'])
        print('Suggested public command:', suggestions['public'])
        return
    # run: perform safe local actions for a limited set
    if args.mode == 'run':
        intent = nlu.get('intent')
        p = nlu.get('params', {})
        if intent == 'stripe_rotate':
            name = p.get('key_name') or 'stripe_live'
            print(f"Rotating local placeholder for key: {name} (local only).")
            try:
                _manage_stripe_cli(['key', 'rotate', '--name', name])
            except Exception as e:
                print('Failed to rotate locally:', str(e))
            return
        # other run actions are not automated; print suggestion
        print('Safe run not implemented for this intent. Suggested command:')
        print(suggestions['admin'])
        return

# intercept early to provide nl management without touching rest of CLI
_early_argv = _normalize_cli_argv(sys.argv[1:])
if _early_argv and _early_argv[0] == 'nl':
    try:
        _manage_nlu_cli(sys.argv[2:])
    except Exception as _e:
        print('nl command failed:', str(_e))
    sys.exit(0)

# --- STRIPE ADMIN COMMANDS ---

def _admin_stripe_store_path() -> Path:
    home = Path.home()
    admin_dir = home.joinpath('.codee_admin')
    admin_dir.mkdir(parents=True, exist_ok=True)
    return admin_dir.joinpath('stripe.json')


def _load_admin_stripe() -> dict:
    p = _admin_stripe_store_path()
    if not p.exists():
        return {"keys": {}, "webhooks": {}}
    try:
        return json.loads(p.read_text())
    except Exception:
        return {"keys": {}, "webhooks": {}}


def _save_admin_stripe(data: dict) -> None:
    p = _admin_stripe_store_path()
    p.write_text(json.dumps(data, indent=2))


def _mask_key(key: str) -> str:
    if not key:
        return ''
    if len(key) <= 8:
        return '****'
    return key[:4] + '…' + key[-4:]


def _print_remote_curl_template(action: str, resource: str, payload: dict | None = None) -> None:
    base = CODEE_BACKEND_API_BASE or DEFAULT_API_BASE
    url = f"{base}/admin/stripe/{resource}"
    print('\nRemote API curl template (replace AUTH and payload):')
    print(f"curl -X {action.upper()} '{url}' \\")
    print("  -H 'Authorization: Bearer <ADMIN_API_KEY>' \\")
    print("  -H 'Content-Type: application/json' \\")
    if payload:
        example = json.dumps(payload)
        print(f"  -d '{example}'")
    print('')


def _manage_stripe_cli(argv: list[str]) -> None:
    import argparse
    parser = argparse.ArgumentParser(prog='codee-cli stripe', description='Admin Stripe key/webhook manager (local store + remote templates)')
    sub = parser.add_subparsers(dest='cmd')

    # keys
    key_parser = sub.add_parser('key', help='Manage Stripe keys')
    key_sub = key_parser.add_subparsers(dest='action')
    add_k = key_sub.add_parser('add', help='Add a named key')
    add_k.add_argument('--name', required=True, help='Logical name for the key, e.g. stripe_live, stripe_webhook')
    add_k.add_argument('--value', required=True, help='Secret key value')
    add_k.add_argument('--remote', action='store_true', help='Print remote curl template instead of storing locally')

    edit_k = key_sub.add_parser('edit', help='Edit an existing key value')
    edit_k.add_argument('--name', required=True)
    edit_k.add_argument('--value', required=True)
    edit_k.add_argument('--remote', action='store_true')

    rm_k = key_sub.add_parser('remove', help='Remove a named key')
    rm_k.add_argument('--name', required=True)
    rm_k.add_argument('--remote', action='store_true')

    list_k = key_sub.add_parser('list', help='List stored key names')

    rotate_k = key_sub.add_parser('rotate', help='Rotate a key (local: mark rotated; remote: print template)')
    rotate_k.add_argument('--name', required=True)
    rotate_k.add_argument('--remote', action='store_true')

    # webhooks
    wh_parser = sub.add_parser('webhook', help='Manage Stripe webhook records')
    wh_sub = wh_parser.add_subparsers(dest='action')
    wh_list = wh_sub.add_parser('list', help='List webhooks')
    wh_add = wh_sub.add_parser('add', help='Add webhook metadata')
    wh_add.add_argument('--id', required=True, help='Webhook id (logical)')
    wh_add.add_argument('--url', required=True)
    wh_add.add_argument('--events', default='*', help='Comma separated events')
    wh_add.add_argument('--secret', default='', help='Signing secret (optional locally stored)')
    wh_add.add_argument('--remote', action='store_true')
    wh_rm = wh_sub.add_parser('remove', help='Remove webhook')
    wh_rm.add_argument('--id', required=True)
    wh_rm.add_argument('--remote', action='store_true')

    args = parser.parse_args(argv)
    if not args.cmd:
        parser.print_help()
        return

    store = _load_admin_stripe()

    if args.cmd == 'key':
        if args.action == 'add':
            if args.remote:
                _print_remote_curl_template('POST', 'keys', {"name": args.name, "value": '<REDACTED>'})
                print('Remote template printed. Use your admin API to persist secrets on server-side.')
                return
            store.setdefault('keys', {})[args.name] = {"value": args.value, "created_at": dt.datetime.utcnow().isoformat()}
            _save_admin_stripe(store)
            print(f"Added key '{args.name}' (stored locally in {_admin_stripe_store_path()}).")
            return
        if args.action == 'edit':
            if args.remote:
                _print_remote_curl_template('PUT', f'keys/{args.name}', {"value": '<REDACTED>'})
                return
            if args.name not in store.get('keys', {}):
                print(f"Key '{args.name}' not found locally.")
                return
            store['keys'][args.name]['value'] = args.value
            store['keys'][args.name]['updated_at'] = dt.datetime.utcnow().isoformat()
            _save_admin_stripe(store)
            print(f"Edited key '{args.name}'.")
            return
        if args.action == 'remove':
            if args.remote:
                _print_remote_curl_template('DELETE', f'keys/{args.name}')
                return
            if args.name in store.get('keys', {}):
                del store['keys'][args.name]
                _save_admin_stripe(store)
                print(f"Removed key '{args.name}' from local store.")
            else:
                print(f"Key '{args.name}' not found.")
            return
        if args.action == 'list':
            keys = store.get('keys', {})
            if not keys:
                print('No local keys stored.')
                return
            for k, v in keys.items():
                val = v.get('value')
                print(f" - {k}: {_mask_key(val)} (created: {v.get('created_at')}, updated: {v.get('updated_at', '')})")
            return
        if args.action == 'rotate':
            if args.remote:
                _print_remote_curl_template('POST', f'keys/{args.name}/rotate')
                return
            if args.name not in store.get('keys', {}):
                print(f"Key '{args.name}' not found locally.")
                return
            # local rotate: mark rotated_at and bump value placeholder
            new_placeholder = f'rotated-{int(time.time())}'
            store['keys'][args.name]['value'] = new_placeholder
            store['keys'][args.name]['rotated_at'] = dt.datetime.utcnow().isoformat()
            _save_admin_stripe(store)
            print(f"Rotated key '{args.name}' locally. New placeholder stored. Push new real key to server as needed.")
            return

    if args.cmd == 'webhook':
        if args.action == 'list':
            wh = store.get('webhooks', {})
            if not wh:
                print('No local webhook records.')
                return
            for wid, meta in wh.items():
                print(f" - {wid}: url={meta.get('url')} events={meta.get('events')} secret={_mask_key(meta.get('secret',''))}")
            return
        if args.action == 'add':
            if args.remote:
                _print_remote_curl_template('POST', 'webhooks', {"id": args.id, "url": args.url, "events": args.events, "secret": '<REDACTED>'})
                return
            store.setdefault('webhooks', {})[args.id] = {"url": args.url, "events": args.events, "secret": args.secret, "created_at": dt.datetime.utcnow().isoformat()}
            _save_admin_stripe(store)
            print(f"Added webhook '{args.id}' locally.")
            return
        if args.action == 'remove':
            if args.remote:
                _print_remote_curl_template('DELETE', f'webhooks/{args.id}')
                return
            if args.id in store.get('webhooks', {}):
                del store['webhooks'][args.id]
                _save_admin_stripe(store)
                print(f"Removed webhook '{args.id}' from local store.")
            else:
                print(f"Webhook '{args.id}' not found.")
            return

# intercept early to provide admin stripe management without touching the rest of the CLI
_early_argv = _normalize_cli_argv(sys.argv[1:])
if _early_argv and _early_argv[0] == 'stripe':
    try:
        _manage_stripe_cli(sys.argv[2:])
    except Exception as _e:
        print('stripe command failed:', str(_e))
    sys.exit(0)

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",
]

CODEE_CODEX_PARITY_REQUIREMENTS = [
    {
        "id": "terminal-entry",
        "label": "Terminal entry",
        "codex_behavior": "User starts inside a terminal and talks to the agent.",
        "codee_command": "codee prompt .",
        "status": "ready-local-router",
    },
    {
        "id": "workspace-state",
        "label": "Workspace state",
        "codex_behavior": "Agent understands the current folder, config, rules, and recent commands.",
        "codee_command": "codee session . --write && codee heartbeat .",
        "status": "ready",
    },
    {
        "id": "permissions",
        "label": "Permission modes",
        "codex_behavior": "Work is gated by read/edit/network/shell approval modes.",
        "codee_command": "codee permissions . --mode suggest --write",
        "status": "ready",
    },
    {
        "id": "memory",
        "label": "Project and user memory",
        "codex_behavior": "Rules and user preferences survive across sessions.",
        "codee_command": "codee memory . --write && codee memory-vault init . --force",
        "status": "ready",
    },
    {
        "id": "tool-registry",
        "label": "Tool registry",
        "codex_behavior": "Agent knows what tools and connectors are allowed.",
        "codee_command": "codee registry . --write --force && codee mcp . --write --force",
        "status": "ready",
    },
    {
        "id": "task-threading",
        "label": "Task threads",
        "codex_behavior": "Requests can become tracked tasks with proof and result files.",
        "codee_command": "codee task create . --title \"Client update\" --service codeeqr",
        "status": "ready-local-plus-backend",
    },
    {
        "id": "proof-loop",
        "label": "Proof loop",
        "codex_behavior": "Agent verifies edits with focused tests, scans, and reports.",
        "codee_command": "codee doctor . --local-only && codee codex-sync . --write --force",
        "status": "ready",
    },
    {
        "id": "model-bridge",
        "label": "Bring-your-own model bridge",
        "codex_behavior": "Agent can use a model provider without bundling private keys into the CLI.",
        "codee_command": "codee model-bridge . --write --force",
        "status": "ready-byo",
    },
    {
        "id": "agent-run",
        "label": "Guarded local agent run",
        "codex_behavior": "Agent turns a goal into inspected context, a task plan, optional checkpointed edits, test proof, and next commands.",
        "codee_command": "codee agent-run . --goal \"Improve this workspace\" --write --force",
        "status": "ready-local-plus-byo-model",
    },
    {
        "id": "codex-version-sync",
        "label": "Codex version sync",
        "codex_behavior": "Codee notices the installed Codex CLI version and records when it changed.",
        "codee_command": "codee codex-sync . --write --force --apply-codee-update",
        "status": "new-ready",
    },
]

CODEE_CODEX_PARITY_MODEL = {
    "schema": "codee.codex-parity.v1",
    "version": VERSION,
    "updated_at": "2026-06-08",
    "manifest_url": CODEE_CODEX_PARITY_MANIFEST_URL,
    "positioning": "CodeeCLI parity layer for Codex-style terminal workspace work.",
    "direct_connection_truth": "Codee cannot receive OpenAI Codex release events directly. Codee can watch the locally installed `codex --version`, write a sync report, and optionally refresh CodeeCLI from its own public release URL when Codex changes.",
    "required_command": "codee codex-sync . --write --force --apply-codee-update",
    "hook_path": ".codee/update-hooks/codex-sync.sh",
    "parity_files": [
        ".codee/codex-parity.json",
        ".codee/CODEX_PARITY.md",
        ".codee/update-hooks/codex-sync.sh",
        ".codee/reports/latest-codex-sync.json",
    ],
    "parity_requirements": CODEE_CODEX_PARITY_REQUIREMENTS,
    "recommended_update_flow": [
        "Update Codex normally with the OpenAI/Codex installer path.",
        "Run `codee codex-sync . --write --force --apply-codee-update` in each Codee workspace.",
        "Run `codee doctor . --local-only` and `codee codex-bridge . --write --force --json` after the sync.",
        "Deploy the refreshed public CodeeCLI copy only after compile and smoke proof pass.",
    ],
}

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.",
    },
]

CODEE_OWNER_SUPPORT_MODEL = {
    "schema": "codee.owner-cli-support.v1",
    "version": VERSION,
    "updated_at": "2026-05-30",
    "public_page": CODEE_OWNER_CLI_URL,
    "manifest_url": CODEE_OWNER_CLI_MANIFEST_URL,
    "positioning": "Owner-only frontend support lane for Codee client sites when the client cannot make the edit or is running an outdated CLI.",
    "support_roles": [
        {"id": "owner", "label": "Owner", "can": ["approve client-facing changes", "authorize emergency support", "approve deploy handoff"]},
        {"id": "frontend-support", "label": "Frontend Support", "can": ["copy edits", "image swaps", "link repairs", "layout fixes", "route scans"]},
        {"id": "qa-proof", "label": "QA Proof", "can": ["before screenshot", "after screenshot", "route scan", "mobile check"]},
    ],
    "frontend_edit_lanes": [
        {"id": "copy-update", "label": "Copy update", "proof": "before text and after text saved in support packet"},
        {"id": "link-update", "label": "Link or CTA repair", "proof": "target URL checked before close"},
        {"id": "image-update", "label": "Image or logo swap", "proof": "image source and visible page checked"},
        {"id": "layout-fix", "label": "Layout or mobile fix", "proof": "desktop and mobile preview checked"},
        {"id": "social-connect", "label": "AI K9 Codee Social Connect", "proof": "official OAuth status checked, no password collection"},
        {"id": "emergency-rollback", "label": "Emergency rollback", "proof": "checkpoint or previous asset path recorded before change"},
    ],
    "social_connect": {
        "public_name": "AI K9 Codee Social Connect",
        "terminal_name": "Codee Social Connect",
        "purpose": "Give a client one secure link to connect Facebook, Instagram, Pinterest, YouTube, or TikTok while Codee gives status and next-step assistance.",
        "visible_rule": "Client sees Codee. Metricool stays fallback infrastructure only when direct platform publishing is not approved yet.",
        "connectable_platforms": ["facebook", "instagram", "pinterest", "youtube", "tiktok"],
        "no_secret_rule": "Never ask for passwords, OAuth tokens, page tokens, app secrets, or cookies. Use official OAuth/client-share screens only.",
    },
    "outdated_cli_protocol": [
        "Ask the client to run `codee self-update . --target ./codee.py --write` when their CLI still opens but is stale.",
        "If their CLI is broken, ask for the local support packet from `.codee/support-requests/` or create an owner-support packet for them.",
        "Never ask for passwords, private keys, .env files, OAuth tokens, or payment secrets.",
        "Close the request only after route proof or a screenshot path is attached.",
    ],
    "owner_commands": [
        "codee owner-support . --client CLIENT_ID --request \"Fix homepage CTA\" --write --force",
        "codee support . --service codee-support --message \"Client cannot edit latest site copy.\" --submit",
        "codee doctor . --local-only",
        "codee scan . --url https://CLIENT-SITE",
    ],
    "admin_rule": "This lane can triage and package frontend fixes; deploy credentials and social tokens remain owner/backend-gated.",
}

CODEE_OWNER_DEV_MODEL = {
    "schema": "codee.owner-dev.v1",
    "version": VERSION,
    "updated_at": "2026-05-30",
    "manifest_url": CODEE_OWNER_DEV_MANIFEST_URL,
    "positioning": "Owner-grade Codee edit workflow for frontend, backend, and full-stack site support work.",
    "operating_rules": [
        "Inspect the existing repo and current file state before editing.",
        "Create a checkpoint before risky frontend, backend, deploy, or public-download changes.",
        "Preserve unrelated user changes and do not overwrite dirty files blindly.",
        "Use narrow edits, then run the smallest proof command that can catch the risk.",
        "Frontend work needs route or browser proof before close.",
        "Backend work needs Python compile or targeted smoke proof before deploy.",
        "Public CLI changes must sync the generated JSON manifests and downloadable CLI copy.",
        "Deploy credentials, OAuth secrets, Stripe secrets, and GCloud access stay owner/backend-gated.",
    ],
    "edit_modes": {
        "frontend": {
            "roots": ["Codee original/frontend-public", "sites", "assets", "css", "js"],
            "proof": ["route scan", "browser scan when layout changed", "download/public asset sync when relevant"],
        },
        "backend": {
            "roots": ["Codee original/backend", "tools"],
            "proof": ["python compile", "targeted smoke", "Cloud Run deploy only after owner approval"],
        },
        "fullstack": {
            "roots": ["Codee original/frontend-public", "Codee original/backend", "tools"],
            "proof": ["checkpoint", "python compile", "manifest sync", "route scan", "owner handoff"],
        },
        "social": {
            "roots": ["Codee original/backend/social_oauth.py", "Codee original/backend/dashboard_routes.py", "Codee original/frontend-public/codee-owner-cli.html"],
            "proof": ["OAuth setup status", "Facebook status endpoint", "no password or token collection"],
        },
        "deploy": {
            "roots": ["Codee original/backend/deploy_now.sh", "firebase.json", "Codee original/frontend-public"],
            "proof": ["local compile", "route scan", "owner-approved deploy command"],
        },
    },
    "download_commands": [
        f"curl -L {CODEE_DOWNLOAD_URL} -o codee.py",
        "./CODEE install . --write --global",
        "codee --version",
        "codee owner-dev . --mode fullstack --request \"Describe the site/backend edit\" --write --force",
    ],
    "owner_only_rule": "This command can plan and prove owner/backend edits; it does not ship private deploy credentials in the public CLI.",
}

CODEE_CODEX_BRIDGE_MODEL = {
    "schema": "codee.codex-bridge.v1",
    "version": VERSION,
    "updated_at": "2026-05-30",
    "manifest_url": CODEE_CODEX_BRIDGE_MANIFEST_URL,
    "positioning": "Machine-readable bridge that lets Codex inspect, improve, and prove Ai K9 CODEE without guessing.",
    "codex_entry_rule": "Install once, then start with `codee codex-bridge . --write --force --json`; use `codee owner-dev` for any frontend, backend, social, or deploy edit packet. Fallback before install: `python3 codee.py codex-bridge ...`.",
    "simple_route": {
        "download": f"curl -L {CODEE_DOWNLOAD_URL} -o codee.py",
        "install_once": "./CODEE install . --write --global",
        "after_install": "codee <command> ...",
        "accepted_forms": ["codee heel", "codee HEEL", "codee (heel)", "codee /heel"],
        "fallback": "python3 codee.py <command> ...",
    },
    "live_urls": {
        "cli_page": f"{DEFAULT_API_BASE}/codee-cli",
        "alpha_pack": CODEE_ALPHA_PACK_URL,
        "download": CODEE_DOWNLOAD_URL,
        "tool_registry": CODEE_TOOL_REGISTRY_URL,
        "release": CODEE_RELEASE_URL,
        "owner_cli": CODEE_OWNER_CLI_URL,
        "owner_cli_manifest": CODEE_OWNER_CLI_MANIFEST_URL,
        "owner_dev_manifest": CODEE_OWNER_DEV_MANIFEST_URL,
        "codex_bridge_manifest": CODEE_CODEX_BRIDGE_MANIFEST_URL,
        "codex_parity_manifest": CODEE_CODEX_PARITY_MANIFEST_URL,
        "promotion_greenlight_manifest": CODEE_PROMOTION_GREENLIGHT_MANIFEST_URL,
        "heel_teacher_manifest": CODEE_HEEL_TEACHER_MANIFEST_URL,
        "heal_teacher_manifest_legacy": CODEE_HEAL_TEACHER_MANIFEST_URL,
        "audit_ladder_manifest": CODEE_AUDIT_LADDER_MANIFEST_URL,
    },
    "codex_commands": [
        f"curl -L {CODEE_DOWNLOAD_URL} -o codee.py",
        "codee --version",
        "codee audit . --business \"Demo Business\" --email owner@example.com --target-url https://example.com --write --json",
        "codee heel . --teacher-email teacher@example.com --write --force",
        "codee codex-bridge . --write --force --json",
        "codee codex-sync . --write --force --apply-codee-update",
        "codee doctor . --local-only",
        "codee owner-dev . --mode fullstack --request \"Describe the CLI/site/backend enhancement\" --write --force",
    ],
    "inspection_files": [
        "tools/codee_cli.py",
        "tools/sync_codeeadmin_public_assets.py",
        "Codee original/frontend-public/assets/downloads/codee-cli.py",
        "Codee original/frontend-public/assets/codee/codee-heel-teacher.json",
        "Codee original/frontend-public/assets/codee/codee-audit-ladder.json",
        "Codee original/frontend-public/codee-cli.html",
        "Codee original/frontend-public/codee-owner-cli.html",
        "Codee original/frontend-public/sw.js",
        "Codee original/backend/dashboard_routes.py",
        "Codee original/backend/social_oauth.py",
    ],
    "enhancement_backlog": [
        {"id": "live-download-proof", "priority": "high", "goal": "Verify the live downloadable Ai K9 CODEE tool compiles and returns the same version as the source."},
        {"id": "manifest-freshness", "priority": "high", "goal": "Sync codee-codex-bridge, owner-dev, tool-registry, release, and downloadable Ai K9 CODEE copy whenever tools/codee_cli.py changes."},
        {"id": "route-proof", "priority": "high", "goal": "Route scan the CLI page, owner CLI page, and JSON manifests before telling users the laptop download is ready."},
        {"id": "owner-handoff", "priority": "normal", "goal": "Use owner-dev packets for any site, backend, social, or deploy enhancement request."},
        {"id": "secret-boundary", "priority": "always", "goal": "Keep OAuth, Stripe, Google Cloud, and private deploy credentials outside public CLI packets."},
    ],
    "codex_allowed_actions": [
        "Read public manifests and local workspace files.",
        "Write local .codee/codex-bridge and owner-dev packets.",
        "Run local compile, JSON, doctor, and route proof commands.",
        "Sync public JSON manifests and downloadable CLI copy after source CLI changes.",
    ],
    "owner_gated_actions": [
        "Firebase deploys and Cloud Run deploys.",
        "Reading or changing secrets, .env files, OAuth tokens, Stripe keys, or Google Cloud credentials.",
        "Connecting or posting through Facebook, Instagram, Google, Canva, Adobe, WordPress, or Metricool accounts.",
        "Changing client production routes without checkpoint and proof output.",
    ],
}

CODEE_K9_COMMAND_MAP = [
    {
        "k9_command": "heel",
        "k9_definition": "Return to the handler's side and move under control.",
        "codee_command": "codee heel . --teacher-email teacher@example.com --write --force",
        "python_fallback": "python3 codee.py heel . --teacher-email teacher@example.com --write --force",
        "codee_logic": "Bring the workspace back beside the owner: create the teacher packet, login command, diagnosis flow, Codex bridge, and support handoff.",
    },
    {
        "k9_command": "sit",
        "k9_definition": "Stop and hold a controlled basic position.",
        "codee_command": "codee doctor . --local-only",
        "python_fallback": "python3 codee.py doctor . --local-only",
        "codee_logic": "Stop the rush and inspect the local folder, tools, manifests, and unsafe files before editing.",
    },
    {
        "k9_command": "stay",
        "k9_definition": "Hold position until the handler releases or returns.",
        "codee_command": "codee checkpoint . --label before-client-edit",
        "python_fallback": "python3 codee.py checkpoint . --label before-client-edit",
        "codee_logic": "Freeze the current safe state before a teacher, client, or Codex changes files.",
    },
    {
        "k9_command": "come",
        "k9_definition": "Return to the handler on command.",
        "codee_command": "codee login . --email teacher@example.com --business \"Business Name\" --write",
        "python_fallback": "python3 codee.py login . --email teacher@example.com --business \"Business Name\" --write",
        "codee_logic": "Bring the user into a known local identity without passwords or third-party secrets.",
    },
    {
        "k9_command": "search",
        "k9_definition": "Search a defined area for a target, subject, or evidence.",
        "codee_command": "codee scan . --url https://example.com",
        "python_fallback": "python3 codee.py scan . --url https://example.com",
        "codee_logic": "Search public routes and manifests for broken pages, 404s, or missing proof.",
    },
    {
        "k9_command": "track",
        "k9_definition": "Follow a trail or scent path until the target is found.",
        "codee_command": "codee heartbeat .",
        "python_fallback": "python3 codee.py heartbeat .",
        "codee_logic": "Follow the workspace trail: identity, latest proof, tasks, routes, and next commands.",
    },
    {
        "k9_command": "guard",
        "k9_definition": "Hold protective control while the handler works.",
        "codee_command": "codee owner-support . --client CLIENT_ID --request \"Client needs help\" --write --force",
        "python_fallback": "python3 codee.py owner-support . --client CLIENT_ID --request \"Client needs help\" --write --force",
        "codee_logic": "Protect the client workflow with support triage, no-secrets rules, and proof before close.",
    },
    {
        "k9_command": "release",
        "k9_definition": "Stop the active hold or action on command.",
        "codee_command": "codee support . --message \"Ready for owner review\"",
        "python_fallback": "python3 codee.py support . --message \"Ready for owner review\"",
        "codee_logic": "Move work out of active repair into documented owner/support review.",
    },
]

CODEE_HEEL_TEACHER_MODEL = {
    "schema": "codee.heel-teacher.v1",
    "version": VERSION,
    "updated_at": "2026-05-30",
    "manifest_url": CODEE_HEEL_TEACHER_MANIFEST_URL,
    "legacy_manifest_url": CODEE_HEAL_TEACHER_MANIFEST_URL,
    "positioning": "Military-working-dog inspired teacher/support packet for a downloaded Ai K9 CODEE user who needs login, diagnosis, repair, and safe owner handoff.",
    "friendly_command": "codee heel . --teacher-email teacher@example.com --write --force",
    "python_fallback": "python3 codee.py heel . --teacher-email teacher@example.com --write --force",
    "alias_commands": ["codee heal . --teacher-email teacher@example.com --write --force", "codee HEEL . --teacher-email teacher@example.com --write --force", "codee (heel) . --teacher-email teacher@example.com --write --force", "codee /heel . --teacher-email teacher@example.com --write --force"],
    "purpose": "Give the teacher or support helper one packet with login steps, workspace pulse, repair commands, Codex bridge, and owner/support escalation without collecting secrets.",
    "k9_logic": "HEEL is the reset command: Codee comes back to the handler's side, gets under control, diagnoses the folder, and prepares the next safe move.",
    "k9_command_map": CODEE_K9_COMMAND_MAP,
    "teacher_receives": [
        "A login-ready identity packet with the exact `codee login` command.",
        "A folder health and proof checklist.",
        "A Codex bridge command so Codex can inspect and enhance safely.",
        "An owner-dev command for frontend, backend, social, or deploy edit packets.",
        "An owner-support command for client rescue and outdated CLI triage.",
        "A strict no-secrets rule for passwords, .env files, OAuth tokens, Stripe keys, and cloud credentials.",
    ],
    "baked_in_commands": [
        "codee login . --email teacher@example.com --business \"Business Name\" --write",
        "codee doctor . --local-only",
        "codee codex-bridge . --write --force --json",
        "codee owner-dev . --mode fullstack --request \"Help this client safely\" --write --force",
        "codee owner-support . --client CLIENT_ID --request \"Client needs help\" --write --force",
        "codee support . --message \"Teacher/support packet created\"",
    ],
    "safe_login_rule": "The CLI can create a local login identity and optional backend registration; it must not ask for passwords or third-party account secrets.",
    "repair_flow": [
        "Download Ai K9 CODEE from the trusted clients.codee.chat URL.",
        "Run `./CODEE install . --write --global` once if you want the Codex-style `codee ...` command.",
        "Run `codee heel` to create the teacher/support packet.",
        "Run `codee login` with the teacher or owner email to bind local identity.",
        "Run `codee doctor --local-only` before edits.",
        "Run `codee codex-bridge` before asking Codex to enhance the CLI or site.",
        "Run `codee owner-dev` or `codee owner-support` depending on whether the job is an edit packet or a support rescue.",
    ],
}
CODEE_HEAL_TEACHER_MODEL = CODEE_HEEL_TEACHER_MODEL

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-30",
    "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",
        "CodeeCard",
        "MiniCodeeSite",
        "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": "free-audit",
            "name": "Free Codee Audit",
            "label": "$0 Free Codee Audit",
            "amount_cents": 0,
            "mode": "free",
            "interval": "",
            "invoice_allowed": False,
            "description": "No-card audit results page with site scorecard, findings, and recommended first paid lane.",
        },
        {
            "id": "codee-affiliate",
            "name": "Codee Affiliate Lane",
            "label": "$0 Codee Affiliate Lane",
            "amount_cents": 0,
            "mode": "referral",
            "interval": "",
            "invoice_allowed": False,
            "description": "Reference code, single-service or all-service link bundle, no-website social QR, Stripe referral ledger, and weekly verified payout review.",
        },
        {
            "id": "veteran-mission-qrcodee",
            "name": "Veteran Mission QRCodee",
            "label": "$0 Veteran Mission QRCodee",
            "amount_cents": 0,
            "mode": "mission",
            "interval": "",
            "invoice_allowed": False,
            "description": "Free veteran Codee app, support destination, QR target, referral code, business service links, and proof report; business customers still use normal paid Codee lanes.",
        },
        {
            "id": "codeeqr",
            "name": "QRCodee",
            "label": "$49 QRCodee",
            "amount_cents": 4900,
            "mode": "payment",
            "interval": "",
            "invoice_allowed": False,
            "description": "Branded QR image, hosted QR landing page, scan proof, and delivery room.",
        },
        {
            "id": "audit-site",
            "name": "Codee Audit Site",
            "label": "$149 Codee Audit Site",
            "amount_cents": 14900,
            "mode": "payment",
            "interval": "",
            "invoice_allowed": False,
            "description": "Free audit turned into a paid hosted action page with report, fix queue, and support request path.",
        },
        {
            "id": "codeeflyer_lane",
            "name": "CodeeFlyer",
            "label": "$99 CodeeFlyer",
            "amount_cents": 9900,
            "mode": "payment",
            "interval": "",
            "invoice_allowed": False,
            "description": "AI-designed or redesigned hosted flyer with a verified lower-corner QRCodee, up to three actions, delivery proof, and 30 days of support.",
        },
        {
            "id": "codeeblog",
            "name": "CodeeBlog",
            "label": "$100 CodeeBlog",
            "amount_cents": 10000,
            "mode": "payment",
            "interval": "",
            "invoice_allowed": False,
            "public_sales_status": "paused",
            "new_orders_enabled": False,
            "existing_deliverables_accessible": True,
            "owner_reactivation_required": True,
            "recommended_alternative": "mini_codeesite",
            "description": "Hosted blog/resource hub with logo, guide links, offers, capture path, and delivery room.",
        },
        {
            "id": "codeeapp250",
            "name": "CodeeApp250",
            "label": "$250 CodeeApp250",
            "amount_cents": 25000,
            "mode": "payment",
            "interval": "",
            "invoice_allowed": False,
            "public_sales_status": "paused",
            "new_orders_enabled": False,
            "existing_deliverables_accessible": True,
            "owner_reactivation_required": True,
            "recommended_alternative": "mini_codeesite",
            "description": "Hosted guidebook/app page with cover, buyer checkout, QR return path, and delivery room.",
        },
        {
            "id": "codeecard",
            "name": "CodeeCard",
            "label": "$250 CodeeCard",
            "amount_cents": 25000,
            "mode": "payment",
            "interval": "",
            "invoice_allowed": False,
            "description": "Premium square-tile link hub with QR, main action, contact/booking tiles, Codee support path, and owner review access when the card needs stronger positioning.",
        },
        {
            "id": "codeebeeper",
            "name": "CodeeBeeper",
            "label": "$149 CodeeBeeper",
            "amount_cents": 14900,
            "mode": "payment",
            "interval": "",
            "invoice_allowed": False,
            "description": "Private storage/vault workspace with PIN, note thread, media slots, and delivery room.",
        },
        {
            "id": "minicodeesite",
            "name": "MiniCodeeSite",
            "label": "$2,500 Pro Mini CodeeSite",
            "amount_cents": 250000,
            "mode": "payment",
            "interval": "",
            "invoice_allowed": True,
            "description": "Simple 3-5 page website shell with Codee CLI-assisted setup, primary CTA, private preview, and no custom app or full CMS.",
        },
        {
            "id": "codeeauthority",
            "name": "CodeeAuthority",
            "label": "$250 CodeeAuthority",
            "amount_cents": 25000,
            "mode": "payment",
            "interval": "",
            "invoice_allowed": False,
            "description": "Owner-review authority/search lane. Backend-supported, not shown as a normal public Codee.chat product until approved.",
        },
        {
            "id": "sean-review-room",
            "name": "Sean Review Room",
            "label": "$200 Sean Review Room",
            "amount_cents": 20000,
            "mode": "payment",
            "interval": "",
            "invoice_allowed": False,
            "description": "Private audit-only review room with consultation/video-room path after context is collected.",
        },
        {
            "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, ten Idea-to-Service previews, 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 with up to fifty Idea-to-Service previews.",
        },
        {
            "id": "service_creator",
            "name": "Codee Service Creator",
            "label": "$249/mo Codee Service Creator",
            "amount_cents": 24900,
            "mode": "subscription",
            "interval": "month",
            "invoice_allowed": False,
            "description": "Workspace tier for turning approved ideas into hosted private previews, public service pages, and owner-reviewed checkout/invoice routes.",
        },
        {
            "id": "business-suite",
            "name": "Codee Business Suite",
            "label": "$2,500 Codee Business Suite",
            "amount_cents": 250000,
            "mode": "payment",
            "interval": "",
            "invoice_allowed": True,
            "description": "Limited 10-slot premium package with backend support, private consultation, QR/flyer/card/site 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": "MiniCodeeSite Product Guide Course",
            "lesson": "Turn a guidebook, PDF, checklist, or mini product into a small hosted page with a cover, bullets, QR, and checkout/download path.",
            "student_output": "A product-guide site folder with cover art, buyer action, QR return path, and download/delivery instructions.",
            "paid_path": "MiniCodeeSite/shop lane with client upload, hosted product-guide view, Stripe buyer path, and delivery room.",
            "activation_service": "minicodeesite",
            "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, CodeeCard, MiniCodeeSite/shop lane, 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, MiniCodeeSite, and CodeeCard 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 screenshot proof, responsive route proof, and visual readiness 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": "codex-bridge",
        "name": "Codex Bridge Packet",
        "access": "public",
        "status": "built-in",
        "summary": "Write a Codex-readable packet with live URLs, local file inventory, enhancement backlog, route proof commands, and the next owner-dev command.",
        "commands": ["codex-bridge", "owner-dev", "doctor", "scan"],
        "requires": ["python3"],
        "proof": ".codee/codex-bridge/CODEX_BRIDGE.md and .codee/reports/latest-codex-bridge.json",
    },
    {
        "id": "owner-dev-edit-packets",
        "name": "Owner Dev Edit Packets",
        "access": "public-plus-owner",
        "status": "built-in",
        "summary": "Prepare frontend, backend, social, deploy, or fullstack edit packets with file inventory, guardrails, proof commands, and safe live-deploy boundaries.",
        "commands": ["owner-dev", "checkpoint", "scan", "browser-scan"],
        "requires": ["python3"],
        "proof": ".codee/owner-dev/OWNER_DEV.md and .codee/reports/latest-owner-dev.json",
    },
    {
        "id": "live-paywall-deploy-gate",
        "name": "Live Paywall Deploy Gate",
        "access": "public-plus-backend",
        "status": "server-routed",
        "summary": "Keep live hosting, backend services, delivery rooms, and customer deploy work behind Stripe-hosted payment or owner-approved support routes.",
        "commands": ["preview", "activate", "delivery", "license", "support"],
        "requires": ["Codee backend", "Stripe hosted checkout"],
        "proof": ".codee/reports/latest-activation-request.json and .codee/license.json",
    },
    {
        "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 = {
    "audit": "free-audit",
    "freeaudit": "free-audit",
    "free-audit": "free-audit",
    "site-audit": "free-audit",
    "audit-report": "free-audit",
    "audit-room": "audit-site",
    "audit-site": "audit-site",
    "paid-audit": "audit-site",
    "codee-audit-site": "audit-site",
    "affiliate": "codee-affiliate",
    "referral": "codee-affiliate",
    "referrals": "codee-affiliate",
    "partner": "codee-affiliate",
    "codeeaffiliate": "codee-affiliate",
    "codee-affiliate": "codee-affiliate",
    "mission": "veteran-mission-qrcodee",
    "mission-qr": "veteran-mission-qrcodee",
    "mission-qrcodee": "veteran-mission-qrcodee",
    "veteran": "veteran-mission-qrcodee",
    "veteran-qr": "veteran-mission-qrcodee",
    "veteran-qrcodee": "veteran-mission-qrcodee",
    "veteran-mission": "veteran-mission-qrcodee",
    "veteran-mission-qrcodee": "veteran-mission-qrcodee",
    "qr": "codeeqr",
    "qrcodee": "codeeqr",
    "codee-qr": "codeeqr",
    "codeeqr": "codeeqr",
    "flyer": "codeeflyer",
    "digiflyer": "codeeflyer",
    "codeeflyer": "codeeflyer",
    "codeeflyer100": "codeeflyer",
    "codeeflyer-100": "codeeflyer",
    "codeeflyer250": "codeeflyer300",
    "codeeflyer-250": "codeeflyer300",
    "codeeflyer300": "codeeflyer300",
    "codeeflyer-300": "codeeflyer300",
    "blog": "codeeblog",
    "digiblog": "codeeblog",
    "codeeblog": "codeeblog",
    "codee-blog": "codeeblog",
    "digiapp": "codeeapp250",
    "codeeapp": "codeeapp250",
    "codeeapp250": "codeeapp250",
    "app250": "codeeapp250",
    "card": "codeecard",
    "digicard": "codeecard",
    "codeecard": "codeecard",
    "beeper": "codeebeeper",
    "vault": "codeebeeper",
    "codeevault": "codeebeeper",
    "codeebeeper": "codeebeeper",
    "mini-site": "minicodeesite",
    "codeesite": "minicodeesite",
    "minicodeesite": "minicodeesite",
    "minicodeesite497": "minicodeesite-template",
    "minicodeesite-497": "minicodeesite-template",
    "template-license": "minicodeesite-template",
    "mini-template": "minicodeesite-template",
    "minicodeesite1500": "minicodeesite-launch",
    "minicodeesite-1500": "minicodeesite-launch",
    "launch-kit": "minicodeesite-launch",
    "mini-launch": "minicodeesite-launch",
    "minicodeesite2500": "codee-business-suite",
    "minicodeesite-2500": "codee-business-suite",
    "supported-build": "codee-business-suite",
    "business-suite": "codee-business-suite",
    "codeebusinesssuite": "codee-business-suite",
    "codee-business-suite": "codee-business-suite",
    "authority": "codeeauthority",
    "codeeauthority": "codeeauthority",
    "codee-authority": "codeeauthority",
    "ai-search-authority": "codeeauthority",
    "consult": "sean-review-room",
    "consultation": "sean-review-room",
    "sean-review": "sean-review-room",
    "sean-review-room": "sean-review-room",
    "review-room": "sean-review-room",
}

CODEE_SERVICE_CONTRACTS: dict[str, dict[str, Any]] = {
    "free-audit": {
        "schema": "codee.service-contract.v1",
        "service": "free-audit",
        "public_name": "Free Codee Audit",
        "price_lane": "0",
        "promise": "Create a no-card audit packet with a site scorecard, delivery room, and the smallest sensible next paid lane.",
        "required_inputs": ["business name", "client email", "current website or target URL", "main business goal"],
        "client_gets": ["audit scorecard", "issue checklist", "delivery room link", "recommended first paid lane", "support request path"],
        "delivery_room_slots": ["open audit report", "review issue list", "choose QR image site or audit-site upsell", "request support"],
        "paywall_rule": "Audit report and delivery room are free; fixes, hosted QR/site assets, managed scans, and support unlock through the chosen paid lane.",
        "accessibility_default": "Short scorecard sections, large next-step buttons, and no payment request before the free report.",
    },
    "audit-site": {
        "schema": "codee.service-contract.v1",
        "service": "audit-site",
        "public_name": "Codee Audit Site",
        "price_lane": "149",
        "promise": "Turn the free audit into a paid hosted action page with a client-facing report, fix queue, QR handoff, and support request path.",
        "required_inputs": ["business name", "client email", "audit target URL", "logo or brand color", "priority fix request"],
        "client_gets": ["hosted audit report", "action page", "fix queue", "QR return link", "support request path"],
        "delivery_room_slots": ["open hosted audit report", "view fixes recommended", "request first edit", "upgrade to QR, flyer, app, or suite"],
        "paywall_rule": "Free audit can be reviewed first; hosted audit-site report, fix queue, and support lane unlock after payment.",
        "accessibility_default": "Report is scannable, issue cards are plain language, and paid fixes are never hidden.",
    },
    "codee-affiliate": {
        "schema": "codee.service-contract.v1",
        "service": "codee-affiliate",
        "public_name": "Codee Affiliate Lane",
        "price_lane": "no purchase required",
        "commission_lane": "10% default cash payout, backend-configurable",
        "service_credit_lane": "15% default service-credit tracking, backend-configurable",
        "promise": "Create a referral code, single-service or all-service link bundle, no-website social QR, and weekly verified payout path.",
        "required_inputs": ["affiliate name", "phone or social handle", "payout method", "payout destination", "service lane to promote", "optional social profile URL for QR"],
        "client_gets": ["referral code", "service-specific referral links", "all-service bundle option", "social-profile QR image when supplied", "CodeEmail owner record", "affiliate ledger visibility after paid sales"],
        "delivery_room_slots": ["open affiliate page", "copy referral links", "download/copy social QR image URL", "view weekly summary", "owner payout status"],
        "paywall_rule": "Affiliate registration is free; payouts only happen after Stripe records a paid sale with the ref code, refund risk is reviewed, and owner marks payout status.",
        "accessibility_default": "Affiliate can start with only a social profile and does not need a website before sharing links.",
    },
    "veteran-mission-qrcodee": {
        "schema": "codee.service-contract.v1",
        "service": "veteran-mission-qrcodee",
        "public_name": "Veteran Mission QRCodee",
        "price_lane": "0 veteran / paid business service",
        "promise": "Create a free veteran Codee app with public-safe profile, support button, QR target, business referral links, and proof report.",
        "required_inputs": ["public-safe veteran display name", "support destination", "QR target", "mission support need", "business service lane to offer"],
        "client_gets": ["veteran app route", "support button", "QR image slot", "referral code", "business service links", "proof report"],
        "delivery_room_slots": ["open veteran app", "copy QR target", "open QRCodee business path", "capture referral lead", "review proof"],
        "paywall_rule": "The veteran app is free for the veteran; businesses use normal Codee paid-service, checkout, delivery, support, and proof paths with the veteran ref attached.",
        "accessibility_default": "Large support and business buttons, public-safe copy, no checkout prompt for the veteran, and visible proof language.",
    },
    "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": "CodeeFlyer",
        "price_lane": "99",
        "promise": "Create or redesign one hosted flyer from a prompt, a reference image, or both, then add a verified lower-corner QRCodee and up to three live actions.",
        "required_inputs": ["business name", "client email", "flyer brief", "reference image optional", "one to three CTA labels and destinations", "logo or brand color"],
        "client_gets": ["AI-designed or redesigned hosted flyer", "up to three CTA buttons", "verified QR image", "delivery room", "route proof", "30 days of support"],
        "delivery_room_slots": ["view and approve flyer proof", "open hosted flyer", "download/share QR", "CTA proof", "support status"],
        "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.",
    },
    "codeeflyer300": {
        "schema": "codee.service-contract.v1",
        "service": "codeeflyer300",
        "public_name": "CodeeFlyer",
        "price_lane": "99",
        "promise": "Legacy CodeeFlyer300 requests resolve to the same unified CodeeFlyer contract: prompt/reference redesign, verified lower-corner QRCodee, and up to three live actions.",
        "required_inputs": ["business name", "client email", "flyer brief", "reference image optional", "one to three CTA labels and destinations", "logo or brand color"],
        "client_gets": ["paid project room", "AI-designed or redesigned flyer", "verified QR image", "hosted flyer", "up to three actions", "30 days of support"],
        "delivery_room_slots": ["view and approve flyer proof", "open hosted flyer", "QR asset proof", "CTA proof", "support status"],
        "paywall_rule": "Payment opens the delivery room first; QR assets are created immediately, then the AI flyer proof is generated and composed with the QR overlay.",
        "accessibility_default": "Short approval copy, clear approve/reject action, and no hidden delivery terms.",
    },
    "codeeblog": {
        "schema": "codee.service-contract.v1",
        "service": "codeeblog",
        "public_name": "CodeeBlog",
        "price_lane": "100",
        "promise": "Create a hosted blog/resource hub with logo, topic tiles, guide links, offers, capture path, and delivery room.",
        "required_inputs": ["business name", "client email", "blog or resource topic", "logo or brand color", "guide/resource links", "primary capture or offer link"],
        "client_gets": ["hosted blog shell", "resource tile layout", "guide/offer links", "capture path", "delivery room"],
        "delivery_room_slots": ["open blog shell", "test guide/resource links", "test capture path", "request edits", "upgrade to app, card, or suite"],
        "paywall_rule": "Blog shell preview can be scoped first; live hosted blog, resource route, and delivery room unlock after payment.",
        "accessibility_default": "Readable topic cards, obvious guide links, clear capture button, and no hidden offer route.",
    },
    "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 supported personal or business card site with profile, QR, booking/message path, reusable contact proof, and Codee/owner review access for positioning.",
        "required_inputs": ["name or brand", "client email", "portrait or logo", "contact links", "booking or message preference", "main audience", "main offer or credibility proof"],
        "client_gets": ["CodeeCard profile", "QR/contact section", "message path", "booking room link when requested", "Codee support route", "owner review note when needed", "delivery room"],
        "delivery_room_slots": ["open card", "test message path", "test booking path", "download/share QR", "request edits", "request positioning review"],
        "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.",
    },
    "minicodeesite": {
        "schema": "codee.service-contract.v1",
        "service": "minicodeesite",
        "public_name": "Mini CodeeSite",
        "price_lane": "497",
        "promise": "Create a simple 3-5 page website shell with clean frontend design, primary CTA, private preview, and Codee CLI-assisted setup. Backend-heavy work routes to owner review.",
        "required_inputs": ["business name", "client email", "primary offer", "brand assets", "3-5 desired pages", "main CTA", "checkout/booking link if already available"],
        "client_gets": ["3-5 page frontend shell", "primary CTA", "private preview", "delivery-room record", "approval state"],
        "delivery_room_slots": ["open Mini CodeeSite preview", "review 3-5 page shell", "test CTA", "request approved revision", "review final hosted delivery"],
        "paywall_rule": "The simple shell unlocks after Stripe payment and approval. Custom backend support, full CMS, e-commerce, integrations, and unlimited revisions require separate owner review.",
        "accessibility_default": "Tier choices are plain language and the page keeps the buy/edit/support actions visible.",
    },
    "minicodeesite-template": {
        "schema": "codee.service-contract.v1",
        "service": "minicodeesite-template",
        "public_name": "MiniCodeeSite Template License",
        "price_lane": "497",
        "promise": "Package a small-site template/license path for clients who need the simplest launch-ready shell before support.",
        "required_inputs": ["business name", "client email", "chosen template", "logo or brand color", "primary CTA", "target URL"],
        "client_gets": ["template/license packet", "starter shell", "QR-ready public link or plan", "delivery room", "upgrade path"],
        "delivery_room_slots": ["open starter shell", "review template checklist", "test CTA", "request upgrade"],
        "paywall_rule": "Template/license packet unlocks after payment; custom supported edits require the launch or suite tier.",
        "accessibility_default": "Simple template proof with one primary action and no hidden custom-work promise.",
    },
    "minicodeesite-launch": {
        "schema": "codee.service-contract.v1",
        "service": "minicodeesite-launch",
        "public_name": "MiniCodeeSite Launch Kit",
        "price_lane": "1500",
        "promise": "Build the mid-tier launch kit with site shell, key offer sections, QR path, checkout/booking proof, and delivery room.",
        "required_inputs": ["business name", "client email", "offer", "logo/photos", "checkout or booking route", "launch deadline", "support preference"],
        "client_gets": ["launch-site shell", "offer sections", "QR path", "checkout/booking proof", "delivery room"],
        "delivery_room_slots": ["open launch shell", "test buyer or booking path", "review asset checklist", "request first edits", "upgrade to supported build"],
        "paywall_rule": "Launch kit work starts after payment; ongoing supported edits remain a higher-tier support lane.",
        "accessibility_default": "Sections are short, CTA route is visible, and launch status is clear.",
    },
    "codee-business-suite": {
        "schema": "codee.service-contract.v1",
        "service": "codee-business-suite",
        "public_name": "Codee Business Suite",
        "price_lane": "2500",
        "slot_limit": 10,
        "promise": "Reserve one of 10 premium Codee Business Suite slots for a deeper supported build: backend support, private consultation, QR/flyer/card/site assets, request room, and launch handoff.",
        "required_inputs": ["business name", "client email", "decision maker", "business model", "primary offer", "brand assets", "current website/domain", "payment path", "booking/contact path", "storage/file needs", "backend or automation needs", "top 3 launch goals", "private consultation preference", "30-day support priority"],
        "client_gets": ["suite strategy intake", "multi-page business site or shell", "QRCodee image", "CodeeFlyer100 or CodeeFlyer300 direction", "CodeeCard", "backend/support review", "private consultation path", "30-day request lane", "delivery proof"],
        "delivery_room_slots": ["open suite site", "product library", "backend/support checklist", "private consultation notes", "edit requests", "video room", "WordPress/Google/Stripe temporary connect if requested"],
        "paywall_rule": "Only 10 client slots are available at the $2,500 package price. Stripe/Klarna payment verification reserves the slot and unlocks the suite work order, private consultation path, delivery folder, and support month.",
        "accessibility_default": "Business owner sees the site, products, edit queue, and support actions without hunting through long text.",
    },
    "codeeauthority": {
        "schema": "codee.service-contract.v1",
        "service": "codeeauthority",
        "public_name": "CodeeAuthority",
        "price_lane": "250",
        "status": "owner-review",
        "promise": "Prepare an authority/search visibility packet only when owner review approves the use case and claims.",
        "required_inputs": ["business name", "client email", "authority topic", "proof links", "allowed claims", "target page"],
        "client_gets": ["authority packet", "search/readiness checklist", "claim-safety notes", "delivery room", "owner review status"],
        "delivery_room_slots": ["review authority scope", "verify claims", "open target page", "owner approval status"],
        "paywall_rule": "Backend supports the lane, but normal public promotion stays paused until owner review approves it.",
        "accessibility_default": "Claims are written plainly, review status is visible, and unsafe guarantees are blocked.",
    },
    "sean-review-room": {
        "schema": "codee.service-contract.v1",
        "service": "sean-review-room",
        "public_name": "Sean Review Room",
        "price_lane": "200",
        "status": "private-review",
        "promise": "Offer a private consultation/review room only after an audit creates enough context for the human review.",
        "required_inputs": ["audit report or waiting-room context", "client email", "review question", "preferred time", "receipt or checkout status"],
        "client_gets": ["consultation room", "video/review path", "audit context summary", "receipt note", "follow-up support path"],
        "delivery_room_slots": ["open consultation room", "review audit context", "confirm booking/receipt", "next support action"],
        "paywall_rule": "Do not advertise as a normal Codee Chat product; show after audit context or owner-directed review.",
        "accessibility_default": "Review purpose, receipt state, and next action are visible before the client joins the room.",
    },
}

CODEE_DOMAIN_SUPPORT_SERVICES = {
    "free-audit",
    "audit-site",
    "codeeqr",
    "codeeflyer",
    "codeeflyer300",
    "codeeflyer250",
    "codeeblog",
    "codeeapp250",
    "codeecard",
    "codeebeeper",
    "minicodeesite",
    "minicodeesite-template",
    "minicodeesite-launch",
    "codee-business-suite",
    "codeeauthority",
    "sean-review-room",
}

CODEE_DOMAIN_SUPPORT_POLICY = {
    "schema": "codee.domain-support.v1",
    "question": "Before checkout: should this stay on the Codee delivery link, or should Codee prepare a custom domain / white-label support path later? Reply CODEE LINK, OWN DOMAIN, NOT SURE, or paste the domain.",
    "default": "codee-link",
    "client_owned_rule": "The client owns and controls the domain. Codee only gives DNS guidance or support after the client authorizes it.",
    "support_value": "Monthly support can include domain guidance, DNS checks, route scans, SSL/HTTPS checks, redirects, and white-label handoff notes.",
    "guardrail": "Do not require a custom domain to buy. Keep the Codee delivery room as the control room even when the public site later points to the client's domain.",
}

CODEE_CHAT_SERVICE_SCRIPT = [
    {
        "id": "free-audit",
        "chat_service": "site-audit",
        "label": "Free Audit",
        "url": f"{DEFAULT_API_BASE}/codee-chat.html?service=site-audit&autostart=1",
        "status": "public",
        "checkout": "No checkout",
        "price_lane": "0",
        "intake": "Site/profile audit intake",
        "delivery": "Audit report and browser save page",
        "client_bucket": "Audit page or report URL",
        "advertise": "Ready",
        "note": "Best first step before Sean review or paid services.",
    },
    {
        "id": "codeeqr",
        "chat_service": "codeeqr",
        "label": "QRCODEE",
        "url": f"{DEFAULT_API_BASE}/codee-chat.html?service=codeeqr&autostart=1",
        "status": "public",
        "checkout": "$49 secure checkout",
        "price_lane": "49",
        "intake": "QR target, logo/color, link or phone",
        "delivery": "QR image, hosted scan page, browser delivery room",
        "client_bucket": "clients.codee.chat/qr-codee/<client>",
        "advertise": "Ready",
        "note": "Ready for QR preload intake advertising.",
    },
    {
        "id": "codee-affiliate",
        "chat_service": "affiliate",
        "label": "Codee Affiliate Lane",
        "url": f"{DEFAULT_API_BASE}/codee-affiliate.html",
        "status": "public",
        "checkout": "No purchase required",
        "price_lane": "10% default payout on Stripe-verified sales",
        "intake": "Name, phone/social handle, payout method, payout destination, service lane, optional social profile URL",
        "delivery": "Reference code, one-service or all-service link bundle, social QR image, weekly payout review date",
        "client_bucket": "clients.codee.chat/codee-ai-k9/affiliate/partners/<referral_code>",
        "advertise": "Ready with no-income-guarantee guardrail",
        "note": "Use this when someone has no website but can promote Codee from a social profile or direct link.",
    },
    {
        "id": "veteran-mission-qrcodee",
        "chat_service": "mission-qrcodee",
        "label": "Veteran Mission QRCodee",
        "url": CODEE_VETERAN_MISSION_QRCODEE_URL,
        "status": "public",
        "checkout": "Free for veteran; business clients use normal Codee checkout paths",
        "price_lane": "0 veteran / paid business service",
        "intake": "Public-safe veteran profile, support destination, QR target, referral code, and business service lane",
        "delivery": "Veteran Codee app, QR image slot, support button, business referral links, and proof report",
        "client_bucket": "clients.codee.chat/veteran-qrcodee.html?veteran=<veteran_id>",
        "advertise": "Ready as mission lane with owner-approved veteran profile",
        "note": "Use this when a homeless or disabled veteran receives a free Codee app while businesses route through QRCodee and other paid Codee lanes with the veteran ref attached.",
    },
    {
        "id": "codeeflyer",
        "chat_service": "digiflyer",
        "tier": "300",
        "label": "CodeeFlyer",
        "url": f"{DEFAULT_API_BASE}/codee-chat.html?service=digiflyer&tier=300&autostart=1",
        "status": "public",
        "checkout": "$99 secure checkout",
        "price_lane": "99",
        "intake": "Flyer prompt, optional reference, logo/assets, colors, and one to three action destinations",
        "delivery": "AI-designed or redesigned flyer, verified lower-corner QRCodee, approval room, hosted flyer, up to three live actions, and 30 days of support",
        "client_bucket": "clients.codee.chat/codeeflyer/<tier>/<client>",
        "advertise": "Ready with cadence cap",
        "note": "Legacy CodeeFlyer100/250/300 names resolve to this one public lane.",
    },
    {
        "id": "minicodeesite",
        "chat_service": "minicodeesite",
        "label": "Mini CodeeSite",
        "url": f"{DEFAULT_API_BASE}/codee-chat.html?service=minicodeesite&autostart=1",
        "status": "owner-review",
        "checkout": "$497 secure checkout",
        "price_lane": "497",
        "intake": "Business, offer, assets, 3-5 desired pages, CTA, checkout/booking link if available",
        "delivery": "Simple 3-5 page website shell, primary CTA, private preview, and delivery-room record",
        "client_bucket": "clients.codee.chat/minicodeesite/<tier>/<client>",
        "advertise": "Private audit lane only",
        "note": "Keep this out of the normal public menu. It may be recommended privately after an audit and owner review.",
    },
    {
        "id": "codeeblog",
        "chat_service": "codeeblog",
        "label": "CodeeBlog",
        "url": f"{DEFAULT_API_BASE}/codee-chat.html?service=codeeblog&autostart=1",
        "status": "paused",
        "new_order_allowed": False,
        "existing_deliverables_accessible": True,
        "owner_reactivation_required": True,
        "recommended_alternative": "mini_codeesite",
        "checkout": "Secure checkout",
        "price_lane": "100",
        "intake": "Blog home, topics, covers, guide links, capture destination",
        "delivery": "Hosted blog shell, guide/resource layout, capture path",
        "client_bucket": "clients.codee.chat/codeeblog/<tier>/<client>",
        "advertise": "Paused as standalone. Route this need through MiniCodeeSite or Codee Business Suite.",
        "note": "Legacy lane retained for existing fulfillment and owner-reviewed builds.",
    },
    {
        "id": "codeeapp250",
        "chat_service": "digiapp",
        "label": "CodeeApp250",
        "url": f"{DEFAULT_API_BASE}/codee-chat.html?service=digiapp&autostart=1",
        "status": "paused",
        "new_order_allowed": False,
        "existing_deliverables_accessible": True,
        "owner_reactivation_required": True,
        "recommended_alternative": "mini_codeesite",
        "checkout": "$250 secure checkout or connected client Stripe guidebook checkout",
        "price_lane": "250",
        "intake": "Guidebook cover, bullet copy, buyer checkout, hosted download URL",
        "delivery": "Hosted guidebook/app page, QRCodee image, buy button, delivery room",
        "client_bucket": "clients.codee.chat/codeeapp250/<client>",
        "advertise": "Paused as standalone. Route this need through MiniCodeeSite or Codee Business Suite.",
        "note": "Legacy guidebook/app lane retained for existing fulfillment and owner-reviewed builds.",
    },
    {
        "id": "codeecard",
        "chat_service": "codeecard",
        "label": "CodeeCard",
        "url": f"{DEFAULT_API_BASE}/codee-chat.html?service=codeecard&autostart=1",
        "status": "public",
        "checkout": "$250 secure checkout",
        "price_lane": "250",
        "intake": "Brand, primary action, tile stack, audience, offer/proof",
        "delivery": "Hosted square-tile link hub with QR, action tiles, Codee support route, and owner review note when needed",
        "client_bucket": "clients.codee.chat/codeecard/<tier>/<client>",
        "advertise": "Ready",
        "note": "Use as the clean personal or business profile card.",
    },
    {
        "id": "codeebeeper",
        "chat_service": "codeevault",
        "label": "CodeeBeeper",
        "url": f"{DEFAULT_API_BASE}/codee-beeper.html",
        "status": "paused_owner_review",
        "checkout": "$149 one-time storage/vault checkout",
        "price_lane": "149",
        "intake": "PIN, note-to-self, uploads, media storage, owner reset path",
        "delivery": "Private storage tool, note thread, upload vault, browser delivery room",
        "client_bucket": "clients.codee.chat/codeebeeper/<client>",
        "advertise": "Paused as standalone. Route this need through MiniCodeeSite or Codee Business Suite.",
        "note": "Legacy vault lane retained for existing fulfillment and owner-reviewed builds.",
    },
    {
        "id": "codee-business-suite",
        "chat_service": "minicodeesite",
        "tier": "supported-build",
        "label": "Codee Business Suite",
        "url": f"{DEFAULT_API_BASE}/codee-chat.html?service=minicodeesite&tier=supported-build&autostart=1",
        "status": "public",
        "checkout": "$2,500 secure checkout with Klarna/eligible wallet support when Stripe allows",
        "price_lane": "2500",
        "intake": "Long-form business suite intake: decision maker, business model, offer, assets, domain/site, payments, booking, storage, backend needs, top goals, private consultation preference",
        "delivery": "Full package room, backend/support checklist, generated products, private consultation path, video review, editable 30-day request lane",
        "client_bucket": "clients.codee.chat/codee-business-suite/<client>",
        "advertise": "Ready as premium package",
        "note": "Only 10 slots at this price. Use when the client needs backend support and more access to Codee/Sean than a MiniCodeeSite shell.",
    },
    {
        "id": "sean-review-room",
        "chat_service": "consultation",
        "label": "Sean Review Room",
        "url": f"{DEFAULT_API_BASE}/consultation/",
        "status": "private review",
        "checkout": "$200 embedded consultation checkout",
        "price_lane": "200",
        "intake": "Audit waiting-room context before booking",
        "delivery": "Audit waiting room, calendar invite, video room, receipt note",
        "client_bucket": "Booklyn consultation room",
        "advertise": "Audit-only upsell",
        "note": "Not a Codee Chat product; only after audit context.",
    },
]

CODEE_CHAT_SERVICE_SCRIPT_MODEL = {
    "ok": True,
    "schema": "codee.chat-services.v1",
    "version": VERSION,
    "updated_at": "2026-05-30",
    "source": "Codee original/frontend-public/admin-production.html serviceReadinessRows and codee-chat.html SERVICE_CATALOG",
    "manifest_url": CODEE_CHAT_SERVICES_MANIFEST_URL,
    "rule": "Keep Codee CLI service names, public delivery promises, and Codee.chat URLs aligned before advertising any service.",
    "services": CODEE_CHAT_SERVICE_SCRIPT,
    "owner_review_services": [
        {
            "id": "codeeauthority",
            "chat_service": "codeeauthority",
            "label": "CodeeAuthority",
            "status": "owner-review",
            "checkout": "$250 secure checkout after owner approval",
            "price_lane": "250",
            "intake": "Authority topic, proof links, allowed claims, target page",
            "delivery": "Authority/readiness packet, claim-safety notes, and delivery room",
            "advertise": "Paused until owner review approves the use case",
            "note": "Backend-supported lane, but not part of the normal Codee.chat public menu today.",
        }
    ],
}

REV001_PUBLIC_SERVICE_IDS = {
    "free-audit",
    "codeeqr",
    "codeeflyer",
    "codee-affiliate",
}

CODEE_AUDIT_LADDER_MODEL = {
    "schema": "codee.audit-ladder.v1",
    "version": VERSION,
    "manifest_url": CODEE_AUDIT_LADDER_MANIFEST_URL,
    "service_manifest_url": CODEE_CHAT_SERVICES_MANIFEST_URL,
    "flow": "free_audit_to_small_paid_lane_to_suite_when_ready",
    "rule": "Do not jump a cold client straight to the $2,500 suite. Start with proof, report, and the smallest useful paid lane.",
    "steps": [
        {
            "id": "free-audit",
            "label": "Free audit",
            "price_lane": "0",
            "command": "codee audit . --service free-audit --write",
            "client_value": "No-card scorecard, report packet, delivery room, and next recommendation.",
        },
        {
            "id": "codeeqr",
            "label": "QR image site",
            "price_lane": "49",
            "command": "codee preview . --service codeeqr --dry-run",
            "client_value": "Fastest paid conversion: branded QR image, landing page, scan proof, and delivery room.",
        },
        {
            "id": "codee-affiliate",
            "label": "Affiliate link bundle",
            "price_lane": "0",
            "command": "codee preview . --service codee-affiliate --dry-run",
            "client_value": "No-website social QR, reference code, one-service or all-service referral links, and weekly Stripe-verified payout review.",
        },
        {
            "id": "audit-site",
            "label": "Audit site delivery room",
            "price_lane": "149",
            "command": "codee preview . --service audit-site --dry-run",
            "client_value": "Hosted audit report with fix queue and support room.",
        },
        {
            "id": "codeeflyer100",
            "label": "Flyer or offer page",
            "price_lane": "100",
            "command": "codee preview . --service codeeflyer100 --dry-run",
            "client_value": "One image or offer becomes a hosted flyer with CTA and QR proof.",
        },
        {
            "id": "codeeflyer300",
            "label": "AI generated premium flyer",
            "price_lane": "300",
            "command": "codee preview . --service codeeflyer300 --dry-run",
            "client_value": "AI-generated hosted flyer with QR overlay, approval room, and revision tracking.",
        },
        {
            "id": "codeeblog",
            "label": "Blog/resource hub",
            "price_lane": "100",
            "command": "codee preview . --service codeeblog --dry-run",
            "client_value": "Guide/resource hub with offers, capture path, and delivery room.",
        },
        {
            "id": "codeeapp250",
            "label": "Mini product/app page",
            "price_lane": "250",
            "command": "codee preview . --service codeeapp250 --dry-run",
            "client_value": "Guidebook, checklist, card, or product page with buyer path and delivery room.",
        },
        {
            "id": "codeecard",
            "label": "Profile/card site",
            "price_lane": "250",
            "command": "codee preview . --service codeecard --dry-run",
            "client_value": "Square-tile profile card with QR, contact, booking, shop, or donation routes.",
        },
        {
            "id": "codeebeeper",
            "label": "Private vault",
            "price_lane": "149",
            "command": "codee preview . --service codeebeeper --dry-run",
            "client_value": "Private note/media storage workspace with PIN, upload slots, and delivery room.",
        },
        {
            "id": "minicodeesite",
            "label": "Mini CodeeSite",
            "price_lane": "497",
            "command": "codee preview . --service minicodeesite --dry-run",
            "client_value": "Create a simple three-to-five-page website shell with a primary CTA, private preview, and approval before hosted delivery.",
        },
        {
            "id": "codee-business-suite",
            "label": "Business Suite",
            "price_lane": "2500",
            "command": "codee preview . --service business-suite --dry-run",
            "client_value": "Full done-for-you launch package after the client understands the smaller lane proof.",
        },
        {
            "id": "sean-review-room",
            "label": "Private review room",
            "price_lane": "200",
            "command": "codee preview . --service sean-review-room --dry-run",
            "client_value": "Audit-only consultation/review lane when the client needs a human review after context exists.",
        },
    ],
}

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": "CodeeFlyer",
        "required_uploads": ["flyer brief", "reference image optional", "logo or brand mark", "one to three CTA destinations", "brand color"],
        "must_have": [
            ("index.html", "The hosted flyer page exists."),
            ("target_url", "At least one flyer action target 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."),
        ],
    },
    "codeeflyer300": {
        "label": "CodeeFlyer",
        "required_uploads": ["flyer brief", "reference image optional", "logo or brand mark", "one to three CTA destinations", "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.",
        },
    ]
)


# --- Lightweight client integration and webhook helpers (admin-facing) ---

import hmac
import hashlib as _hashlib

# Add gcloud helper for admin troubleshooting and secret inspection
def _manage_gcloud_cli(argv: list[str]) -> None:
    """Simple helper to run gcloud checks from the admin CLI.
    Usage:
      codee-cli gcloud check                # prints gcloud version, auth list, project
      codee-cli gcloud secrets              # lists secrets in configured project (JSON)
      codee-cli gcloud secrets <SECRET>     # prints latest secret value (if permitted)
    """
    import subprocess
    try:
        if not argv:
            print('Usage: codee-cli gcloud check|secrets [SECRET_NAME]')
            return
        action = argv[0]
        if action == 'check':
            # gcloud version
            try:
                p = subprocess.run(['gcloud', '--version'], capture_output=True, text=True, check=False)
                print('gcloud --version:')
                print(p.stdout or p.stderr)
            except Exception as e:
                print('Failed to run gcloud --version:', str(e))
            # auth list
            try:
                p = subprocess.run(['gcloud', 'auth', 'list', '--format=json'], capture_output=True, text=True, check=False)
                print('\ngcloud auth list:')
                print(p.stdout or p.stderr)
            except Exception as e:
                print('Failed to run gcloud auth list:', str(e))
            # project
            try:
                p = subprocess.run(['gcloud', 'config', 'get-value', 'project'], capture_output=True, text=True, check=False)
                proj = (p.stdout or '').strip()
                print('\nConfigured project:', proj or '(none)')
            except Exception as e:
                print('Failed to get gcloud project:', str(e))
            return
        if action == 'secrets':
            # need project
            try:
                p = subprocess.run(['gcloud', 'config', 'get-value', 'project'], capture_output=True, text=True, check=False)
                proj = (p.stdout or '').strip()
            except Exception as e:
                print('Failed to get gcloud project:', str(e))
                return
            if not proj:
                print('No gcloud project configured. Run: gcloud config set project <PROJECT>')
                return
            # list secrets or show a secret
            if len(argv) == 1:
                # list secrets as JSON
                try:
                    p = subprocess.run(['gcloud', 'secrets', 'list', '--project', proj, '--limit=500', '--format=json'], capture_output=True, text=True, check=False)
                    print(p.stdout or p.stderr)
                except Exception as e:
                    print('Failed to list secrets:', str(e))
                return
            # show secret value (may require permissions)
            secret_name = argv[1]
            try:
                p = subprocess.run(['gcloud', 'secrets', 'versions', 'access', 'latest', '--secret', secret_name, '--project', proj], capture_output=True, text=True, check=False)
                if p.returncode == 0:
                    print(p.stdout)
                else:
                    print('Error accessing secret:', p.stderr or p.stdout)
            except Exception as e:
                print('Failed to access secret:', str(e))
            return
        print('Unknown gcloud action. Usage: codee-cli gcloud check|secrets [SECRET_NAME]')
    except Exception as e:
        print('gcloud helper failed:', str(e))

# Admin helper paths
def _admin_dir_path() -> str:
    d = os.path.join(Path.home(), '.codee_admin')
    os.makedirs(d, exist_ok=True)
    return d

def _ensure_prompts_dir() -> str:
    p = os.path.join(_admin_dir_path(), 'prompts')
    os.makedirs(p, exist_ok=True)
    return p

def _save_prompt_template(name: str, prompt: str) -> str:
    pdir = _ensure_prompts_dir()
    fname = os.path.join(pdir, f"{name}.txt")
    with open(fname, 'w', encoding='utf8') as f:
        f.write(prompt)
    return fname

def _list_prompt_templates() -> list[str]:
    pdir = _ensure_prompts_dir()
    try:
        return [f for f in os.listdir(pdir) if f.endswith('.txt')]
    except Exception:
        return []

# Preview token secret management
def _preview_secret_path() -> str:
    return os.path.join(_admin_dir_path(), 'preview_secret.json')

def _get_preview_secret() -> bytes:
    # prefer env var
    env = os.getenv('CODEE_PREVIEW_SECRET')
    if env:
        return env.encode('utf8')
    try:
        p = _preview_secret_path()
        if os.path.exists(p):
            data = json.loads(open(p, 'r', encoding='utf8').read() or '{}')
            if data.get('secret'):
                return data['secret'].encode('utf8')
    except Exception:
        pass
    # create and persist a new secret
    secret = _hashlib.sha256(os.urandom(64)).hexdigest()
    try:
        with open(_preview_secret_path(), 'w', encoding='utf8') as f:
            json.dump({'secret': secret}, f)
    except Exception:
        pass
    return secret.encode('utf8')

def _hmac_sign(message: str) -> str:
    secret = _get_preview_secret()
    return hmac.new(secret, message.encode('utf8'), _hashlib.sha256).hexdigest()

def _generate_preview_token(client_id: str, ttl: int = 3600) -> str:
    expires = int(time.time()) + int(ttl)
    payload = json.dumps({'client_id': client_id, 'exp': expires}, separators=(',', ':'))
    sig = _hmac_sign(payload)
    token = f"{payload}.{sig}"
    # For safety store a local mapping
    try:
        store = os.path.join(_admin_dir_path(), 'previews.json')
        data = {}
        if os.path.exists(store):
            data = json.loads(open(store, 'r', encoding='utf8').read() or '{}')
        data_entry = {'client_id': client_id, 'exp': expires, 'token_sig': sig}
        data[client_id] = data_entry
        with open(store, 'w', encoding='utf8') as f:
            json.dump(data, f)
    except Exception:
        pass
    return token

def _verify_preview_token(token: str) -> dict:
    try:
        if '.' not in token:
            return {'ok': False, 'error': 'invalid_format'}
        payload_b, sig = token.rsplit('.', 1)
        payload = payload_b
        expected = _hmac_sign(payload)
        if not hmac.compare_digest(expected, sig):
            return {'ok': False, 'error': 'invalid_signature'}
        data = json.loads(payload)
        if int(time.time()) > int(data.get('exp', 0)):
            return {'ok': False, 'error': 'expired'}
        return {'ok': True, 'client_id': data.get('client_id'), 'exp': data.get('exp')}
    except Exception as e:
        return {'ok': False, 'error': str(e)}

# Helper to persist webhook locally on fallback
def _persist_webhook_local(url: str, events: list | None = None, name: str | None = None):
    try:
        store = os.path.join(_admin_dir_path(), 'webhooks.json')
        data = json.loads(open(store, 'r', encoding='utf8').read() or '[]') if os.path.exists(store) else []
        entry = {'url': url, 'events': events or [], 'name': name, 'created_at': int(time.time())}
        data.append(entry)
        with open(store, 'w', encoding='utf8') as f:
            json.dump(data, f, indent=2)
        return True
    except Exception:
        return False

def _http_request(method: str, path: str, data: Any = None, extra_headers: dict | None = None) -> tuple[int, dict | str]:
    """Simple HTTP request helper against the CODEE backend. Returns (status, parsed_json_or_text)."""
    url = CODEE_BACKEND_API_BASE.rstrip('/') + path
    headers = {'Content-Type': 'application/json', 'User-Agent': f'codee-cli/{VERSION}'}
    if extra_headers:
        headers.update(extra_headers)
    body = None
    if data is not None:
        body = json.dumps(data).encode('utf8')
    req = urllib.request.Request(url, data=body, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=20) as resp:
            raw = resp.read()
            text = raw.decode('utf8', errors='ignore')
            try:
                return resp.getcode(), json.loads(text)
            except Exception:
                return resp.getcode(), text
    except urllib.error.HTTPError as e:
        try:
            return e.code, json.loads(e.read().decode('utf8'))
        except Exception:
            return e.code, str(e)
    except Exception as e:
        return 0, str(e)


def _print_remote_curl_template_for_webhook(action: str, url: str, events: list[str] | None = None, name: str | None = None):
    payload = {'url': url}
    if events:
        payload['events'] = events
    if name:
        payload['name'] = name
    curl = (
        f"curl -X POST '{CODEE_BACKEND_API_BASE.rstrip('/')}/admin/webhooks' \\"
        f" -H 'Content-Type: application/json' \\"
        f" -d '{json.dumps(payload)}'"
    )
    print('\nRemote webhook curl template (run on admin host or in a secure environment):')
    print(curl)


from http.server import BaseHTTPRequestHandler, HTTPServer
import threading

class _DevWebhookHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        length = int(self.headers.get('content-length', '0'))
        body = self.rfile.read(length) if length else b''
        text = body.decode('utf8', errors='ignore')
        print('\n--- webhook received ---')
        print('Path:', self.path)
        print('Headers:')
        for k, v in self.headers.items():
            print(f'  {k}: {v}')
        print('Body:')
        print(text)
        print('--- end webhook ---\n')
        # Simple echo response
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        self.wfile.write(b'{"ok": true}')


def _start_local_webhook_listener(port: int = 8181):
    server = HTTPServer(('0.0.0.0', port), _DevWebhookHandler)
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    print(f'Listening for webhooks on http://0.0.0.0:{port}/ — press Ctrl-C to stop')
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print('Shutting down webhook listener...')
        server.shutdown()
        server.server_close()


def _manage_webhook_cli(argv: list[str]):
    # subcommands: add --url <url> --events ev1,ev2 --name <name>
    #             list
    #             remove --id <id>
    #             listen --port <port>
    if len(argv) < 3:
        print('Usage: codee-cli webhook <add|list|remove|listen> [options]')
        return
    sub = argv[2]
    if sub == 'listen':
        port = 8181
        for i, a in enumerate(argv):
            if a in ('--port', '-p') and i + 1 < len(argv):
                try:
                    port = int(argv[i + 1])
                except Exception:
                    pass
        _start_local_webhook_listener(port)
        return

    if sub == 'list':
        status, data = _http_request('GET', '/admin/webhooks')
        if status and status >= 200 and status < 300:
            print('Registered webhooks:')
            print(json.dumps(data, indent=2))
            return
        print('Failed to list remote webhooks, fallback:')
        print(data)
        return

    if sub == 'remove':
        # expect --id <id>
        idv = None
        for i, a in enumerate(argv):
            if a in ('--id',):
                idv = argv[i + 1] if i + 1 < len(argv) else None
        if not idv:
            print('Usage: codee-cli webhook remove --id <id>')
            return
        status, data = _http_request('DELETE', f'/admin/webhooks/{urllib.parse.quote(idv)}')
        if status and 200 <= status < 300:
            print('Removed webhook:', idv)
            return
        print('Failed to remove webhook remotely, fallback:')
        print(data)
        return

    if sub == 'add':
        url = None
        events = None
        name = None
        for i, a in enumerate(argv):
            if a in ('--url',) and i + 1 < len(argv): url = argv[i + 1]
            if a in ('--events',) and i + 1 < len(argv): events = argv[i + 1].split(',')
            if a in ('--name',) and i + 1 < len(argv): name = argv[i + 1]
        if not url:
            print('Usage: codee-cli webhook add --url <https://...> [--events ev1,ev2] [--name <name>]')
            return
        # Try remote registration
        status, data = _http_request('POST', '/admin/webhooks', {'url': url, 'events': events or [], 'name': name})
        if status and 200 <= status < 300:
            print('Webhook registered remotely:', json.dumps(data, indent=2))
            return
        # Fallback: print curl template so admin can run securely on server
        print('Could not register webhook remotely, printing curl template:')
        _print_remote_curl_template_for_webhook('add', url, events, name)
        return

    print('Unknown webhook subcommand:', sub)


def _manage_client_cli(argv: list[str]):
    # subcommands for client integration: connect, status, pull, push
    if len(argv) < 3:
        print('Usage: codee-cli client <connect|status|pull|push> [options]')
        return
    sub = argv[2]
    if sub == 'connect':
        # request a short-lived client token from backend
        payload = {'action': 'client_connect', 'ts': int(time.time())}
        status, data = _http_request('POST', '/admin/client/connect', payload)
        if status and 200 <= status < 300:
            print('Client connect token/info:')
            print(json.dumps(data, indent=2))
            print('\nUse the token in your client CLI to `connect` to the backend.')
            return
        print('Failed to request client connect token remotely:')
        print(data)
        return

    if sub == 'status':
        client_id = None
        for i, a in enumerate(argv):
            if a in ('--id',) and i + 1 < len(argv): client_id = argv[i + 1]
        if not client_id:
            print('Usage: codee-cli client status --id <client_id>')
            return
        status, data = _http_request('GET', f'/admin/client/{urllib.parse.quote(client_id)}/status')
        print('Client status:')
        print(status, data)
        return

    if sub == 'pull':
        client_id = None
        out = None
        for i, a in enumerate(argv):
            if a in ('--id',) and i + 1 < len(argv): client_id = argv[i + 1]
            if a in ('--out',) and i + 1 < len(argv): out = argv[i + 1]
        if not client_id:
            print('Usage: codee-cli client pull --id <client_id> --out <dir>')
            return
        out = out or './client-pull'
        status, data = _http_request('GET', f'/admin/client/{urllib.parse.quote(client_id)}/pull')
        if status and 200 <= status < 300 and isinstance(data, dict) and data.get('archive_url'):
            print('Client package available at:', data['archive_url'])
            print('Download manually or use wget/curl to fetch and extract to', out)
        else:
            print('Failed to pull client package remotely:')
            print(status, data)
        return

    if sub == 'push':
        client_id = None
        package = None
        for i, a in enumerate(argv):
            if a in ('--id',) and i + 1 < len(argv): client_id = argv[i + 1]
            if a in ('--package',) and i + 1 < len(argv): package = argv[i + 1]
        if not client_id or not package:
            print('Usage: codee-cli client push --id <client_id> --package <path.zip>')
            return
        # We provide a curl template for secure upload if direct push is not desirable
        print('To push client package securely, upload the package to the admin server using the following template:')
        print(f"curl -X POST '{CODEE_BACKEND_API_BASE.rstrip('/')}/admin/client/{urllib.parse.quote(client_id)}/push' -H 'Content-Type: multipart/form-data' -F 'package=@{package}'")
        return

    print('Unknown client subcommand:', sub)


# Early CLI intercepts for quick admin tooling
if len(sys.argv) > 1 and sys.argv[1] in ('webhook', 'webhooks'):
    _manage_webhook_cli(sys.argv)
    sys.exit(0)
if len(sys.argv) > 1 and sys.argv[1] in ('client', 'clients'):
    _manage_client_cli(sys.argv)
    sys.exit(0)

CODEE_TOOL_REGISTRY = {
    "schema": "codee.tool-registry.v1",
    "version": VERSION,
    "updated_at": "2026-05-30",
    "purpose": "Public registry for Ai K9 CODEE tools, service lanes, connectors, permission profiles, hooks, skills, 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 Ai K9 CODEE command 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": "audit", "kind": "client", "purpose": "Start the CodeeChat ladder with a free audit, delivery room, report, and smallest paid upsell."},
        {"name": "services", "kind": "client", "purpose": "Show the Codee.chat service menu mirrored into the CLI: audit, QR, flyer, site, blog, app, card, beeper, suite, and review lanes."},
        {"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": "heel", "kind": "support", "purpose": "Military K9-inspired teacher/support packet with login command, diagnosis flow, Codex bridge, and owner handoff."},
        {"name": "owner-dev", "kind": "owner", "purpose": "Write the owner-grade frontend/backend edit workflow packet with checkpoints, proof gates, and download sync steps."},
        {"name": "owner-support", "kind": "owner", "purpose": "Write the owner-only frontend support packet for client edit rescue and outdated CLI triage."},
        {"name": "codex-bridge", "kind": "owner", "purpose": "Write a Codex-readable bridge packet with live CLI URLs, file inventory, enhancement backlog, and proof commands."},
        {"name": "codex-sync", "kind": "owner", "purpose": "Detect local Codex CLI version changes, write Codee parity files, and optionally refresh Codee CLI from the public Codee release."},
        {"name": "browser-scan", "kind": "proof", "purpose": "Use Playwright when available to open a live route, capture screenshot proof, and document visual readiness."},
        {"name": "skills", "kind": "policy", "purpose": "List CODEE's built-in, optional, owner, and backend-gated skills before work starts."},
        {"name": "skill-check", "kind": "proof", "purpose": "Verify local optional skills such as Playwright and report missing install steps."},
        {"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,
        "owner_cli": CODEE_OWNER_CLI_URL,
        "alpha_pack": CODEE_ALPHA_PACK_URL,
        "owner_cli_manifest": CODEE_OWNER_CLI_MANIFEST_URL,
        "owner_dev_manifest": CODEE_OWNER_DEV_MANIFEST_URL,
        "codex_bridge_manifest": CODEE_CODEX_BRIDGE_MANIFEST_URL,
        "codex_parity_manifest": CODEE_CODEX_PARITY_MANIFEST_URL,
        "promotion_greenlight_manifest": CODEE_PROMOTION_GREENLIGHT_MANIFEST_URL,
        "heel_teacher_manifest": CODEE_HEEL_TEACHER_MANIFEST_URL,
        "heal_teacher_manifest_legacy": CODEE_HEAL_TEACHER_MANIFEST_URL,
        "audit_ladder_manifest": CODEE_AUDIT_LADDER_MANIFEST_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",
        "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,
    "owner_cli_url": CODEE_OWNER_CLI_URL,
    "owner_cli_manifest_url": CODEE_OWNER_CLI_MANIFEST_URL,
    "owner_dev_manifest_url": CODEE_OWNER_DEV_MANIFEST_URL,
    "codex_bridge_manifest_url": CODEE_CODEX_BRIDGE_MANIFEST_URL,
    "codex_parity_manifest_url": CODEE_CODEX_PARITY_MANIFEST_URL,
    "promotion_greenlight_manifest_url": CODEE_PROMOTION_GREENLIGHT_MANIFEST_URL,
    "heel_teacher_manifest_url": CODEE_HEEL_TEACHER_MANIFEST_URL,
    "heal_teacher_manifest_legacy_url": CODEE_HEAL_TEACHER_MANIFEST_URL,
    "audit_ladder_manifest_url": CODEE_AUDIT_LADDER_MANIFEST_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-30",
    "status": "audit-ladder-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 audit-first CodeeChat flow: `codee audit` creates a free audit packet, delivery room, report link, paywall preview, and QR/audit-site upsell ladder before Business Suite.",
        "Added Codee HEEL CLI: `codee heel` uses military K9-style handler logic to write the teacher/support packet with login command, diagnosis flow, Codex bridge, owner-dev, and owner-support handoff.",
        "Added Codex Bridge CLI: a downloadable machine-readable handoff so Codex can inspect live URLs, local CLI files, enhancement backlog, owner gates, and proof commands before improving Codee.",
        "Added Owner Dev CLI: a downloadable owner-grade edit workflow for frontend, backend, full-stack, social, and deploy support packets.",
        "Added Owner Support CLI: internal frontend rescue packets, outdated public CLI triage, support-team roles, and owner-only browser page.",
        "Added Meta Page context enrichment so Facebook OAuth can store Page id and Page access token for direct owner-approved Page posting.",
        "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 does not bundle private model keys; use `model-bridge` and `agent-run` for local rules or bring-your-own model commands.",
        "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",
        "Owner Support CLI page and manifest return 200 and stay owner/backend gated for credentials",
        "Owner Dev manifest is synced with the downloadable CLI and proves frontend/backend edit workflow rules",
        "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 = {
    "qrcodee-lane": {
        "name": "QRCodee Lane",
        "audience": "business buying one hosted QR tool",
        "billing": "$49 one-time creation; $19/mo account hosting after the included 30 days",
        "unlocks": ["one QRCodee build", "one scan destination", "delivery proof", "30 included hosting days"],
        "limits": ["does not unlock flyer lanes", "new builds cost $49", "hosting care does not create new tools"],
    },
    "codeeflyer-lane": {
        "name": "CodeeFlyer Lane",
        "audience": "business buying one AI-designed or redesigned hosted flyer",
        "billing": "$99 one-time creation; $19/mo account hosting after the included 30 days",
        "unlocks": ["one CodeeFlyer build", "verified lower-corner QRCodee", "up to three actions", "delivery proof", "30 included hosting days"],
        "limits": ["does not unlock a separate QRCodee build", "new flyer builds cost $99", "hosting care does not create new tools"],
    },
    "hosting-care": {
        "name": "Codee Hosting Care",
        "audience": "client keeping already-purchased Codee links managed and live",
        "billing": "$19/month per client account",
        "unlocks": ["hosting for up to three purchased links", "monthly route and QR check", "one simple link or text update monthly"],
        "limits": ["does not unlock unpurchased lanes", "does not include new builds", "7-day payment grace then managed hosting pauses at period end"],
    },
    "free-trainee": {
        "name": "Codee Trainee",
        "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 Chief",
        "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": "Codee 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", "more private Service Seeds"],
        "limits": ["public service activation still requires Service Creator, Business Suite, or owner-approved checkout proof"],
    },
    "service-creator": {
        "name": "Codee Service Creator",
        "audience": "business or partner turning ideas into public service pages",
        "billing": "$249/mo service creator workspace",
        "unlocks": ["private hosted Service Seeds", "approved public service page requests", "Powered by Codee attribution", "checkout or invoice preparation after owner review"],
        "limits": ["public launch, checkout, and invoice routes still require owner review and active hosting"],
    },
    "business-suite": {
        "name": "Codee Biz",
        "audience": "business buying the full launch bundle",
        "billing": "$2,500 package plus optional hosting/support",
        "unlocks": ["QRCodee", "CodeeFlyer100", "CodeeFlyer300", "CodeeCard", "private audit/site review", "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_PLAN_ALIASES = {
    "qrcodee": "qrcodee-lane",
    "qrcodee_lane": "qrcodee-lane",
    "qrcodee-lane": "qrcodee-lane",
    "codeeflyer": "codeeflyer-lane",
    "codeeflyer-lane": "codeeflyer-lane",
    "flyer100": "codeeflyer-lane",
    "codeeflyer100": "codeeflyer-lane",
    "flyer100-lane": "codeeflyer-lane",
    "flyer250": "codeeflyer-lane",
    "codeeflyer250": "codeeflyer-lane",
    "flyer250-lane": "codeeflyer-lane",
    "flyer300": "codeeflyer-lane",
    "codeeflyer300": "codeeflyer-lane",
    "flyer300-lane": "codeeflyer-lane",
    "bundle": "codeeflyer-lane",
    "business-client": "codeeflyer-lane",
    "business-bundle": "codeeflyer-lane",
    "hosting": "hosting-care",
    "hosting_care": "hosting-care",
    "hosting-care": "hosting-care",
    "trainee": "free-trainee",
    "free": "free-trainee",
    "free-trainee": "free-trainee",
    "chief": "pro",
    "pro": "pro",
    "partner": "partner",
    "creator": "service-creator",
    "service-creator": "service-creator",
    "service_creator": "service-creator",
    "workspace-pro": "service-creator",
    "biz": "business-suite",
    "codee-biz": "business-suite",
    "business-suite": "business-suite",
    "codee-business-suite": "business-suite",
    "owner": "owner-admin",
    "owner-admin": "owner-admin",
}


def _normalize_plan_id(value: str | None) -> str:
    clean = re.sub(r"[^a-z0-9-]+", "-", str(value or "").strip().lower()).strip("-")
    return CODEE_PLAN_ALIASES.get(clean, clean)


def _codee_local_pricing_payload(*, include_review: bool = False) -> dict[str, Any]:
    plans: list[dict[str, Any]] = [
        {
            "id": "qrcodee_lane", "name": "QRCodee Lane", "label": "$49 QRCodee Lane", "amount_cents": 4900,
            "mode": "payment", "interval": "", "invoice_allowed": False,
            "description": "One QRCodee build with the first 30 days of managed hosting included.",
        },
        {
            "id": "codeeflyer_lane", "name": "CodeeFlyer Lane", "label": "$99 CodeeFlyer Lane", "amount_cents": 9900,
            "mode": "payment", "interval": "", "invoice_allowed": False,
            "description": "One AI-designed or redesigned hosted flyer with a verified lower-corner QRCodee, up to three actions, and 30 days of support.",
        },
        {
            "id": "hosting_care", "name": "Codee Hosting Care", "label": "$19/mo Codee Hosting Care", "amount_cents": 1900,
            "mode": "subscription", "interval": "month", "invoice_allowed": False,
            "description": "Keep up to three purchased Codee links managed and live; new builds are not included.",
        },
    ]
    if include_review:
        plans.extend(
            [
                {
                    "id": "codeeauthority",
                    "name": "CodeeAuthority",
                    "label": "$250 CodeeAuthority",
                    "amount_cents": 25000,
                    "mode": "payment",
                    "interval": "",
                    "invoice_allowed": False,
                    "description": "Owner-review authority/search lane. Backend-supported, not shown as a normal public Codee.chat product until approved.",
                },
                {
                    "id": "sean-review-room",
                    "name": "Sean Review Room",
                    "label": "$200 Sean Review Room",
                    "amount_cents": 20000,
                    "mode": "payment",
                    "interval": "",
                    "invoice_allowed": False,
                    "description": "Private audit-only review room with consultation/video-room path after context is collected.",
                },
            ]
        )
    return {
        "ok": True,
        "currency": "usd",
        "source": "local",
        "plans": plans,
    }

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": "minicodeesite", "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": "minicodeesite", "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,
        "owner_cli": CODEE_OWNER_CLI_URL,
        "owner_cli_manifest": CODEE_OWNER_CLI_MANIFEST_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",
        "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",
    },
    "heal_teacher": CODEE_HEEL_TEACHER_MODEL,
    "owner_support": CODEE_OWNER_SUPPORT_MODEL,
    "owner_dev": CODEE_OWNER_DEV_MODEL,
    "codex_bridge": CODEE_CODEX_BRIDGE_MODEL,
}

CODEE_REMOTE_ARCHITECTURE = {
    "schema": "codee.remote.v1",
    "version": VERSION,
    "updated_at": "2026-08-28",
    "positioning": "Codee Remote has two tracks: consent-based browser screen viewing and a four-command Codee bridge. Mouse and keyboard control are not implemented.",
    "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": "live-browser-viewer",
            "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": "live-four-command-bridge",
            "summary": "Phone or browser sends Status, Doctor, Heartbeat, or Scan to the paired Python host. Results and a sanitized audit trail return to the viewer.",
            "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", "browser screen stream", "emergency stop"],
    "cli_bridge_capabilities": ["status", "doctor", "heartbeat", "scan"],
    "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, CodeeCard, MiniCodeeSite, 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, CodeeFlyer, CodeeCard, MiniCodeeSite, or Codee Business Suite.",
            "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", "CodeeFlyer100", "MiniCodeeSite", "CodeeCard"],
        "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", "CodeeCard", "CodeeFlyer100", "MiniCodeeSite"],
        "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", "CodeeFlyer250", "MiniCodeeSite", "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", "CodeeFlyer250", "MiniCodeeSite", "CodeeCard"],
        "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", "MiniCodeeSite", "CodeeFlyer100", "CodeeCard"],
        "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", "CodeeFlyer250", "MiniCodeeSite", "CodeeCard"],
        "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": ["CodeeCard", "QRCodee", "MiniCodeeSite", "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", "CodeeFlyer250", "MiniCodeeSite", "CodeeCard"],
        "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", "CodeeCard", "MiniCodeeSite", "CodeeFlyer100"],
        "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", "CodeeFlyer250", "CodeeCard", "MiniCodeeSite"],
        "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, headers: dict[str, str] | None = None) -> 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])
    for key, value in (headers or {}).items():
        if str(key).lower() in {"content-type", "user-agent"}:
            continue
        command.extend(["-H", f"{key}: {value}"])
    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, headers: dict[str, str] | None = None) -> dict[str, Any]:
    data = None
    request_headers = {"User-Agent": f"CodeeCLI/{VERSION}", "Accept": "application/json"}
    request_headers.update({str(key): str(value) for key, value in (headers or {}).items()})
    if payload is not None:
        data = json.dumps(payload).encode("utf-8")
        request_headers["Content-Type"] = "application/json"
    req = urllib.request.Request(url, data=data, method=method.upper(), headers=request_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, headers=headers)
        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 _session_payload(root: Path) -> dict[str, Any]:
    manifest = _load_manifest(root)
    state = _load_state(root)
    session = state.get("session") if isinstance(state.get("session"), dict) else {}
    client_id = str(session.get("client_id") or state.get("client_id") or manifest.get("client_id") or root.name).strip()
    service = _normalize_service(str(session.get("service") or state.get("service") or manifest.get("service") or "codee-support"))
    email = str(session.get("email") or state.get("owner_email") or manifest.get("owner_email") or "").strip().lower()
    owner = str(session.get("owner") or manifest.get("owner") or "Business Owner").strip()
    business = str(session.get("business") or manifest.get("business") or "Codee Client").strip()
    api_base = str(session.get("api_base") or CODEE_BACKEND_API_BASE).strip().rstrip("/")
    return {
        "schema": "codee.session.v1",
        "created_at": str(session.get("created_at") or _now()),
        "updated_at": str(session.get("updated_at") or _now()),
        "cli_version": VERSION,
        "root": str(root),
        "business": business,
        "owner": owner,
        "email": email,
        "client_id": client_id,
        "workspace_id": client_id,
        "service": service,
        "api_base": api_base,
        "codee_user_id": str(session.get("codee_user_id") or manifest.get("codee_user_id") or _codee_user_id(email, f"{owner}:{business}:{client_id}")),
        "privacy": "Local session stores identity defaults only. It does not store passwords, card data, app secrets, OAuth tokens, or deploy credentials.",
    }


def _write_session(root: Path, payload: dict[str, Any]) -> Path:
    state = _load_state(root)
    existing = state.get("session") if isinstance(state.get("session"), dict) else {}
    session = {**existing, **payload, "schema": "codee.session.v1", "updated_at": _now(), "cli_version": VERSION}
    if session.get("client_id"):
        session["workspace_id"] = str(session.get("client_id"))
    session.setdefault("created_at", existing.get("created_at") or _now())
    state.update(
        {
            "business": session.get("business"),
            "owner_email": session.get("email"),
            "client_id": session.get("client_id"),
            "codee_user_id": session.get("codee_user_id"),
            "service": session.get("service"),
            "session": session,
        }
    )
    _write_state(root, state)
    path = root / ".codee" / "session.json"
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(session, 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"]
    contract = json.loads(json.dumps(base))
    if clean in CODEE_DOMAIN_SUPPORT_SERVICES:
        contract["domain_support"] = json.loads(json.dumps(CODEE_DOMAIN_SUPPORT_POLICY))
        for key, value in (
            ("required_inputs", "domain preference: Codee delivery link, own domain, not sure, or pasted domain"),
            ("client_gets", "optional client-owned domain / white-label support slot"),
            ("delivery_room_slots", "custom domain / white-label support"),
        ):
            items = contract.setdefault(key, [])
            if value not in items:
                items.append(value)
    return contract


def _all_service_contracts() -> dict[str, Any]:
    return {key: _service_contract(key) for key in CODEE_SERVICE_CONTRACTS}


def _normalize_custom_domain(value: str) -> str:
    raw = str(value or "").strip().lower()
    if not raw:
        return ""
    raw = re.sub(r"^https?://", "", raw)
    raw = raw.split("/", 1)[0].split("?", 1)[0].strip(". ")
    raw = re.sub(r"^www\.", "", raw)
    if "." not in raw or " " in raw:
        return ""
    if not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,251}\.[a-z]{2,24}", raw):
        return ""
    return raw


def _domain_support_request(args: argparse.Namespace, *, manifest: dict[str, Any] | None = None, service: str = "") -> dict[str, Any]:
    manifest = manifest or {}
    clean = _normalize_service(service or str(getattr(args, "service", "") or manifest.get("service") or "codeeqr"))
    preference = str(
        getattr(args, "domain_preference", "")
        or manifest.get("domain_connect_preference")
        or manifest.get("domain_preference")
        or ""
    ).strip()
    domain = str(
        getattr(args, "custom_domain", "")
        or manifest.get("custom_domain_name")
        or manifest.get("custom_domain")
        or ""
    ).strip()
    pasted_domain = _normalize_custom_domain(domain or preference)
    lower = preference.lower()
    white_label = bool(getattr(args, "white_label", False) or str(manifest.get("white_label_support_requested") or "").lower() in {"1", "true", "yes"})
    if pasted_domain:
        normalized_preference = "own-domain"
        white_label = True
    elif any(token in lower for token in ("own", "domain", "dns", "white", "label")):
        normalized_preference = "own-domain"
        white_label = True
    elif any(token in lower for token in ("not sure", "unsure", "later")):
        normalized_preference = "not-sure"
    elif any(token in lower for token in ("codee", "delivery", "link", "default")):
        normalized_preference = "codee-link"
    else:
        normalized_preference = "not-asked"
    return {
        "schema": "codee.domain-support-request.v1",
        "eligible": clean in CODEE_DOMAIN_SUPPORT_SERVICES,
        "service": clean,
        "question": CODEE_DOMAIN_SUPPORT_POLICY["question"],
        "preference": normalized_preference,
        "raw_answer": preference,
        "custom_domain_name": pasted_domain,
        "white_label_support_requested": bool(white_label),
        "control_room_rule": CODEE_DOMAIN_SUPPORT_POLICY["guardrail"],
        "client_owned_rule": CODEE_DOMAIN_SUPPORT_POLICY["client_owned_rule"],
        "monthly_support_value": CODEE_DOMAIN_SUPPORT_POLICY["support_value"],
    }


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),
        "codex_parity": _codex_parity_payload(root, apply_codee_update=False),
        "next_commands": [
            f"python3 codee.py codex-sync {root} --write --force",
            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 private model key is bundled in the CLI; local rules and bring-your-own model commands are available through `model-bridge` and `agent-run`.",
            "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)
    codex_parity = payload["codex_parity"] if isinstance(payload.get("codex_parity"), dict) else _codex_parity_payload(root, apply_codee_update=False)
    user_memory = _ensure_user_memory_vault(root, business=business, service=service, force=force)
    accessibility = _accessibility_manifest(root, business=business, service=service)
    sync_script_path = root / ".codee" / "update-hooks" / "codex-sync.sh"
    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),
        "codex_parity": _write_json(root / ".codee" / "codex-parity.json", codex_parity, force=force),
        "codex_parity_markdown": _write_text(root / ".codee" / "CODEX_PARITY.md", _codex_parity_markdown(codex_parity), force=force),
        "codex_sync_hook": _write_text(sync_script_path, _codex_sync_shell(root, apply_codee_update=True), 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),
    }
    try:
        sync_script_path.chmod(0o755)
    except Exception:
        pass
    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, "codex_parity": codex_parity, "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="MiniCodeeSite product guide preview">
        <div class="book-cover">
          <span>MiniCodeeSite</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 _local_codex_status(*, timeout: float = 8) -> dict[str, Any]:
    path = shutil.which("codex")
    if not path:
        return {"ok": False, "path": "", "version": "", "raw": "", "stderr": "", "error": "codex_not_found"}
    try:
        proc = subprocess.run([path, "--version"], text=True, capture_output=True, timeout=float(timeout), check=False)
    except Exception as exc:
        return {"ok": False, "path": path, "version": "", "raw": "", "stderr": "", "error": f"{type(exc).__name__}: {str(exc)[:180]}"}
    raw = (proc.stdout or "").strip()
    stderr = (proc.stderr or "").strip()
    combined = f"{raw}\n{stderr}".strip()
    match = re.search(r"(\d+\.\d+\.\d+(?:[-+][A-Za-z0-9._-]+)?)", combined)
    return {
        "ok": proc.returncode == 0 and bool(match),
        "path": path,
        "version": match.group(1) if match else "",
        "raw": raw,
        "stderr": stderr,
        "exit_code": proc.returncode,
        "error": "" if proc.returncode == 0 else stderr[:180],
    }


def _codex_sync_shell(root: Path, *, apply_codee_update: bool = False) -> str:
    root_q = shlex.quote(str(root))
    update_flag = " --apply-codee-update" if apply_codee_update else ""
    return "\n".join(
        [
            "#!/usr/bin/env bash",
            "set -euo pipefail",
            f"cd {root_q}",
            'if [ -f "./codee.py" ]; then',
            f"  python3 ./codee.py codex-sync . --write --force{update_flag}",
            'elif [ -f "tools/codee_cli.py" ]; then',
            f"  python3 tools/codee_cli.py codex-sync . --write --force{update_flag}",
            "else",
            '  echo "Codee CLI not found in this folder. Download from https://clients.codee.chat/assets/downloads/codee-cli.py" >&2',
            "  exit 2",
            "fi",
            "",
        ]
    )


def _codex_parity_payload(root: Path, *, apply_codee_update: bool = False, timeout: float = 8) -> dict[str, Any]:
    previous = _read_json_if_exists(root / ".codee" / "codex-parity.json")
    previous_codex = previous.get("codex") if isinstance(previous.get("codex"), dict) else {}
    codex = _local_codex_status(timeout=timeout)
    previous_version = str(previous_codex.get("version") or "")
    current_version = str(codex.get("version") or "")
    changed = bool(current_version and previous_version and current_version != previous_version)
    first_sync = bool(current_version and not previous_version)
    codee_update: dict[str, Any] = {"attempted": False, "ok": False, "reason": "not_requested"}
    if apply_codee_update and (changed or first_sync or not previous_version):
        result = _curl_fetch("GET", CODEE_DOWNLOAD_URL, timeout=max(15, float(timeout)))
        body = str(result.get("body") or "")
        ok_body = bool(result.get("ok") and "VERSION" in body[:5000])
        target = Path(__file__).resolve()
        checkpoint = ""
        wrote = False
        if ok_body:
            checkpoint = _checkpoint_existing_path(target, reason="codex-sync-codee-update")
            target.write_text(body, encoding="utf-8")
            wrote = True
        codee_update = {
            "attempted": True,
            "ok": ok_body,
            "http_status": result.get("status"),
            "target": str(target),
            "checkpoint": checkpoint,
            "wrote": wrote,
            "reason": "codex_version_changed_or_first_sync",
            "error": "" if ok_body else str(result.get("error") or "download_failed")[:180],
        }
    status = "synced"
    if not codex.get("ok"):
        status = "codex-missing"
    elif changed:
        status = "codex-changed"
    elif first_sync:
        status = "first-sync"
    return {
        "ok": bool(codex.get("ok")),
        "schema": "codee.codex-parity.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "root": str(root),
        "status": status,
        "codex": codex,
        "previous_codex_version": previous_version,
        "codex_version_changed": changed,
        "first_sync": first_sync,
        "codee_update": codee_update,
        "parity_requirements": CODEE_CODEX_PARITY_REQUIREMENTS,
        "bridge_manifest_url": CODEE_CODEX_BRIDGE_MANIFEST_URL,
        "parity_manifest_url": CODEE_CODEX_PARITY_MANIFEST_URL,
        "direct_connection_truth": "Codee cannot receive OpenAI Codex release events directly. Codee can watch the locally installed `codex --version`, write a sync report, and optionally refresh Codee CLI from its own public release URL when Codex changes.",
        "recommended_update_flow": [
            "Update Codex normally with the OpenAI/Codex installer path.",
            "Run `codee codex-sync . --write --force --apply-codee-update` in each Codee workspace.",
            "Run `codee doctor . --local-only` and `codee codex-bridge . --write --force --json` after the sync.",
            "Deploy the refreshed public Codee CLI copy only after compile and smoke proof pass.",
        ],
        "files": {
            "parity_json": str(root / ".codee" / "codex-parity.json"),
            "parity_markdown": str(root / ".codee" / "CODEX_PARITY.md"),
            "sync_script": str(root / ".codee" / "update-hooks" / "codex-sync.sh"),
        },
        "next_commands": [
            "codee codex-sync . --write --force --apply-codee-update",
            "codee doctor . --local-only",
            "codee codex-bridge . --write --force --json",
            "codee platform . --write --force",
        ],
    }


def _codex_parity_markdown(payload: dict[str, Any]) -> str:
    codex = payload.get("codex") if isinstance(payload.get("codex"), dict) else {}
    lines = [
        "# Codee Codex Parity",
        "",
        f"Status: {payload.get('status')}",
        f"Codee CLI: {payload.get('cli_version')}",
        f"Codex CLI: {codex.get('version') or 'not found'}",
        f"Codex path: {codex.get('path') or 'not found'}",
        f"Previous Codex CLI: {payload.get('previous_codex_version') or 'none'}",
        f"Changed: {payload.get('codex_version_changed')}",
        "",
        "## Connection Truth",
        "",
        str(payload.get("direct_connection_truth") or ""),
        "",
        "## Parity Requirements",
        "",
    ]
    for item in payload.get("parity_requirements") or []:
        lines.append(f"- {item.get('label')}: {item.get('status')} - `{item.get('codee_command')}`")
    lines.extend(["", "## Recommended Update Flow", ""])
    for item in payload.get("recommended_update_flow") or []:
        lines.append(f"- {item}")
    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 _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)
    domain_support = _domain_support_request(args, manifest=manifest | activation_packet | course_packet, 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,
        "domain_support": domain_support,
        "domain_connect_preference": domain_support["preference"],
        "custom_domain_name": domain_support["custom_domain_name"],
        "white_label_support_requested": "yes" if domain_support["white_label_support_requested"] else "no",
        "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, domain_support: dict[str, Any] | None = None) -> dict[str, Any]:
    clean = _normalize_service(service or "codeeqr")
    contract = _service_contract(clean)
    domain_support = domain_support or _domain_support_request(argparse.Namespace(service=clean), service=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 "",
        "domain_support": domain_support,
        "domain_connect_preference": domain_support.get("preference") or "",
        "custom_domain_name": domain_support.get("custom_domain_name") or "",
        "custom_domain_requested": bool(domain_support.get("custom_domain_name") or domain_support.get("preference") == "own-domain"),
        "white_label_support_requested": "yes" if domain_support.get("white_label_support_requested") else "no",
        "domain_support_policy": "delivery_room_support_slot_dns_help_white_label_optional_client_owned_domain",
        "delivery_room_domain_slot": "included_as_optional_support_request_after_delivery",
    }
    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 == "free-audit":
        payload.update(
            {
                "product_type": "custom",
                "service_tier": "free_audit_delivery_room",
                "tier_requested": "0",
                "audit_target_url": target_url or "",
                "audit_goal": goal or "Find the fastest proof-backed first paid lane.",
                "audit_paywall_mode": "free_report_then_paid_fix_lane",
            }
        )
    elif clean == "audit-site":
        payload.update(
            {
                "product_type": "custom",
                "service_tier": "audit_site_delivery_room_149",
                "tier_requested": "149",
                "audit_target_url": target_url or "",
                "audit_goal": goal or "Turn the free audit into a hosted report and fix queue.",
                "audit_paywall_mode": "free_preview_then_paid_hosted_report",
            }
        )
    elif clean == "codee-affiliate":
        payload.update(
            {
                "product_type": "custom",
                "service_tier": "codee_affiliate_weekly_review",
                "tier_requested": "0",
                "affiliate_registration_url": f"{DEFAULT_API_BASE}/codee-affiliate.html",
                "affiliate_program_api": f"{DEFAULT_API_BASE}/api/dashboard/affiliate/program",
                "affiliate_link_modes": ["single_service_link", "all_service_bundle", "no_website_social_qr"],
                "affiliate_commission_percent": "10",
                "affiliate_payout_rule": "Stripe-paid sales with the ref code enter weekly verified payout review after refund-risk and owner approval.",
            }
        )
    elif clean in {"codeeflyer", "codeeflyer100", "codeeflyer-100", "codeeflyer250", "codeeflyer-250", "codeeflyer300", "codeeflyer-300"}:
        payload.update(
            {
                "product_type": "digiflyer",
                "service_tier": "300",
                "tier_requested": "300",
                "digiflyer_target_link": target_url,
                "digiflyer_design_brief": goal,
                "digiflyer_multi_actions_required": True,
                "digiflyer_qr_target_policy": "qr_points_to_hosted_flyer_page_actions_live_in_action_window",
                "digiflyer_multi_action_hint": "Collect one to three actions such as Call, Text, Book, or Buy. The verified QRCodee points to the hosted flyer page.",
                "digiflyer_generated_image_mode": "prompt_reference_or_both",
            }
        )
    elif clean == "codeeblog":
        payload.update(
            {
                "product_type": "digiblog",
                "service_tier": "codeeblog_public_100",
                "tier_requested": "100",
                "digiblog_home_title": business or "CodeeBlog",
                "digiblog_goal": goal or "Create a resource hub with guide links, offers, and capture path.",
                "digiblog_primary_link": target_url or "",
            }
        )
    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",
                "codeecard_support_model": "codee_support_route_owner_review_when_positioning_needed",
                "codeecard_required_context": ["main audience", "main offer", "credibility proof", "primary action", "tile stack"],
            }
        )
    elif clean in {"codeebeeper", "codeevault"}:
        payload.update({"product_type": "codeevault", "tier_requested": "149"})
    elif clean == "minicodeesite-template":
        payload.update({"product_type": "minicodeesite", "tier_requested": "497", "service_tier": "minicodeesite_template_497"})
    elif clean == "minicodeesite-launch":
        payload.update({"product_type": "minicodeesite", "tier_requested": "1500", "service_tier": "minicodeesite_launch_1500"})
    elif clean == "minicodeesite":
        payload.update(
            {
                "product_type": "minicodeesite",
                "tier_requested": "497",
                "service_tier": "minicodeesite_template_497",
                "minicodeesite_tier_choices": ["497"],
            }
        )
    elif clean in {"business-suite", "codee-business-suite"}:
        payload.update(
            {
                "product_type": "minicodeesite",
                "tier_requested": "2500",
                "service_tier": "codee_business_suite_supported_2500",
                "suite_slot_limit": "10",
                "suite_support_model": "backend_support_private_consultation_30_day_request_lane",
                "suite_long_intake_required": True,
                "suite_required_context": [
                    "decision maker",
                    "business model",
                    "primary offer",
                    "current website/domain",
                    "payment path",
                    "booking/contact path",
                    "storage/file needs",
                    "backend or automation needs",
                    "top 3 launch goals",
                    "private consultation preference",
                    "30-day support priority",
                ],
            }
        )
    elif clean == "codeeauthority":
        payload.update(
            {
                "product_type": "codeeauthority",
                "service_tier": "owner_review_required",
                "tier_requested": "250",
                "authority_topic": goal or business or "CodeeAuthority",
                "authority_target_url": target_url or "",
                "public_promotion_status": "paused_owner_review",
            }
        )
    elif clean == "sean-review-room":
        payload.update(
            {
                "product_type": "custom",
                "service_tier": "sean_review_room_200",
                "tier_requested": "200",
                "audit_target_url": target_url or "",
                "review_goal": goal or "Review the audit context and define the right next paid lane.",
                "public_promotion_status": "audit_only_private_review",
            }
        )
    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.")
    domain_support = packet.get("domain_support") if isinstance(packet.get("domain_support"), dict) else {}
    if domain_support:
        lines.extend([
            "",
            "## Domain / White-Label Support",
            "",
            f"- Preference: {domain_support.get('preference')}",
            f"- Custom domain: {domain_support.get('custom_domain_name') or 'not provided'}",
            f"- White-label support requested: {'yes' if domain_support.get('white_label_support_requested') else 'no'}",
            f"- Rule: {domain_support.get('client_owned_rule')}",
            f"- Monthly support value: {domain_support.get('monthly_support_value')}",
        ])
    paywall = packet.get("paywall") if isinstance(packet.get("paywall"), dict) else {}
    lines.extend(["", "## Paywall Rule", ""])
    if paywall:
        lines.append(f"- Status: {paywall.get('status')}")
        lines.append(f"- Rule: {paywall.get('unlock_rule')}")
        if paywall.get("preview_window_minutes"):
            lines.append(f"- Preview window: {paywall.get('preview_window_minutes')} minutes.")
    else:
        lines.append("- Codee may create a locked preview first.")
        lines.append("- True deploy, hosted route, delivery room unlock, managed scan, and support handoff wait for Stripe/payment verification.")
        lines.append("- The client can review the preview, then pay to keep the final route live.")
    lines.extend([
        f"- Live proof promo code: {packet.get('promo_code') or CODEE_LIVE_PROOF_PROMO_CODE}.",
        f"- Renewal/support reminder: day {packet.get('renewal_reminder_day') or CODEE_RENEWAL_REMINDER_DAY} of {packet.get('support_window_days') or CODEE_SUPPORT_WINDOW_DAYS}.",
        "",
        "## 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 _audit_flow_markdown(packet: dict[str, Any]) -> str:
    lines = [
        "# Codee Free Audit Flow",
        "",
        f"Business: {packet.get('business')}",
        f"Client email: {packet.get('account_email') or 'not provided'}",
        f"Target URL: {packet.get('target_url') or 'not provided'}",
        f"Delivery room: {packet.get('delivery_room_url')}",
        "",
        "## Scorecard",
        "",
    ]
    for item in packet.get("scorecard") or []:
        if isinstance(item, dict):
            lines.append(f"- {item.get('label')}: {item.get('status')} - {item.get('note')}")
    lines.extend(["", "## Free Audit Unlocks", ""])
    for item in packet.get("free_deliverables") or []:
        lines.append(f"- {item}")
    lines.extend(["", "## Paywall Preview", ""])
    paywall = packet.get("paywall_preview") if isinstance(packet.get("paywall_preview"), dict) else {}
    for item in paywall.get("unlocked_now") or []:
        lines.append(f"- Free now: {item}")
    for item in paywall.get("locked_until_paid") or []:
        lines.append(f"- Paid unlock: {item}")
    lines.extend(["", "## Recommended Ladder", ""])
    for step in packet.get("recommended_ladder") or []:
        if isinstance(step, dict):
            lines.append(f"- {step.get('label')} ({step.get('price_lane')}): {step.get('client_value')}")
    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 _audit_scorecard(target_url: str, goal: str) -> list[dict[str, str]]:
    has_url = bool(str(target_url or "").strip())
    has_goal = bool(str(goal or "").strip())
    return [
        {
            "id": "site-route",
            "label": "Website route",
            "status": "ready-to-review" if has_url else "missing",
            "note": "Target URL is present for route proof." if has_url else "Ask for the current site, Google profile, booking link, or social link.",
        },
        {
            "id": "mobile-cta",
            "label": "Mobile CTA",
            "status": "needs-proof",
            "note": "Audit should confirm one visible call-to-action above the fold on a phone.",
        },
        {
            "id": "trust-proof",
            "label": "Trust proof",
            "status": "needs-proof",
            "note": "Look for reviews, address, phone, service area, credentials, photos, or before/after proof.",
        },
        {
            "id": "offer-clarity",
            "label": "Offer clarity",
            "status": "ready-to-review" if has_goal else "needs-owner-input",
            "note": "Goal is clear enough to recommend a first paid lane." if has_goal else "Ask what the client wants visitors to do first.",
        },
        {
            "id": "first-paid-lane",
            "label": "First paid lane",
            "status": "qr-first",
            "note": "QRCodee is the fastest conversion when the client only needs a scanable route and proof.",
        },
    ]


def _audit_delivery_payload(
    *,
    root: Path,
    manifest: dict[str, Any],
    service: str,
    recommended_service: str,
    business: str,
    owner: str,
    email: str,
    target_url: str,
    goal: str,
) -> dict[str, Any]:
    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 "").strip() or _codee_user_id(email, workspace_id)
    mini_manifest = {"client_id": workspace_id, "codee_user_id": codee_user_id, "business": business}
    report_query = urllib.parse.urlencode(
        {
            "client_id": workspace_id,
            "workspace_id": workspace_id,
            "codee_user_id": codee_user_id,
            "service": service,
            "source": "codee-cli-audit",
        }
    )
    paid_query = urllib.parse.urlencode(
        {
            "service": recommended_service,
            "business": business or "Codee Client",
            "target_url": target_url or "",
            "source": "codee-cli-audit",
        }
    )
    return {
        "schema": "codee.cli.audit-flow.v1",
        "ok": True,
        "created_at": _now(),
        "cli_version": VERSION,
        "root": str(root),
        "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,
        "audit_contract": _service_contract(service),
        "recommended_service": recommended_service,
        "recommended_contract": _service_contract(recommended_service),
        "delivery_room_url": _delivery_room_url(mini_manifest, service=service),
        "audit_report_url": f"{DEFAULT_API_BASE}/free-audit/?{report_query}",
        "paid_preview_url": f"{DEFAULT_API_BASE}/codee-chat.html?{paid_query}",
        "scorecard": _audit_scorecard(target_url, goal),
        "free_deliverables": [
            "Audit scorecard",
            "Plain-language issue checklist",
            "Delivery room link",
            "Recommended first paid lane",
            "Support request path",
        ],
        "paywall_preview": {
            "status": "free_audit_open_paid_fixes_locked",
            "unlocked_now": ["audit scorecard", "delivery room", "recommended first paid lane"],
            "locked_until_paid": [
                "hosted QR/image site",
                "hosted audit report site",
                "managed route scan",
                "first support edit or fix queue",
                "full business-suite build",
            ],
            "rule": "Start with free proof; ask for payment only when the client chooses the smallest useful paid lane.",
        },
        "recommended_ladder": [dict(step) for step in CODEE_AUDIT_LADDER_MODEL["steps"]],
        "next_commands": [
            f"codee client {shlex.quote(str(root))} --service {service} --business {shlex.quote(business or 'Codee Client')} --email {email or 'owner@example.com'} --target-url {shlex.quote(target_url or 'https://example.com')} --dry-run",
            f"codee preview {shlex.quote(str(root))} --service {recommended_service} --business {shlex.quote(business or 'Codee Client')} --email {email or 'owner@example.com'} --target-url {shlex.quote(target_url or 'https://example.com')} --dry-run",
            f"codee activate {shlex.quote(str(root))} --service {recommended_service} --business {shlex.quote(business or 'Codee Client')} --email {email or 'owner@example.com'} --target-url {shlex.quote(target_url or 'https://example.com')} --dry-run",
            f"codee room {shlex.quote(str(root))} --service {service}",
        ],
    }


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
- MiniCodeeSite Product Guide 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 client tool pricing")
    print("CODEECLI itself is a free download. Paying buys client builds or managed hosting, not the command.")
    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("The $19 hosting plan keeps purchased tools live; it does not unlock unpurchased lanes or include new builds.")
    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), "MiniCodeeSite/shop lane should include a PDF/guidebook or cover image before fulfillment.", severity="warn")
    if service in {"codeeflyer", "codeeflyer250", "codeeflyer300"}:
        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 MiniCodeeSite 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": "MiniCodeeSite", "purpose": "Hosted page for a guide, product, ebook, shop lane, 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.
- MiniCodeeSite: Hosted page for a guide, product, ebook, shop lane, 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 = _codee_local_pricing_payload(include_review=bool(getattr(args, "include_review", False)))
    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 = _codee_local_pricing_payload(include_review=bool(getattr(args, "include_review", False))) | {"remote_error": payload}
        except Exception as exc:
            payload = _codee_local_pricing_payload(include_review=bool(getattr(args, "include_review", False))) | {"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 command_services(args: argparse.Namespace) -> int:
    payload = json.loads(json.dumps(CODEE_CHAT_SERVICE_SCRIPT_MODEL))
    if not args.include_review:
        payload["owner_review_services"] = []
    if args.public_only:
        payload["services"] = [
            item
            for item in payload.get("services") or []
            if str(item.get("status") or "").lower() == "public"
            and str(item.get("id") or "") in REV001_PUBLIC_SERVICE_IDS
        ]
        payload["owner_review_services"] = []
    if args.json:
        print(json.dumps(payload, indent=2))
    else:
        print("Codee.chat service menu")
        print("")
        for item in payload.get("services") or []:
            label = str(item.get("label") or item.get("id") or "")
            price = str(item.get("checkout") or item.get("price_lane") or "")
            status = str(item.get("status") or "")
            command = f"codee preview . --service {item.get('id')} --dry-run"
            if item.get("id") == "free-audit":
                command = "codee audit . --write"
            print(f"{item.get('id')}: {label} - {price} [{status}]")
            print(f"  {str(item.get('note') or '').strip()}")
            print(f"  {command}")
        for item in payload.get("owner_review_services") or []:
            print(f"{item.get('id')}: {item.get('label')} - {item.get('checkout')} [{item.get('status')}]")
            print(f"  {item.get('note')}")
            print(f"  codee preview . --service {item.get('id')} --dry-run")
        print("")
        print(f"Manifest: {payload.get('manifest_url')}")
    return 0


def command_maintain(args: argparse.Namespace) -> int:
    worker = Path(__file__).resolve().parent / "codee_maintenance_worker.py"
    cmd = [
        sys.executable,
        str(worker),
        args.path,
        "--profile",
        args.profile,
        "--timeout",
        str(args.timeout),
    ]
    if args.skip_intake_smoke:
        cmd.append("--skip-intake-smoke")
    if args.skip_workspace_smoke:
        cmd.append("--skip-workspace-smoke")
    if args.live:
        cmd.append("--live")
    if args.strict:
        cmd.append("--strict")
    if args.write_report:
        cmd.append("--write-report")
    if args.json:
        cmd.append("--json")
    proc = subprocess.run(cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
    if proc.stdout:
        print(proc.stdout, end="")
    if proc.stderr:
        print(proc.stderr, end="", file=sys.stderr)
    return int(proc.returncode)


SERVICE_SEED_PRICING = {
    "free": {
        "label": "$0 local preview",
        "private_hosted_preview": False,
        "public_launch": False,
        "summary": "Create local service-seed JSON, markdown, and preview HTML. No hosted public route.",
    },
    "chief": {
        "label": "$29/mo Codee Chief",
        "private_hosted_preview": True,
        "public_launch": False,
        "summary": "One serious workspace with private previews and upgrade checks.",
    },
    "partner": {
        "label": "$99/mo Codee Partner",
        "private_hosted_preview": True,
        "public_launch": False,
        "summary": "Multiple client workspaces with more private previews and partner support packets.",
    },
    "service_creator": {
        "label": "$249/mo Codee Service Creator",
        "private_hosted_preview": True,
        "public_launch": True,
        "summary": "Approved service pages, public launch requests, and checkout/invoice preparation after owner review.",
    },
    "business_suite": {
        "label": "$2,500 Codee Business Suite",
        "private_hosted_preview": True,
        "public_launch": True,
        "summary": "Launch bundle with one approved service activation inside the paid workspace.",
    },
}


def _service_seed_plan_key(value: str) -> str:
    key = _slugify(value or "free").replace("-", "_")
    aliases = {
        "pro": "chief",
        "codee_pro": "chief",
        "workspace_standard": "partner",
        "workspace_pro": "service_creator",
        "creator": "service_creator",
        "service_creator": "service_creator",
        "business_suite": "business_suite",
        "suite": "business_suite",
        "biz": "business_suite",
    }
    return aliases.get(key, key if key in SERVICE_SEED_PRICING else "free")


def _service_seed_blueprint(*, title: str, idea: str, business: str, client_id: str, source: str) -> dict[str, Any]:
    lower = idea.lower()
    if any(term in lower for term in ("indeed", "job post", "hiring", "candidate", "salary", "1099")):
        lane = "lead-to-service"
        outcome = "Turn hiring demand into a scoped service offer the business can understand."
    elif any(term in lower for term in ("qr", "flyer", "campaign", "consultation", "booking", "lead")):
        lane = "campaign-to-service"
        outcome = "Turn the idea into a QR, landing, intake, and proof route."
    elif any(term in lower for term in ("app", "portal", "dashboard", "workspace", "software")):
        lane = "workspace-to-service"
        outcome = "Turn the idea into a private workspace preview with activation gates."
    else:
        lane = "idea-to-service"
        outcome = "Turn the rough idea into a private service preview before public launch."
    service_name = title or f"{business} Service Seed"
    return {
        "lane": lane,
        "service_name": service_name,
        "service_slug": _slugify(service_name),
        "business": business,
        "client_id": client_id,
        "source": source,
        "primary_outcome": outcome,
        "audience": "The client, buyer, or business segment described in the idea.",
        "offer": f"{service_name}: a Codee-reviewed service preview that needs approval before going public.",
        "cta": "Request this service",
        "payment_path": "No public checkout or invoice is created until the workspace tier and owner approval are active.",
        "delivery_path": "Local preview -> private hosted preview -> approval -> public page -> delivery/proof room.",
        "proof_checklist": [
            "Local service seed files were created inside the workspace.",
            "Private preview exists before any public launch request.",
            "Powered by Codee points to https://codee.chat/.",
            "Public launch requires Service Creator or Business Suite approval.",
            "Checkout or invoice routes are owner-reviewed before use.",
            "No income, lead volume, approval, or outcome guarantee is promised.",
        ],
    }


def _service_seed_markdown(payload: dict[str, Any]) -> str:
    blueprint = payload.get("blueprint") if isinstance(payload.get("blueprint"), dict) else {}
    gate = payload.get("activation_gate") if isinstance(payload.get("activation_gate"), dict) else {}
    lines = [
        "# Codee Service Seed",
        "",
        f"Title: {payload.get('title', '')}",
        f"Business: {payload.get('business', '')}",
        f"Workspace: {payload.get('client_id', '')}",
        f"Plan: {payload.get('plan_label', '')}",
        f"Status: {payload.get('status', '')}",
        "",
        "## Blueprint",
        "",
        f"- Lane: {blueprint.get('lane', '')}",
        f"- Outcome: {blueprint.get('primary_outcome', '')}",
        f"- Offer: {blueprint.get('offer', '')}",
        f"- CTA: {blueprint.get('cta', '')}",
        f"- Payment path: {blueprint.get('payment_path', '')}",
        f"- Delivery path: {blueprint.get('delivery_path', '')}",
        "",
        "## Activation Gate",
        "",
        f"- Local preview: {gate.get('local_preview')}",
        f"- Private hosted preview: {gate.get('private_hosted_preview')}",
        f"- Public launch: {gate.get('public_launch')}",
        f"- Required for public launch: {gate.get('required_for_public_launch') or 'Owner review'}",
        "",
        "## Powered By",
        "",
        "[Powered by Codee](https://codee.chat/)",
        "",
        "## Proof Checklist",
        "",
    ]
    for item in blueprint.get("proof_checklist") or []:
        lines.append(f"- {item}")
    lines.extend(["", "## Idea", "", str(payload.get("idea") or "").strip()])
    return "\n".join(lines) + "\n"


def _service_seed_html(payload: dict[str, Any]) -> str:
    blueprint = payload.get("blueprint") if isinstance(payload.get("blueprint"), dict) else {}
    gate = payload.get("activation_gate") if isinstance(payload.get("activation_gate"), dict) else {}
    required = str(gate.get("required_for_public_launch") or "Owner review before launch")
    proof_items = "".join(f"<li>{html.escape(str(item))}</li>" for item in blueprint.get("proof_checklist") or [])
    return f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>{html.escape(str(payload.get('title') or 'Codee Service Seed'))}</title>
  <style>
    body{{margin:0;font-family:Inter,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:#08111f;color:#e5edf7}}
    main{{max-width:960px;margin:0 auto;padding:34px 18px 54px}}
    section{{border:1px solid rgba(148,163,184,.22);border-radius:18px;background:rgba(15,23,42,.82);padding:22px;margin:0 0 16px}}
    h1{{margin:0 0 10px;font-size:clamp(2rem,5vw,3.3rem);line-height:1.02}} h2{{margin:0 0 10px}} p,li{{line-height:1.7;color:#c7d4e6}}
    .pill{{display:inline-flex;margin:0 8px 8px 0;padding:7px 10px;border-radius:999px;background:#123b63;color:#dbeafe;font-weight:800;font-size:12px;text-transform:uppercase;letter-spacing:.08em}}
    a{{color:#93c5fd;font-weight:900}}
  </style>
</head>
<body>
  <main>
    <section>
      <span class="pill">Private Preview</span><span class="pill">{html.escape(str(payload.get('plan_label') or 'Local'))}</span>
      <h1>{html.escape(str(payload.get('title') or 'Codee Service Seed'))}</h1>
      <p>{html.escape(str(blueprint.get('primary_outcome') or 'Private service preview ready for review.'))}</p>
      <p><a href="https://codee.chat/" target="_blank" rel="noopener">Powered by Codee</a></p>
    </section>
    <section><h2>Offer</h2><p>{html.escape(str(blueprint.get('offer') or ''))}</p><p><strong>CTA:</strong> {html.escape(str(blueprint.get('cta') or 'Request this service'))}</p></section>
    <section><h2>Activation Gate</h2><p>Public launch requires: {html.escape(required)}.</p><p>{html.escape(str(blueprint.get('payment_path') or ''))}</p></section>
    <section><h2>Proof Checklist</h2><ul>{proof_items}</ul></section>
  </main>
</body>
</html>
"""


def command_service_seed(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 root.name or "Codee Client").strip()
    client_id = _slugify(str(args.client_id or manifest.get("client_id") or business or root.name))
    title = str(args.title or "").strip() or f"{business} Service Seed"
    idea = str(args.idea or "").strip()
    if args.idea_file:
        idea_path = Path(args.idea_file).expanduser()
        if not idea_path.is_absolute():
            idea_path = root / idea_path
        if idea_path.exists():
            idea = f"{idea}\n\n{idea_path.read_text(encoding='utf-8', errors='replace')}".strip()
    if not idea:
        print("service-seed requires --idea \"...\" or --idea-file path")
        return 2
    plan_key = _service_seed_plan_key(str(args.plan or "free"))
    plan = SERVICE_SEED_PRICING[plan_key]
    seed_id = f"seed-{hashlib.sha256(f'{client_id}:{title}:{idea[:400]}'.encode('utf-8')).hexdigest()[:12]}"
    blueprint = _service_seed_blueprint(title=title, idea=idea, business=business, client_id=client_id, source="codee-cli")
    activation_gate = {
        "local_preview": True,
        "private_hosted_preview": bool(plan["private_hosted_preview"]),
        "public_launch": bool(plan["public_launch"]),
        "checkout_or_invoice": bool(plan["public_launch"]),
        "required_for_public_launch": "" if plan["public_launch"] else "Codee Service Creator or Codee Business Suite",
    }
    payload = {
        "ok": True,
        "schema": "codee.service-seed.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "seed_id": seed_id,
        "title": title,
        "business": business,
        "client_id": client_id,
        "workspace": str(root),
        "plan": plan_key,
        "plan_label": plan["label"],
        "status": "private_preview_ready",
        "idea": idea,
        "blueprint": blueprint,
        "activation_gate": activation_gate,
        "pricing_rule": "Codee can create local/private previews first. Public service pages, checkout, invoice, and hosting require the correct paid workspace tier and owner review.",
        "powered_by": {"label": "Powered by Codee", "url": "https://codee.chat/"},
        "next_commands": [
            f"codee service-seed {shlex.quote(str(root))} --title {shlex.quote(title)} --idea {shlex.quote(idea[:120])} --write --force",
            "codee pricing",
            f"codee upgrade {shlex.quote(str(root))} --plan service_creator --email owner@example.com --open",
            f"codee support {shlex.quote(str(root))} --service idea-to-service --message \"Review and activate service seed {seed_id}\"",
        ],
    }
    backend_result: dict[str, Any] = {"ok": False, "skipped": True}
    if args.submit:
        backend_result = _request_json(
            "POST",
            _api_url(args.api_base, f"/api/codee/workspace/{urllib.parse.quote(client_id, safe='')}/service-seed"),
            {"title": title, "idea": idea, "seed_id": seed_id, "plan": plan_key, "source": "codee-cli"},
            timeout=float(args.timeout),
        )
    report_path = ""
    preview_path = ""
    if args.write:
        seed_dir = root / ".codee" / "service-seeds"
        _write_json(seed_dir / f"{seed_id}.json", payload | {"backend": backend_result}, force=args.force)
        _write_text(seed_dir / f"{seed_id}.md", _service_seed_markdown(payload), force=args.force)
        _write_text(root / "service-preview.html", _service_seed_html(payload), force=args.force)
        _write_text(root / ".codee" / "SERVICE_SEED.md", _service_seed_markdown(payload), force=True)
        report_path = str(_write_report(root, "latest-service-seed.json", payload | {"backend": backend_result}))
        preview_path = str(root / "service-preview.html")
        _append_event(root, "ServiceSeedCreated", {"seed_id": seed_id, "client_id": client_id, "plan": plan_key, "submitted": bool(args.submit)})
    if args.json:
        print(json.dumps(payload | {"backend": backend_result, "report": report_path, "preview": preview_path}, indent=2))
    else:
        print(f"Codee Service Seed: ok=True id={seed_id}")
        print(f"business={business}")
        print(f"plan={plan['label']}")
        print(f"private_hosted_preview={activation_gate['private_hosted_preview']} public_launch={activation_gate['public_launch']}")
        print(f"powered_by=https://codee.chat/")
        if report_path:
            print(f"report={report_path}")
            print(f"preview={preview_path}")
        if args.submit:
            print(f"backend_ok={backend_result.get('ok')} status={backend_result.get('scan_status') or backend_result.get('error') or 'submitted'}")
    if args.open and preview_path:
        webbrowser.open(Path(preview_path).as_uri())
    return 0 if payload["ok"] and (not args.submit or backend_result.get("ok")) else 1


def _owner_generate_service_record(service: str) -> dict[str, Any]:
    normalized = _normalize_service(service)
    for item in CODEE_CHAT_SERVICE_SCRIPT:
        if _normalize_service(str(item.get("id") or "")) == normalized:
            return dict(item)
    contract = _service_contract(normalized)
    return {
        "id": normalized,
        "chat_service": normalized,
        "label": str(contract.get("name") or normalized),
        "status": "owner-internal",
        "checkout": "Owner/admin no-paywall local generation",
        "price_lane": "owner",
        "intake": ", ".join(str(v) for v in contract.get("required_inputs") or []) or "Owner-provided service brief",
        "delivery": ", ".join(str(v) for v in contract.get("client_gets") or []) or "Owner-generated preview and proof packet",
        "client_bucket": "local owner workspace",
        "advertise": "Internal only",
        "note": "Generated from service contract fallback.",
    }


def _owner_generate_html(payload: dict[str, Any]) -> str:
    service = payload.get("service_record") if isinstance(payload.get("service_record"), dict) else {}
    contract = payload.get("service_contract") if isinstance(payload.get("service_contract"), dict) else {}
    client_gets = service.get("delivery") or ", ".join(str(v) for v in contract.get("client_gets") or [])
    required_inputs = service.get("intake") or ", ".join(str(v) for v in contract.get("required_inputs") or [])
    return f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>{html.escape(str(payload.get('business') or 'Codee Owner Service'))}</title>
  <style>
    body{{margin:0;font-family:Inter,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:#f7f8fb;color:#172033}}
    main{{max-width:980px;margin:0 auto;padding:34px 18px 56px}}
    section{{border:1px solid #d9e1ee;border-radius:8px;background:#fff;padding:22px;margin:0 0 14px}}
    h1{{margin:0 0 8px;font-size:42px;line-height:1.05}} h2{{margin:0 0 10px;font-size:20px}} p,li{{line-height:1.65}}
    .tag{{display:inline-flex;margin:0 8px 10px 0;padding:6px 9px;border-radius:6px;background:#13243a;color:#fff;font-size:12px;font-weight:800;text-transform:uppercase}}
    .actions a{{display:inline-block;margin:0 8px 8px 0;padding:10px 12px;border-radius:6px;background:#0f766e;color:#fff;text-decoration:none;font-weight:900}}
    code{{background:#eef2f7;padding:2px 5px;border-radius:4px}}
  </style>
</head>
<body>
  <main>
    <section>
      <span class="tag">Owner Generated</span><span class="tag">No Paywall</span>
      <h1>{html.escape(str(payload.get('business') or 'Codee Owner Service'))}</h1>
      <p>{html.escape(str(payload.get('goal') or service.get('note') or 'Internal owner/admin preview generated instantly.'))}</p>
      <p><strong>Service:</strong> {html.escape(str(payload.get('service') or ''))} · <strong>Status:</strong> {html.escape(str(payload.get('activation_status') or ''))}</p>
    </section>
    <section><h2>What This Generates</h2><p>{html.escape(str(client_gets or 'Owner service preview and proof packet.'))}</p></section>
    <section><h2>Inputs</h2><p>{html.escape(str(required_inputs or 'Owner-provided business, target URL, and service brief.'))}</p></section>
    <section class="actions"><h2>Owner Links</h2><a href="{html.escape(str(payload.get('workspace_redirect_url') or '#'))}">Open Workbench</a><a href="{html.escape(str(payload.get('delivery_room_url') or '#'))}">Open Delivery Room</a><a href="https://codee.chat/">Powered by Codee</a></section>
    <section><h2>Proof</h2><ul><li>Payment bypass is marked owner/admin internal only.</li><li>Customer hosted activation still requires Stripe/payment proof.</li><li>Generated report is saved in <code>.codee/reports/latest-owner-generate.json</code>.</li></ul></section>
  </main>
</body>
</html>
"""


def _owner_generate_markdown(payload: dict[str, Any]) -> str:
    service = payload.get("service_record") if isinstance(payload.get("service_record"), dict) else {}
    lines = [
        "# Codee Owner Generate",
        "",
        f"Business: {payload.get('business')}",
        f"Service: {payload.get('service')}",
        f"Client ID: {payload.get('client_id')}",
        f"Status: {payload.get('activation_status')}",
        "",
        "## Owner No-Paywall Rule",
        "",
        "- This workspace was generated by the owner/admin command.",
        "- `requires_payment` is false for this local owner workspace.",
        "- Public customer hosted activation still requires Stripe/payment proof.",
        "- Do not publish this as a customer bypass code.",
        "",
        "## Service",
        "",
        f"- Label: {service.get('label') or payload.get('service')}",
        f"- Intake: {service.get('intake') or 'Owner-provided brief'}",
        f"- Delivery: {service.get('delivery') or 'Owner-generated preview and proof packet'}",
        "",
        "## Links",
        "",
        f"- Workbench: {payload.get('workbench_url')}",
        f"- Delivery room: {payload.get('delivery_room_url')}",
        f"- Hosted URL: {payload.get('hosted_url')}",
        "",
        "## Next Commands",
        "",
    ]
    for cmd in payload.get("next_commands") or []:
        lines.append(f"```bash\n{cmd}\n```")
    lines.append("")
    return "\n".join(lines)


def command_owner_generate(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    if args.write:
        root.mkdir(parents=True, exist_ok=True)
    service = _normalize_service(str(args.service or "codeeqr"))
    business = str(args.business or root.name or "Codee Owner Client").strip()
    client_id = _slugify(str(args.client_id or business or root.name))
    codee_user_id = str(args.codee_user_id or "").strip() or f"owner_{hashlib.sha256(client_id.encode('utf-8')).hexdigest()[:14]}"
    target_url = str(args.target_url or "").strip()
    service_record = _owner_generate_service_record(service)
    contract = _service_contract(service)
    public_base = str(args.public_base or DEFAULT_API_BASE).rstrip("/")
    query = urllib.parse.urlencode({
        "client_id": client_id,
        "workspace_id": client_id,
        "codee_user_id": codee_user_id,
        "service": service,
        "source": "codee-owner-generate",
        "activation_status": "owner_activated",
        "business": business,
    })
    payload = {
        "ok": True,
        "schema": "codee.owner-generate.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "source_surface": "codee-owner-cli",
        "owner_only": True,
        "owner_bypass": True,
        "payment_verified": True,
        "payment_proof": {
            "source": "owner-admin-local",
            "paid": True,
            "status": "owner_bypass",
            "metadata_allowed": True,
            "rule": "Owner/admin no-paywall generation is local/internal. Customer hosted activation stays Stripe-gated.",
        },
        "requires_payment": False,
        "activation_status": "owner_activated",
        "workspace_id": client_id,
        "client_id": client_id,
        "codee_user_id": codee_user_id,
        "business": business,
        "owner": str(args.owner or "Sean").strip(),
        "service": service,
        "target_url": target_url,
        "goal": str(args.goal or "").strip(),
        "service_record": service_record,
        "service_contract": contract,
        "workspace_redirect_url": f"{public_base}/codee-workbench.html?{query}",
        "workbench_url": f"{public_base}/codee-workbench.html?{query}",
        "delivery_room_url": f"{public_base}/codee-delivery.html?{query}",
        "hosted_url": f"{public_base}/codee-workbench.html?{query}",
        "next_commands": [
            f"codee owner-generate {shlex.quote(str(root))} --service {shlex.quote(service)} --business {shlex.quote(business)} --write --force",
            f"codee scan {shlex.quote(str(root))} --url {shlex.quote(f'{public_base}/codee-workbench.html?{query}')}",
            f"codee support {shlex.quote(str(root))} --service {shlex.quote(service)} --message \"Owner generated no-paywall workspace is ready for review.\"",
        ],
    }
    report_path = ""
    preview_path = ""
    if args.write:
        _write_json(root / ".codee" / "owner-generate.json", payload, force=bool(args.force))
        _write_json(root / ".codee" / "activation.json", payload, force=True)
        _write_text(root / ".codee" / "OWNER_GENERATE.md", _owner_generate_markdown(payload), force=True)
        _write_text(root / "owner-preview.html", _owner_generate_html(payload), force=bool(args.force))
        report_path = str(_write_report(root, "latest-owner-generate.json", payload))
        preview_path = str(root / "owner-preview.html")
        _append_event(root, "OwnerGenerateCreated", {"client_id": client_id, "service": service, "requires_payment": False})
    result = payload | {"report": report_path, "preview": preview_path}
    if args.json:
        print(json.dumps(result, indent=2))
    else:
        print(f"Codee owner generate: ok=True service={service} client_id={client_id}")
        print("requires_payment=False activation_status=owner_activated")
        if preview_path:
            print(f"preview={preview_path}")
        if report_path:
            print(f"report={report_path}")
    if args.open and preview_path:
        webbrowser.open(Path(preview_path).as_uri())
    return 0


def _mission_qrcodee_service_links(veteran_id: str, ref: str) -> dict[str, dict[str, str]]:
    def service_url(service: str) -> str:
        query = {
            "service": "codeeqr" if service == "free-audit" else service,
            "autostart": "1",
            "ref": ref,
            "mission": "veteran-mission-qrcodee",
            "veteran": veteran_id,
        }
        if service == "free-audit":
            query["service"] = "site-audit"
        if service == "codeeflyer100":
            query["service"] = "digiflyer"
            query["tier"] = "100"
        if service in {"codeeflyer250", "codeeflyer300"}:
            query["service"] = "digiflyer"
            query["tier"] = "300"
        if service == "business-suite":
            query["service"] = "minicodeesite"
            query["tier"] = "supported-build"
        return f"{DEFAULT_API_BASE}/codee-chat.html?{urllib.parse.urlencode(query)}"

    labels = {
        "codeeqr": "QRCodee",
        "codeeflyer100": "CodeeFlyer",
        "codeeflyer250": "CodeeFlyer",
        "codeeflyer300": "CodeeFlyer",
        "codeecard": "CodeeCard",
        "minicodeesite": "MiniCodeeSite",
        "business-suite": "Codee Business Suite",
        "free-audit": "Free Codee Audit",
    }
    return {
        service: {
            "label": label,
            "url": service_url(service),
            "tracking_rule": "Business lead keeps the veteran referral code in the Codee service URL.",
        }
        for service, label in labels.items()
    }


def _mission_qrcodee_payload(root: Path, args: argparse.Namespace) -> dict[str, Any]:
    manifest = _load_manifest(root)
    veteran_id = _slugify(str(getattr(args, "veteran_id", "") or getattr(args, "name", "") or "veteran-of-the-week"))
    display_name = str(getattr(args, "name", "") or manifest.get("owner") or "Veteran of the Week").strip()
    cash_tag = str(getattr(args, "cash_tag", "") or "AIK9Codee").strip().lstrip("$") or "AIK9Codee"
    support_url = str(getattr(args, "support_url", "") or f"https://cash.app/${cash_tag}").strip()
    ref = _slugify(str(getattr(args, "ref", "") or f"mission-{veteran_id}"))
    app_url = f"{CODEE_VETERAN_MISSION_QRCODEE_URL}?{urllib.parse.urlencode({'veteran': veteran_id})}"
    qr_target = str(getattr(args, "qr_target_url", "") or app_url).strip()
    service_links = _mission_qrcodee_service_links(veteran_id, ref)
    primary_service = _normalize_service(str(getattr(args, "business_service", "") or "codeeqr"))
    if primary_service not in service_links:
        primary_service = "codeeqr"
    payload = {
        "schema": "codee.mission-qrcodee.local-proof.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "workspace": str(root),
        "lane": "veteran-mission-qrcodee",
        "mode": "philanthropic_first_capitalistic_route",
        "veteran_price": "$0",
        "business_primary_service": primary_service,
        "profile": {
            "veteran_id": veteran_id,
            "display_name": display_name,
            "cohort": str(getattr(args, "cohort", "") or "homeless-or-disabled-veteran").strip(),
            "weekly_status": str(getattr(args, "weekly_status", "") or "ready_for_owner_selection").strip(),
            "story_public": str(getattr(args, "story_public", "") or "Owner-approved public-safe veteran story goes here before public promotion.").strip(),
            "support_need": str(getattr(args, "support_need", "") or "Owner-approved support need goes here.").strip(),
            "support_destination_label": str(getattr(args, "support_label", "") or f"${cash_tag}").strip(),
            "support_button_label": str(getattr(args, "support_button_label", "") or "Support this veteran").strip(),
            "support_url": support_url,
            "qr_target_url": qr_target,
            "qr_image_url": str(getattr(args, "qr_image_url", "") or f"{DEFAULT_API_BASE}/assets/codee/codee-chat-qr.png").strip(),
            "app_url": app_url,
            "affiliate_ref": ref,
            "service_links": service_links,
        },
        "proof": {
            "ok": True,
            "checks": [
                {"name": "public_veteran_app_route", "status": "configured", "proof": app_url},
                {"name": "support_button_destination", "status": "configured", "proof": support_url},
                {"name": "qr_target_url", "status": "configured", "proof": qr_target},
                {"name": "qrcodee_business_referral_link", "status": "configured", "proof": service_links["codeeqr"]["url"]},
                {"name": "referral_capture_api", "status": "configured", "proof": f"{DEFAULT_API_BASE}/api/mission-qrcodee/referral"},
                {"name": "free_veteran_no_checkout", "status": "configured", "proof": "Veteran app and profile are free for the veteran."},
                {"name": "paid_business_path", "status": "configured", "proof": "Business customers route to normal Codee paid-service checkout/support paths."},
            ],
            "guardrail": "No income, benefits, housing, grant, approval, or instant-payout promise.",
        },
        "next_commands": [
            f"CODEE veteran-mission {root} --write --force",
            f"CODEE test lane {root} --service codeeqr --route-check",
            f"CODEE support {root} --service veteran-mission-qrcodee --message \"Review mission QRCodee proof and publish the owner-approved profile.\"",
        ],
        "public_manifest": CODEE_VETERAN_MISSION_QRCODEE_MANIFEST_URL,
    }
    return payload


def _mission_qrcodee_markdown(payload: dict[str, Any]) -> str:
    profile = payload.get("profile") if isinstance(payload.get("profile"), dict) else {}
    proof = payload.get("proof") if isinstance(payload.get("proof"), dict) else {}
    lines = [
        "# Veteran Mission QRCodee",
        "",
        f"Veteran app: {profile.get('app_url', '')}",
        f"Referral code: {profile.get('affiliate_ref', '')}",
        f"Support destination: {profile.get('support_destination_label', '')}",
        f"QR target: {profile.get('qr_target_url', '')}",
        "",
        "## Rule",
        "",
        "The veteran app is free for the veteran. Business clients still use normal Codee paid-service checkout, delivery, support, and proof paths with the veteran referral code attached.",
        "",
        "## Business Links",
        "",
    ]
    service_links = profile.get("service_links") if isinstance(profile.get("service_links"), dict) else {}
    for service, item in service_links.items():
        if isinstance(item, dict):
            lines.append(f"- {item.get('label', service)}: {item.get('url', '')}")
    lines.extend(["", "## Proof Checks", ""])
    for check in proof.get("checks") or []:
        if isinstance(check, dict):
            lines.append(f"- {check.get('name')}: {check.get('status')} - {check.get('proof')}")
    lines.extend(["", "## Guardrail", "", str(proof.get("guardrail") or "")])
    return "\n".join(lines) + "\n"


def command_veteran_mission(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    if args.write:
        root.mkdir(parents=True, exist_ok=True)
    payload = _mission_qrcodee_payload(root, args)
    report_path = ""
    if args.write:
        _write_json(root / ".codee" / "veteran-mission-qrcodee.json", payload, force=args.force)
        _write_text(root / ".codee" / "VETERAN_MISSION_QRCODEE.md", _mission_qrcodee_markdown(payload), force=args.force)
        report_path = str(_write_report(root, "latest-veteran-mission-qrcodee.json", payload))
        _append_event(root, "VeteranMissionQRCodeePrepared", {"veteran_id": payload["profile"]["veteran_id"], "ref": payload["profile"]["affiliate_ref"]})
    if args.json:
        print(json.dumps(payload | {"report": report_path}, indent=2))
    else:
        profile = payload["profile"]
        print("Veteran Mission QRCodee")
        print(f"app={profile['app_url']}")
        print(f"support={profile['support_url']}")
        print(f"ref={profile['affiliate_ref']}")
        print(f"qrcodee={profile['service_links']['codeeqr']['url']}")
        if report_path:
            print(f"report={report_path}")
    return 0


def command_audit(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    if args.write:
        root.mkdir(parents=True, exist_ok=True)
    manifest = _load_manifest(root)
    service = _normalize_service(str(args.service or "free-audit"))
    if service not in {"free-audit", "audit-site"}:
        service = "free-audit"
    recommended_service = _normalize_service(str(args.recommended_service or "codeeqr"))
    business = str(args.business or manifest.get("business") or "").strip() or "Codee Client"
    owner = str(args.owner or manifest.get("owner") or "").strip() or "Business Owner"
    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()
    packet = _audit_delivery_payload(
        root=root,
        manifest=manifest,
        service=service,
        recommended_service=recommended_service,
        business=business,
        owner=owner,
        email=email,
        target_url=target_url,
        goal=goal,
    )
    report_path = ""
    if args.write:
        _write_json(root / ".codee" / "audit-flow.json", packet, force=args.force)
        _write_text(root / ".codee" / "AUDIT_FLOW.md", _audit_flow_markdown(packet), force=args.force)
        report_path = str(_write_report(root, "latest-audit-flow.json", packet))
        _append_event(
            root,
            "AuditFlow",
            {
                "service": service,
                "recommended_service": recommended_service,
                "workspace_id": packet["workspace_id"],
                "delivery_room_url": packet["delivery_room_url"],
            },
        )
    if args.json:
        print(json.dumps(packet | {"report": report_path}, indent=2))
    else:
        print(f"Codee audit flow: ok=true service={service} recommended={recommended_service}")
        print(f"business={packet['business']} workspace_id={packet['workspace_id']}")
        print(f"delivery_room={packet['delivery_room_url']}")
        print(f"audit_report={packet['audit_report_url']}")
        print(f"paid_preview={packet['paid_preview_url']}")
        if report_path:
            print(f"report={report_path}")
    return 0


def command_human_proof(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    promo_code = str(args.promo_code or CODEE_LIVE_PROOF_PROMO_CODE).strip().upper()
    promo_display = promo_code or "supplied at runtime only"
    payload = {
        "schema": "codee.cli.human_proof.v1",
        "ok": True,
        "created_at": _now(),
        "cli_version": VERSION,
        "human_proof_url": CODEE_HUMAN_PROOF_URL,
        "manifest_url": CODEE_HUMAN_PROOF_MANIFEST_URL,
        "promo_code": promo_code,
        "support_window_days": CODEE_SUPPORT_WINDOW_DAYS,
        "renewal_reminder_day": CODEE_RENEWAL_REMINDER_DAY,
        "recording_steps": [
            "Open Codee.chat and complete one lane intake.",
            "Show the locked preview and Stripe paywall.",
            "Apply the promo code in hosted Stripe checkout.",
            "Return to the delivery room and open the generated lane.",
            "Download or inspect Codee CLI and run client, connect, activate, room, and support commands.",
            "Fast-forward delivery room with support_day=25 to prove the renewal/support reminder copy.",
        ],
    }
    if args.write:
        report = _write_report(root, "latest-human-proof.json", payload)
        _write_text(root / ".codee" / "HUMAN_PROOF.md", "\n".join([
            "# Codee Human Proof Run",
            "",
            f"- Page: {payload['human_proof_url']}",
            f"- Promo code: {promo_display}",
            f"- Support reminder: day {payload['renewal_reminder_day']} of {payload['support_window_days']}",
            "",
            "## Steps",
            *[f"- {step}" for step in payload["recording_steps"]],
        ]), force=True)
        payload["report"] = str(report)
    if args.json:
        print(json.dumps(payload, indent=2))
    else:
        print(f"human_proof_url={payload['human_proof_url']}")
        print(f"manifest_url={payload['manifest_url']}")
        print(f"promo_code={promo_display}")
        print(f"renewal_reminder_day={payload['renewal_reminder_day']}")
        if payload.get("report"):
            print(f"report={payload['report']}")
    return 0


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))
    promo_code = str(getattr(args, "promo_code", "") or getattr(args, "promotion_code", "") or "").strip().upper()
    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,
        "promo_code": promo_code,
        "promotion_code": promo_code,
        "requested_promo_code": promo_code,
    }


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()
    manifest = _load_manifest(root)
    session = _session_payload(root)
    email = str(args.email or manifest.get("owner_email") or session.get("email") or "").strip().lower()
    if "@" not in email and sys.stdin.isatty():
        email = input("Receipt email: ").strip().lower()
    if "@" not in email:
        print("A valid --email is required so Stripe can send the hosted checkout receipt.")
        return 2
    args.email = email
    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()
    manifest = _load_manifest(root)
    session = _session_payload(root)
    email = str(args.email or manifest.get("owner_email") or session.get("email") or "").strip().lower()
    if "@" not in email and sys.stdin.isatty():
        email = input("Invoice email: ").strip().lower()
    if "@" not in email:
        print("A valid --email is required so Stripe can send the hosted invoice page.")
        return 2
    args.email = email
    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()
    domain_answer = str(getattr(args, "domain_preference", "") or "").strip()
    promo_code = str(getattr(args, "promo_code", "") or "").strip().upper()
    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 (free-audit/codeeqr/audit-site/codeeflyer100/codeeflyer300/codeecard/minicodeesite/business-suite)", service))
        target_url = _cli_prompt("Target URL or main CTA", target_url)
        goal = _cli_prompt("What should Codee generate or improve?", goal)
        domain_answer = _cli_prompt("Custom domain later? CODEE LINK, OWN DOMAIN, NOT SURE, or paste domain", domain_answer)
        promo_code = _cli_prompt("Promo code for live proof checkout, if any", promo_code).upper()
        if domain_answer and not getattr(args, "domain_preference", ""):
            args.domain_preference = domain_answer
        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)
    domain_support = _domain_support_request(args, manifest=manifest, service=service)
    chat_payload = _client_service_to_chat_payload(
        service,
        business=business or "Codee Client",
        email=email,
        target_url=target_url,
        goal=goal,
        domain_support=domain_support,
    )
    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",
            "promo_code": promo_code,
            "promotion_code": promo_code,
            "requested_promo_code": promo_code,
        }
    )
    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"],
        "live_proof_promo_code": promo_code or CODEE_LIVE_PROOF_PROMO_CODE,
        "support_window_days": CODEE_SUPPORT_WINDOW_DAYS,
        "renewal_reminder_day": CODEE_RENEWAL_REMINDER_DAY,
    }
    if service == "free-audit":
        paywall.update(
            {
                "status": "free_audit_open_paid_fixes_locked",
                "preview_window_minutes": 0,
                "unlock_rule": "Free audit report and delivery room stay open; hosted QR/site assets, fix queue, managed scans, and support unlock through the chosen paid lane.",
                "teachable_pattern": ["business goal", "target URL", "audit scorecard", "delivery room", "smallest paid lane", "Stripe unlock only after client chooses paid work"],
            }
        )
        chat_payload.update(
            {
                "paywall_mode": "free_audit_then_paid_lane",
                "true_deploy_status": "free_audit_open_paid_assets_locked",
            }
        )
    elif service == "audit-site":
        paywall.update(
            {
                "status": "audit_site_preview_payment_required",
                "unlock_rule": "Free audit can be reviewed first; hosted audit-site report, fix queue, and support lane unlock after payment.",
                "teachable_pattern": ["free audit", "hosted report preview", "Stripe unlock", "delivery room", "fix queue", "support handoff"],
            }
        )
        chat_payload.update(
            {
                "paywall_mode": "free_audit_to_paid_audit_site",
                "true_deploy_status": "hosted_audit_site_locked_until_paid",
            }
        )
    submit_command = f"codee client {shlex.quote(str(root))} --service {service} --business {shlex.quote(business or 'Codee Client')} --email {email or 'owner@example.com'} --target-url {shlex.quote(target_url or 'https://example.com')} --submit"
    shell_submit_command = f"bash {shlex.quote(str(root / '.codee' / 'submit-with-shell-curl.sh'))}"
    connect_command = f"codee connect {shlex.quote(str(root))} --service {service} --email {email or 'owner@example.com'}"
    activate_command = f"codee activate {shlex.quote(str(root))} --service {service}"
    verify_command = f"codee verify {shlex.quote(str(root))} --service {service}"
    if args.dry_run:
        next_commands = [
            submit_command,
            shell_submit_command,
            connect_command,
            activate_command,
            f"{verify_command}  # run after a generated site, activation packet, or delivery room exists",
        ]
    else:
        next_commands = [
            verify_command,
            submit_command,
            shell_submit_command,
            connect_command,
            activate_command,
        ]
    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,
        "domain_support": domain_support,
        "domain_connect_preference": domain_support["preference"],
        "custom_domain_name": domain_support["custom_domain_name"],
        "white_label_support_requested": "yes" if domain_support["white_label_support_requested"] else "no",
        "promo_code": promo_code,
        "support_window_days": CODEE_SUPPORT_WINDOW_DAYS,
        "renewal_reminder_day": CODEE_RENEWAL_REMINDER_DAY,
        "paywall": paywall,
        "connector_plan": connector_plan,
        "chat_intake_payload": chat_payload,
        "next_commands": next_commands,
    }
    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}")
        print(f"domain_support={domain_support.get('preference')} custom_domain={domain_support.get('custom_domain_name') or 'none'}")
        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, CodeeCard, MiniCodeeSite, and Codee Business Suite 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, CodeeCard, MiniCodeeSite, 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",
            "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."),
        ("CodeeFlyer", "A prompt, reference, or both become one hosted flyer with verified QR proof and up to three actions."),
        ("CodeeCard", "A person or brand gets a profile card with booking, message, and proof path."),
        ("MiniCodeeSite", "A small shop, service, or offer becomes a hosted site lane with checkout or contact proof."),
        ("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 = _normalize_plan_id(args.plan)
    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": _service_contract(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 view 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. Save audit event and session proof.",
                        "6. Keep mouse and keyboard input disabled; it is not implemented in this release.",
                        "",
                    ]
                ),
                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": [
                "Open the certificate-free browser setup page; do not launch the legacy unsigned .command file.",
                "Press Copy Install to download and fingerprint-verify readable host source.",
                "Press Copy Secure Sign-in to store the owner token privately in macOS Keychain.",
                "Press Copy Connect to create the secure host link and background service.",
                "Optionally press Copy Full Control to compile mouse, keyboard, and reviewed voice-text support locally.",
            ],
            "phone_cli_bridge": {
                "status": "live-four-command-allowlist",
                "commands": ["status", "heartbeat", "doctor", "scan"],
                "outside_home": True,
                "blocked": ["raw shell", "secret access", "unapproved deploy"],
            },
            "security_note": "The browser-first host does not ship owner credentials or bypass macOS privacy permissions. The phone CLI bridge is allowlisted rather than unrestricted shell access.",
        }
        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}",
                        "",
                        "Open the installer page and use four plain-language copy actions:",
                        "1. Copy Install",
                        "2. Copy Secure Sign-in",
                        "3. Copy Connect",
                        "4. Copy Full Control (optional)",
                        "",
                        "Phone CLI bridge: Status, Heartbeat, Doctor, and Route Scan work outside the home after trusted pairing.",
                        "Raw shell, secret access, and unapproved deploys remain blocked.",
                        "",
                    ]
                ),
                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_help_me(args: argparse.Namespace) -> int:
    words = [str(item).strip() for item in (getattr(args, "message", []) or []) if str(item).strip()]
    path = str(getattr(args, "path", ".") or ".")
    if len(words) > 1:
        candidate = Path(words[0]).expanduser()
        if candidate.exists():
            path = str(candidate)
            words = words[1:]
    message = " ".join(words).strip()
    if not message:
        print('Usage: CODEE help-me "Fix my flyer link"')
        return 2
    support_args = argparse.Namespace(
        path=path,
        service=getattr(args, "service", "codee-support"),
        type=getattr(args, "type", "site-update"),
        title=getattr(args, "title", ""),
        message=message,
        route=getattr(args, "route", ""),
        attachment=getattr(args, "attachment", None),
        priority=getattr(args, "priority", "normal"),
        email=getattr(args, "email", ""),
        business=getattr(args, "business", ""),
        owner=getattr(args, "owner", ""),
        delivery_room_url=getattr(args, "delivery_room_url", ""),
        api_base=getattr(args, "api_base", DEFAULT_API_BASE),
        timeout=getattr(args, "timeout", "30"),
        submit=bool(getattr(args, "submit", False)),
        dry_run=bool(getattr(args, "dry_run", False)),
        open=bool(getattr(args, "open", False)),
        json=bool(getattr(args, "json", False)),
    )
    return command_support(support_args)


def _owner_dev_file_inventory(root: Path, requested_files: list[str], mode: str) -> list[dict[str, Any]]:
    common = [
        "tools/codee_cli.py",
        "tools/sync_codeeadmin_public_assets.py",
        "Codee original/frontend-public/assets/downloads/codee-cli.py",
        "Codee original/frontend-public/codee-owner-cli.html",
        "Codee original/frontend-public/codee-cli.html",
        "Codee original/frontend-public/codee-runtime.js",
        "Codee original/frontend-public/sw.js",
        "Codee original/backend/dashboard_routes.py",
        "Codee original/backend/social_oauth.py",
        "Codee original/backend/social_autopost.py",
        "Codee original/backend/deploy_now.sh",
        "Codee original/backend/.env.example",
        "Codee original/backend/.env.template",
    ]
    mode_files = {
        "frontend": [
            "Codee original/frontend-public/codee-owner-cli.html",
            "Codee original/frontend-public/codee-cli.html",
            "Codee original/frontend-public/codee-runtime.js",
            "Codee original/frontend-public/sw.js",
        ],
        "backend": [
            "Codee original/backend/dashboard_routes.py",
            "Codee original/backend/social_oauth.py",
            "Codee original/backend/social_autopost.py",
            "Codee original/backend/deploy_now.sh",
        ],
        "social": [
            "Codee original/backend/social_oauth.py",
            "Codee original/backend/dashboard_routes.py",
            "Codee original/frontend-public/codee-owner-cli.html",
            "Codee original/backend/docs/CODEE_META_APP_SETUP_RUNBOOK.md",
        ],
        "deploy": [
            "Codee original/backend/deploy_now.sh",
            "firebase.json",
            "Codee original/frontend-public/firebase.json",
        ],
        "fullstack": common,
    }
    wanted = list(dict.fromkeys([*(mode_files.get(mode) or []), *common, *requested_files]))
    inventory: list[dict[str, Any]] = []
    for raw in wanted:
        text = str(raw or "").strip()
        if not text:
            continue
        path = Path(text).expanduser()
        if not path.is_absolute():
            path = root / path
        item: dict[str, Any] = {"path": str(path), "requested": text in requested_files}
        try:
            rel = path.resolve().relative_to(root.resolve())
            item["relative_path"] = str(rel)
        except Exception:
            item["relative_path"] = str(path)
        if path.exists() and path.is_file():
            try:
                data = path.read_bytes()
                item.update({"exists": True, "bytes": len(data), "sha256_12": hashlib.sha256(data).hexdigest()[:12]})
            except Exception as exc:
                item.update({"exists": True, "error": f"{type(exc).__name__}: {exc}"})
        else:
            item["exists"] = False
        inventory.append(item)
    return inventory


def _owner_dev_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee Owner Dev Packet",
        "",
        f"Status: {payload.get('status')}",
        f"Created: {payload.get('created_at')}",
        f"Mode: {payload.get('mode')}",
        f"Client: {payload.get('client_id')}",
        f"Service: {payload.get('service')}",
        "",
        "## Request",
        "",
        str(payload.get("request") or "No request entered."),
        "",
        "## Operating Rules",
        "",
    ]
    for item in payload.get("operating_rules") or []:
        lines.append(f"- {item}")
    lines.extend(["", "## Edit Scope", ""])
    for item in payload.get("edit_scope") or []:
        lines.append(f"- {item}")
    lines.extend(["", "## File Inventory", ""])
    for item in payload.get("file_inventory") or []:
        state = "exists" if item.get("exists") else "missing"
        lines.append(f"- {item.get('relative_path')}: {state}")
    lines.extend(["", "## Proof Gates", ""])
    for item in payload.get("proof_gates") 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 command_owner_dev(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _load_manifest(root)
    mode = str(args.mode or "fullstack").strip().lower()
    if mode not in CODEE_OWNER_DEV_MODEL["edit_modes"]:
        mode = "fullstack"
    client_id = _slugify(str(args.client or manifest.get("client_id") or root.name))
    service = _normalize_service(str(args.service or manifest.get("service") or "codee-owner-dev"))
    request_text = str(args.request or "").strip() or "Owner wants Codee to plan, edit, prove, and package a frontend/backend site change."
    ticket_seed = f"{client_id}:{service}:{mode}:{request_text}:{_now()}"
    ticket_id = f"odev_{hashlib.sha256(ticket_seed.encode('utf-8')).hexdigest()[:16]}"
    root_q = shlex.quote(str(root))
    mode_q = shlex.quote(mode)
    request_q = shlex.quote(request_text[:180])
    service_q = shlex.quote(service)
    route = str(args.route or "").strip()
    route_q = shlex.quote(route or "https://clients.codee.chat/codee-owner-cli.html")
    frontend_modes = {"frontend", "fullstack", "social", "deploy"}
    backend_modes = {"backend", "fullstack", "social", "deploy"}
    proof_gates = [
        "Checkpoint exists before edits.",
        "Sensitive files are not copied into support packets or public downloads.",
        "Relevant frontend route is scanned after visible edits.",
        "Downloadable CLI copy is synced when tools/codee_cli.py changes.",
    ]
    if mode in backend_modes:
        proof_gates.insert(2, "Python compile passes for touched backend or CLI files.")
    if mode in frontend_modes:
        proof_gates.insert(3, "Browser or route proof is captured for changed public pages.")
    next_commands = [
        f"codee checkpoint {root_q} --label before-{ticket_id}",
        f"codee owner-dev {root_q} --mode {mode_q} --service {service_q} --request {request_q} --write --force",
        f"codee doctor {root_q} --local-only",
    ]
    if mode in backend_modes:
        next_commands.append('python3 -m py_compile "Codee original/backend/dashboard_routes.py" "Codee original/backend/social_oauth.py" tools/codee_cli.py')
    if mode in frontend_modes:
        next_commands.append(f"codee scan {root_q} --url {route_q}")
    next_commands.extend(
        [
            "python3 tools/sync_codeeadmin_public_assets.py",
            'cp tools/codee_cli.py "Codee original/frontend-public/assets/downloads/codee-cli.py"',
            'python3 "Codee original/frontend-public/assets/downloads/codee-cli.py" --version',
            f"curl -L {CODEE_DOWNLOAD_URL} -o codee.py",
            "python3 codee.py --version",
        ]
    )
    payload = {
        "ok": True,
        "schema": "codee.owner-dev.packet.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "status": "edit-workflow-ready",
        "ticket_id": ticket_id,
        "mode": mode,
        "client_id": client_id,
        "business": str(args.business or manifest.get("business") or client_id).strip(),
        "owner": str(args.owner or manifest.get("owner") or "Sean").strip(),
        "service": service,
        "route": route,
        "request": request_text,
        "model": CODEE_OWNER_DEV_MODEL,
        "operating_rules": CODEE_OWNER_DEV_MODEL["operating_rules"],
        "edit_scope": (CODEE_OWNER_DEV_MODEL["edit_modes"].get(mode) or {}).get("roots") or [],
        "proof_gates": proof_gates,
        "file_inventory": _owner_dev_file_inventory(root, [str(item).strip() for item in (args.file or [])], mode),
        "download_commands": CODEE_OWNER_DEV_MODEL["download_commands"],
        "next_commands": next_commands,
    }
    packet_dir = root / ".codee" / "owner-dev"
    packet_path = packet_dir / f"{ticket_id}.json"
    markdown_path = packet_dir / f"{ticket_id}.md"
    wrote = False
    if args.write:
        _write_json(packet_path, payload, force=args.force)
        _write_text(markdown_path, _owner_dev_markdown(payload), force=args.force)
        _write_report(root, "latest-owner-dev.json", payload | {"packet": str(packet_path), "markdown": str(markdown_path)})
        _append_event(root, "OwnerDevPacketCreated", {"ticket_id": ticket_id, "client_id": client_id, "service": service, "mode": mode})
        wrote = True
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "packet": str(packet_path), "markdown": str(markdown_path)}, indent=2))
    else:
        print(f"Codee owner dev: ok=True ticket={ticket_id} mode={mode} wrote={wrote}")
        print(f"client_id={client_id}")
        print(f"download={CODEE_DOWNLOAD_URL}")
        print(f"manifest={CODEE_OWNER_DEV_MANIFEST_URL}")
        if wrote:
            print(f"packet={packet_path}")
            print(f"markdown={markdown_path}")
    if args.open:
        webbrowser.open(CODEE_OWNER_CLI_URL)
    return 0


def _codex_bridge_file_inventory(root: Path, requested_files: list[str]) -> list[dict[str, Any]]:
    wanted = list(dict.fromkeys([*CODEE_CODEX_BRIDGE_MODEL["inspection_files"], *requested_files]))
    inventory: list[dict[str, Any]] = []
    for raw in wanted:
        text = str(raw or "").strip()
        if not text:
            continue
        path = Path(text).expanduser()
        if not path.is_absolute():
            path = root / path
        item: dict[str, Any] = {"path": str(path), "requested": text in requested_files}
        try:
            rel = path.resolve().relative_to(root.resolve())
            item["relative_path"] = str(rel)
        except Exception:
            item["relative_path"] = str(path)
        if path.exists() and path.is_file():
            try:
                data = path.read_bytes()
                item.update({"exists": True, "bytes": len(data), "sha256_12": hashlib.sha256(data).hexdigest()[:12]})
            except Exception as exc:
                item.update({"exists": True, "error": f"{type(exc).__name__}: {exc}"})
        else:
            item["exists"] = False
        inventory.append(item)
    return inventory


def _codex_bridge_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee Codex Bridge",
        "",
        f"Status: {payload.get('status')}",
        f"Created: {payload.get('created_at')}",
        f"CLI Version: {payload.get('cli_version')}",
        f"Client: {payload.get('client_id')}",
        "",
        "## Request",
        "",
        str(payload.get("request") or "No request entered."),
        "",
        "## Codex Entry Rule",
        "",
        str(payload.get("model", {}).get("codex_entry_rule") or ""),
        "",
        "## Live URLs",
        "",
    ]
    for key, url in (payload.get("live_urls") or {}).items():
        lines.append(f"- {key}: {url}")
    lines.extend(["", "## File Inventory", ""])
    for item in payload.get("file_inventory") or []:
        state = "exists" if item.get("exists") else "missing"
        digest = f" sha256={item.get('sha256_12')}" if item.get("sha256_12") else ""
        lines.append(f"- {item.get('relative_path')}: {state}{digest}")
    lines.extend(["", "## Enhancement Backlog", ""])
    for item in payload.get("enhancement_backlog") or []:
        lines.append(f"- {item.get('id')} ({item.get('priority')}): {item.get('goal')}")
    lines.extend(["", "## Proof Commands", ""])
    for command in payload.get("proof_commands") or []:
        lines.append(f"```bash\n{command}\n```")
    if payload.get("route_checks"):
        lines.extend(["", "## Route Checks", ""])
        for item in payload.get("route_checks") or []:
            lines.append(f"- {item.get('name')}: ok={item.get('ok')} status={item.get('status')} url={item.get('url')}")
    return "\n".join(lines) + "\n"


def command_codex_bridge(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _load_manifest(root)
    client_id = _slugify(str(args.client or manifest.get("client_id") or root.name))
    request_text = str(args.request or "").strip() or "Make Codee CLI reachable to Codex for live state, missing updates, and safe enhancement work."
    bridge_seed = f"{client_id}:{request_text}:{_now()}"
    bridge_id = f"cxb_{hashlib.sha256(bridge_seed.encode('utf-8')).hexdigest()[:16]}"
    root_q = shlex.quote(str(root))
    live_targets = [
        {"name": "cli-page", "url": f"{DEFAULT_API_BASE}/codee-cli", "expected": [200]},
        {"name": "alpha-pack", "url": CODEE_ALPHA_PACK_URL, "expected": [200]},
        {"name": "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": "owner-dev-manifest", "url": CODEE_OWNER_DEV_MANIFEST_URL, "expected": [200]},
        {"name": "codex-bridge-manifest", "url": CODEE_CODEX_BRIDGE_MANIFEST_URL, "expected": [200]},
    ]
    route_checks: list[dict[str, Any]] = []
    if args.live_check:
        route_checks = [_route_check(target, float(args.timeout or 20)) for target in live_targets]
    proof_commands = [
        "python3 -m py_compile tools/codee_cli.py tools/sync_codeeadmin_public_assets.py",
        "python3 tools/sync_codeeadmin_public_assets.py",
        'cp tools/codee_cli.py "Codee original/frontend-public/assets/downloads/codee-cli.py"',
        'python3 "Codee original/frontend-public/assets/downloads/codee-cli.py" --version',
        f"codee codex-bridge {root_q} --write --force --json",
        f"codee scan {root_q} --url {shlex.quote(str(CODEE_DOWNLOAD_URL))} --url {shlex.quote(str(CODEE_CODEX_BRIDGE_MANIFEST_URL))}",
        f"curl -L {CODEE_DOWNLOAD_URL} -o codee.py",
        "python3 codee.py --version",
    ]
    payload = {
        "ok": bool(not route_checks or all(item.get("ok") for item in route_checks)),
        "schema": "codee.codex-bridge.packet.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "status": "codex-reachable",
        "bridge_id": bridge_id,
        "client_id": client_id,
        "business": str(args.business or manifest.get("business") or client_id).strip(),
        "owner": str(args.owner or manifest.get("owner") or "Sean").strip(),
        "request": request_text,
        "model": CODEE_CODEX_BRIDGE_MODEL,
        "live_urls": CODEE_CODEX_BRIDGE_MODEL["live_urls"],
        "codex_commands": CODEE_CODEX_BRIDGE_MODEL["codex_commands"],
        "file_inventory": _codex_bridge_file_inventory(root, [str(item).strip() for item in (args.file or [])]),
        "enhancement_backlog": CODEE_CODEX_BRIDGE_MODEL["enhancement_backlog"],
        "codex_allowed_actions": CODEE_CODEX_BRIDGE_MODEL["codex_allowed_actions"],
        "owner_gated_actions": CODEE_CODEX_BRIDGE_MODEL["owner_gated_actions"],
        "proof_commands": proof_commands,
        "route_targets": live_targets,
        "route_checks": route_checks,
        "next_owner_dev_command": f"codee owner-dev {root_q} --mode fullstack --request {shlex.quote(request_text[:160])} --write --force",
    }
    packet_dir = root / ".codee" / "codex-bridge"
    packet_path = packet_dir / f"{bridge_id}.json"
    markdown_path = packet_dir / f"{bridge_id}.md"
    wrote = False
    if args.write:
        _write_json(packet_path, payload, force=args.force)
        _write_text(markdown_path, _codex_bridge_markdown(payload), force=args.force)
        _write_report(root, "latest-codex-bridge.json", payload | {"packet": str(packet_path), "markdown": str(markdown_path)})
        _append_event(root, "CodexBridgePacketCreated", {"bridge_id": bridge_id, "client_id": client_id})
        wrote = True
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "packet": str(packet_path), "markdown": str(markdown_path)}, indent=2))
    else:
        print(f"Codee Codex bridge: ok={payload['ok']} bridge={bridge_id} wrote={wrote}")
        print(f"download={CODEE_DOWNLOAD_URL}")
        print(f"manifest={CODEE_CODEX_BRIDGE_MANIFEST_URL}")
        print("entry=codee codex-bridge . --write --force --json")
        if route_checks:
            print(f"routes_ok={sum(1 for item in route_checks if item.get('ok'))}/{len(route_checks)}")
        if wrote:
            print(f"packet={packet_path}")
            print(f"markdown={markdown_path}")
    if args.open:
        webbrowser.open(f"{DEFAULT_API_BASE}/codee-cli")
    return 0


def command_codex_sync(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    root.mkdir(parents=True, exist_ok=True)
    payload = _codex_parity_payload(
        root,
        apply_codee_update=bool(args.apply_codee_update),
        timeout=float(args.timeout or 8),
    )
    parity_path = root / ".codee" / "codex-parity.json"
    markdown_path = root / ".codee" / "CODEX_PARITY.md"
    hook_path = root / ".codee" / "update-hooks" / "codex-sync.sh"
    wrote = False
    if args.write:
        _write_json(parity_path, payload, force=args.force)
        _write_text(markdown_path, _codex_parity_markdown(payload), force=args.force)
        _write_text(hook_path, _codex_sync_shell(root, apply_codee_update=bool(args.apply_codee_update)), force=args.force)
        try:
            hook_path.chmod(0o755)
        except Exception:
            pass
        state = _load_state(root)
        state["codex_sync"] = {
            "at": payload.get("created_at"),
            "codex_version": payload.get("codex", {}).get("version") if isinstance(payload.get("codex"), dict) else "",
            "status": payload.get("status"),
            "codee_update_attempted": bool((payload.get("codee_update") or {}).get("attempted") if isinstance(payload.get("codee_update"), dict) else False),
        }
        _write_state(root, state)
        _write_report(root, "latest-codex-sync.json", payload | {"parity": str(parity_path), "markdown": str(markdown_path), "hook": str(hook_path)})
        _append_event(root, "CodexSyncCompleted", {"status": payload.get("status"), "codex_version": payload.get("codex", {}).get("version") if isinstance(payload.get("codex"), dict) else ""})
        wrote = True
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "parity": str(parity_path), "markdown": str(markdown_path), "hook": str(hook_path)}, indent=2))
    else:
        codex = payload.get("codex") if isinstance(payload.get("codex"), dict) else {}
        update = payload.get("codee_update") if isinstance(payload.get("codee_update"), dict) else {}
        print(f"Codee Codex sync: ok={payload['ok']} status={payload['status']} wrote={wrote}")
        print(f"codex_version={codex.get('version') or 'not-found'}")
        print(f"codee_version={VERSION}")
        print(f"changed={payload.get('codex_version_changed')} first_sync={payload.get('first_sync')}")
        if update.get("attempted"):
            print(f"codee_update_ok={update.get('ok')} wrote={update.get('wrote')} status={update.get('http_status')}")
        print(f"parity={parity_path}")
        print(f"hook={hook_path}")
        print("connection=local version watcher, not direct OpenAI release subscription")
    return 0 if payload["ok"] else 1


def _heel_teacher_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee HEEL Teacher Packet",
        "",
        f"Status: {payload.get('status')}",
        f"Created: {payload.get('created_at')}",
        f"CLI Version: {payload.get('cli_version')}",
        f"Business: {payload.get('business')}",
        f"Teacher: {payload.get('teacher_name')}",
        f"Teacher Email: {payload.get('teacher_email') or 'not set'}",
        "",
        "## Request",
        "",
        str(payload.get("request") or "No request entered."),
        "",
        "## What The Teacher Receives",
        "",
    ]
    for item in payload.get("teacher_receives") or []:
        lines.append(f"- {item}")
    lines.extend(["", "## Login Command", "", "```bash", str(payload.get("login_command") or ""), "```", "", "## HEEL Commands", ""])
    for command in payload.get("heel_commands") or []:
        lines.append(f"```bash\n{command}\n```")
    lines.extend(["", "## Safe Rules", ""])
    for item in payload.get("safe_rules") or []:
        lines.append(f"- {item}")
    return "\n".join(lines) + "\n"


def command_heel(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _load_manifest(root)
    business = str(args.business or manifest.get("business") or root.name).strip()
    owner = str(args.owner or manifest.get("owner") or "Sean").strip()
    teacher_name = str(args.teacher or args.owner or manifest.get("owner") or "Codee Teacher").strip()
    teacher_email = str(args.teacher_email or args.email or manifest.get("owner_email") or "").strip().lower()
    student_email = str(args.student_email or "").strip().lower()
    client_id = _slugify(str(args.client or manifest.get("client_id") or root.name))
    service = _normalize_service(str(args.service or manifest.get("service") or "codee-heel"))
    request_text = str(args.request or "").strip() or "Teacher/support helper needs a login-ready Codee packet, diagnosis flow, and safe owner handoff."
    route = str(args.route or "").strip()
    heel_seed = f"{client_id}:{teacher_email}:{service}:{request_text}:{_now()}"
    heel_id = f"heel_{hashlib.sha256(heel_seed.encode('utf-8')).hexdigest()[:16]}"
    root_q = shlex.quote(str(root))
    business_q = shlex.quote(business)
    teacher_q = shlex.quote(teacher_name)
    email_for_command = teacher_email or "teacher@example.com"
    teacher_email_q = shlex.quote(email_for_command)
    request_q = shlex.quote(request_text[:160])
    service_q = shlex.quote(service)
    route_q = shlex.quote(route or CODEE_OWNER_CLI_URL)
    login_command = f"codee login {root_q} --email {teacher_email_q} --business {business_q} --owner {teacher_q} --write"
    login_fallback_command = f"python3 codee.py login {root_q} --email {teacher_email_q} --business {business_q} --owner {teacher_q} --write"
    heel_commands = [
        login_command,
        f"codee doctor {root_q} --local-only",
        f"codee codex-bridge {root_q} --write --force --json",
        f"codee owner-dev {root_q} --mode fullstack --service {service_q} --request {request_q} --write --force",
        f"codee owner-support {root_q} --client {shlex.quote(client_id)} --service codee-support --request {request_q} --write --force",
        f"codee scan {root_q} --url {route_q}",
        f"curl -L {CODEE_DOWNLOAD_URL} -o codee.py",
        "./CODEE --version",
        "./CODEE install . --write",
    ]
    safe_rules = [
        "Do not ask for passwords, private keys, .env files, OAuth tokens, Stripe secrets, or Google Cloud credentials.",
        "Use `codee login` for local identity; use official OAuth screens for social or app connectors.",
        "Create a checkpoint before changing client-facing files.",
        "Use `codex-bridge` before asking Codex to enhance the CLI, frontend, or backend.",
        "Use owner-dev for edits and owner-support for support rescue.",
    ]
    live_targets = [
        {"name": "cli-page", "url": f"{DEFAULT_API_BASE}/codee-cli", "expected": [200]},
        {"name": "cli-download", "url": CODEE_DOWNLOAD_URL, "expected": [200]},
        {"name": "heel-teacher-manifest", "url": CODEE_HEEL_TEACHER_MANIFEST_URL, "expected": [200]},
        {"name": "heal-teacher-legacy-manifest", "url": CODEE_HEAL_TEACHER_MANIFEST_URL, "expected": [200]},
        {"name": "codex-bridge-manifest", "url": CODEE_CODEX_BRIDGE_MANIFEST_URL, "expected": [200]},
    ]
    route_checks: list[dict[str, Any]] = []
    if args.live_check:
        route_checks = [_route_check(target, float(args.timeout or 20)) for target in live_targets]
    payload = {
        "ok": bool((teacher_email or not args.require_email) and (not route_checks or all(item.get("ok") for item in route_checks))),
        "schema": "codee.heel.packet.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "status": "teacher-packet-ready",
        "heel_id": heel_id,
        "client_id": client_id,
        "business": business,
        "owner": owner,
        "teacher_name": teacher_name,
        "teacher_email": teacher_email,
        "student_email": student_email,
        "service": service,
        "route": route,
        "request": request_text,
        "login_ready": bool(teacher_email),
        "login_command": login_command,
        "login_fallback_command": login_fallback_command,
        "model": CODEE_HEEL_TEACHER_MODEL,
        "teacher_receives": CODEE_HEEL_TEACHER_MODEL["teacher_receives"],
        "heel_commands": heel_commands,
        "heal_commands": heel_commands,
        "safe_rules": safe_rules,
        "route_targets": live_targets,
        "route_checks": route_checks,
        "download_url": CODEE_DOWNLOAD_URL,
        "manifest_url": CODEE_HEEL_TEACHER_MANIFEST_URL,
        "legacy_manifest_url": CODEE_HEAL_TEACHER_MANIFEST_URL,
        "codex_bridge_manifest_url": CODEE_CODEX_BRIDGE_MANIFEST_URL,
    }
    packet_dir = root / ".codee" / "heel"
    packet_path = packet_dir / f"{heel_id}.json"
    markdown_path = packet_dir / f"{heel_id}.md"
    teacher_packet_path = root / ".codee" / "teacher-packet.json"
    wrote = False
    if args.write:
        _write_json(packet_path, payload, force=args.force)
        _write_text(markdown_path, _heel_teacher_markdown(payload), force=args.force)
        _write_json(teacher_packet_path, payload, force=True)
        _write_report(root, "latest-heel.json", payload | {"packet": str(packet_path), "markdown": str(markdown_path), "teacher_packet": str(teacher_packet_path)})
        _write_report(root, "latest-heal.json", payload | {"packet": str(packet_path), "markdown": str(markdown_path), "teacher_packet": str(teacher_packet_path)})
        _append_event(root, "HeelTeacherPacketCreated", {"heel_id": heel_id, "client_id": client_id, "teacher_email": teacher_email})
        wrote = True
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "packet": str(packet_path), "markdown": str(markdown_path), "teacher_packet": str(teacher_packet_path)}, indent=2))
    else:
        print(f"Codee heel: ok={payload['ok']} heel={heel_id} wrote={wrote}")
        print(f"login_ready={payload['login_ready']}")
        print(f"login_command={login_command}")
        print(f"manifest={CODEE_HEEL_TEACHER_MANIFEST_URL}")
        if wrote:
            print(f"packet={packet_path}")
            print(f"teacher_packet={teacher_packet_path}")
    if args.open:
        webbrowser.open(f"{DEFAULT_API_BASE}/codee-cli")
    return 0 if payload["ok"] else 1


def _owner_support_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee Owner Support Packet",
        "",
        f"Status: {payload.get('status')}",
        f"Created: {payload.get('created_at')}",
        f"Client: {payload.get('client_id')}",
        f"Service: {payload.get('service')}",
        "",
        "## Request",
        "",
        str(payload.get("request") or "No request entered."),
        "",
        "## Frontend Checklist",
        "",
    ]
    for item in payload.get("frontend_checklist") or []:
        lines.append(f"- {item.get('label')}: {item.get('proof')}")
    social = payload.get("social_connect") if isinstance(payload.get("social_connect"), dict) else {}
    if social:
        lines.extend(["", "## AI K9 Codee Social Connect", ""])
        lines.append(f"- Client link: {social.get('client_connect_url')}")
        lines.append(f"- Facebook OAuth link: {social.get('facebook_connect_url')}")
        lines.append(f"- Facebook status URL: {social.get('facebook_status_url')}")
        lines.append(f"- Rule: {social.get('visible_rule')}")
        lines.append(f"- No-secret rule: {social.get('no_secret_rule')}")
    lines.extend(["", "## Outdated CLI Protocol", ""])
    for item in payload.get("outdated_cli_protocol") 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 command_social_connect(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _load_manifest(root)
    client_id = _slugify(str(args.client or manifest.get("client_id") or root.name))
    platform = str(args.platform or "facebook").strip().lower()
    if platform not in {"facebook", "instagram", "pinterest", "youtube", "tiktok"}:
        platform = "facebook"
    client_connect_url = f"{CODEE_SOCIAL_CONNECT_URL}?client_id={urllib.parse.quote(client_id)}&service=codee_social_connect&platform={urllib.parse.quote(platform)}"
    oauth_start_url = f"{CODEE_BACKEND_API_BASE}/api/dashboard/{urllib.parse.quote(client_id)}/oauth/start?platform={urllib.parse.quote(platform)}&redirect=1&return_to={urllib.parse.quote(client_connect_url, safe=':/?=&')}"
    status_url = f"{CODEE_BACKEND_API_BASE}/api/dashboard/{urllib.parse.quote(client_id)}/auth/{urllib.parse.quote(platform)}/status"
    payload = {
        "ok": True,
        "schema": "codee.social-connect.terminal.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "client_id": client_id,
        "platform": platform,
        "name": "AI K9 Codee Social Connect",
        "status": "connect-link-ready",
        "client_connect_url": client_connect_url,
        "oauth_start_url": oauth_start_url,
        "status_url": status_url,
        "client_terminal_lines": [
            "AI K9 Codee Social Connect online.",
            f"Client: {client_id}",
            f"Platform: {platform}",
            "Open the secure connect link. Do not send passwords or tokens.",
            "Codee will read connection status after the official provider callback.",
        ],
        "guardrails": [
            "Use official OAuth or approved client-share screens only.",
            "Never collect social passwords, OAuth tokens, cookies, app secrets, or page tokens in chat.",
            "Keep Metricool as a fallback scheduler only where direct platform posting is not approved yet.",
        ],
    }
    if args.open:
        webbrowser.open(client_connect_url)
    if args.json:
        print(json.dumps(payload, indent=2))
    else:
        print("AI K9 Codee Social Connect")
        print(f"client_id={client_id}")
        print(f"platform={platform}")
        print(f"connect_url={client_connect_url}")
        print(f"oauth_start={oauth_start_url}")
        print(f"status_url={status_url}")
        print("status=connect-link-ready")
    return 0


def command_owner_support(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _load_manifest(root)
    client_id = _slugify(str(args.client or manifest.get("client_id") or root.name))
    service = _normalize_service(str(getattr(args, "service", "") or manifest.get("service") or "codee-support"))
    request_text = str(args.request or "").strip() or "Client cannot complete a frontend edit from their current Codee CLI."
    ticket_seed = f"{client_id}:{service}:{request_text}:{_now()}"
    ticket_id = f"osup_{hashlib.sha256(ticket_seed.encode('utf-8')).hexdigest()[:16]}"
    root_q = shlex.quote(str(root))
    service_q = shlex.quote(service)
    priority_q = shlex.quote(str(args.priority or "normal").strip())
    title_q = shlex.quote(f"{client_id} frontend support")
    request_q = shlex.quote(request_text[:140])
    social_connect_url = f"{CODEE_SOCIAL_CONNECT_URL}?client_id={urllib.parse.quote(client_id)}&service=codee_social_connect"
    facebook_connect_url = f"{CODEE_BACKEND_API_BASE}/api/dashboard/{urllib.parse.quote(client_id)}/oauth/start?platform=facebook&redirect=1&return_to={urllib.parse.quote(social_connect_url, safe=':/?=&')}"
    facebook_status_url = f"{CODEE_BACKEND_API_BASE}/api/dashboard/{urllib.parse.quote(client_id)}/auth/facebook/status"
    social_connect_model = dict(CODEE_OWNER_SUPPORT_MODEL.get("social_connect") or {})
    social_connect_packet = {
        **social_connect_model,
        "client_connect_url": social_connect_url,
        "facebook_connect_url": facebook_connect_url,
        "facebook_status_url": facebook_status_url,
        "live_assistance": [
            "Client opens one Codee Social Connect link.",
            "Codee checks Facebook status in real time.",
            "If not connected, Codee opens the official Meta OAuth screen.",
            "After callback, Codee reads Page context and reports what is ready next.",
        ],
        "terminal_preview": [
            f"codee social-connect . --client {client_id} --platform facebook",
            f"connect_url={social_connect_url}",
            f"facebook_oauth={facebook_connect_url}",
            "status=waiting_for_client_connection",
        ],
    }
    payload = {
        "ok": True,
        "schema": "codee.owner-support.packet.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "status": "triage-ready",
        "ticket_id": ticket_id,
        "client_id": client_id,
        "business": str(args.business or manifest.get("business") or client_id).strip(),
        "owner": str(args.owner or manifest.get("owner") or "Sean").strip(),
        "service": service,
        "priority": str(args.priority or "normal").strip(),
        "route": str(args.route or "").strip(),
        "request": request_text,
        "support_team": [str(item).strip() for item in (args.team or []) if str(item).strip()],
        "source_surface": "codee-owner-cli",
        "model": CODEE_OWNER_SUPPORT_MODEL,
        "frontend_checklist": CODEE_OWNER_SUPPORT_MODEL["frontend_edit_lanes"],
        "outdated_cli_protocol": CODEE_OWNER_SUPPORT_MODEL["outdated_cli_protocol"],
        "social_connect": social_connect_packet if service == "social-connect" else {},
        "guardrails": [
            "Use checkpoints before edits.",
            "Do not collect client passwords, .env files, private keys, OAuth tokens, or payment secrets.",
            "Use official OAuth connect screens for Facebook, Instagram, Google, Canva, Adobe, and WordPress.",
            "Close a request only after route proof or screenshot proof is attached.",
        ],
        "next_commands": [
            f"codee checkpoint {root_q} --label before-{client_id}-support",
            f"codee doctor {root_q} --local-only",
            f"codee support {root_q} --service {service_q} --type site-update --title {title_q} --message {request_q} --priority {priority_q}",
            f"codee self-update {root_q} --target ./codee.py --write",
        ],
    }
    if service == "social-connect":
        payload["next_commands"].insert(2, f"open {shlex.quote(social_connect_url)}")
        payload["next_commands"].insert(3, f"curl -L {shlex.quote(facebook_status_url)}")
    packet_dir = root / ".codee" / "owner-support"
    packet_path = packet_dir / f"{ticket_id}.json"
    markdown_path = packet_dir / f"{ticket_id}.md"
    wrote = False
    if args.write:
        _write_json(packet_path, payload, force=args.force)
        _write_text(markdown_path, _owner_support_markdown(payload), force=args.force)
        _write_report(root, "latest-owner-support.json", payload | {"packet": str(packet_path), "markdown": str(markdown_path)})
        _append_event(root, "OwnerSupportPacketCreated", {"ticket_id": ticket_id, "client_id": client_id, "service": service})
        wrote = True
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "packet": str(packet_path), "markdown": str(markdown_path)}, indent=2))
    else:
        print(f"Codee owner support: ok=True ticket={ticket_id} wrote={wrote}")
        print(f"client_id={client_id}")
        print(f"page={CODEE_OWNER_CLI_URL}")
        print(f"manifest={CODEE_OWNER_CLI_MANIFEST_URL}")
        if wrote:
            print(f"packet={packet_path}")
            print(f"markdown={markdown_path}")
    if args.open:
        webbrowser.open(CODEE_OWNER_CLI_URL)
    return 0


def command_admin_cli(args: argparse.Namespace) -> int:
    request = str(args.request or "").strip()
    if not request:
        print('Usage: codee admin-cli "update the homepage and deploy it"')
        return 2
    lowered = request.lower()
    if any(word in lowered for word in ("deploy", "publish", "push live", "frontend", "edit", "site", "page", "design", "upload image", "image upload")):
        return command_owner_dev(
            argparse.Namespace(
                path=args.path,
                mode="fullstack",
                client=str(args.client or ""),
                business=str(args.business or ""),
                owner=str(args.owner or "Sean"),
                service=str(args.service or "codee-owner-dev"),
                request=request,
                route=str(args.route or ""),
                file=list(getattr(args, "file", []) or []),
                write=bool(args.write),
                force=bool(args.force),
                open=bool(args.open),
                json=bool(args.json),
            )
        )
    if any(word in lowered for word in ("state", "playbook", "daily digest", "owner ops", "admin ops", "company", "policy", "packet")):
        return command_codeeadmin(
            argparse.Namespace(
                path=args.path,
                business=str(args.business or "AI K9 / Invest In Vets"),
                owner=str(args.owner or "Sean"),
                focus=str(args.focus or "land housing mission"),
                month=str(args.month or ""),
                state=list(getattr(args, "state", []) or []),
                all_states=bool(getattr(args, "all_states", False)),
                write=bool(args.write),
                force=bool(args.force),
                open=bool(args.open),
                json=bool(args.json),
            )
        )
    return command_owner_support(
        argparse.Namespace(
            path=args.path,
            client=str(args.client or ""),
            business=str(args.business or ""),
            owner=str(args.owner or "Sean"),
            service=str(args.service or "codee-support"),
            request=request,
            route=str(args.route or ""),
            priority="normal",
            team=list(getattr(args, "team", []) or []),
            write=bool(args.write),
            force=bool(args.force),
            open=bool(args.open),
            json=bool(args.json),
        )
    )


def _admin_edit_token() -> str:
    return str(os.getenv("CODEE_ADMIN_TOKEN") or os.getenv("ADMIN_TOKEN") or "").strip()


def _admin_edit_headers(*, required: bool) -> tuple[dict[str, str], str]:
    token = _admin_edit_token()
    if required and not token:
        return {}, "Set CODEE_ADMIN_TOKEN in the owner shell. Tokens are never accepted as CLI arguments or written to reports."
    return ({"Authorization": f"Bearer {token}"} if token else {}), ""


def command_preview_edit(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _load_manifest(root)
    client_id = _slugify(str(args.client or manifest.get("client_id") or root.name))
    site_key = str(args.site_key or manifest.get("client_id") or client_id).strip()
    requested_change = str(args.request or "").strip()
    suggested_copy = str(args.copy or "").strip()
    if not requested_change or not suggested_copy:
        print("Both --request and --copy are required. Use structured copy such as 'headline: New headline'.", file=sys.stderr)
        return 2
    payload = {
        "siteKey": site_key,
        "pageKey": str(args.page or "home").strip(),
        "sectionKey": str(args.section or "hero").strip(),
        "actionType": "update",
        "requestedChange": requested_change,
        "suggestedCopy": suggested_copy,
        "priority": str(args.priority or "normal"),
        "status": "pending_review",
        "sourceLane": "codee_cli_admin",
        "sourceType": "codee_cli_preview",
        "requesterName": str(args.requester or manifest.get("owner") or "Codee Owner").strip(),
        "requesterEmail": str(args.email or "").strip(),
        "notes": "Preview only. Explicit owner approval is required before apply.",
    }
    url = _api_url(args.api_base, f"/api/dashboard/{urllib.parse.quote(client_id)}/change-requests")
    result: dict[str, Any]
    if args.submit:
        result = _request_json("POST", url, payload, timeout=float(args.timeout))
    else:
        result = {"ok": True, "status": "preview_request_ready", "submitted": False, "url": url, "request": payload}
    report = {
        "ok": bool(result.get("ok")),
        "schema": "codee.admin-edit-preview.v1",
        "created_at": _now(),
        "client_id": client_id,
        "submitted": bool(args.submit),
        "result": result,
        "approval_required": True,
        "next_command": "codee approve-edit . --client CLIENT --request-id REQUEST_ID --submit",
    }
    if args.write:
        report_path = _write_report(root, "latest-admin-edit-preview.json", report)
        report["report"] = str(report_path)
    if args.json:
        print(json.dumps(report, indent=2))
    else:
        record = result.get("record") if isinstance(result.get("record"), dict) else {}
        request_id = str(record.get("changeRequestId") or "")
        print(f"Codee edit preview: ok={report['ok']} submitted={args.submit} request_id={request_id or 'pending'}")
        print("No live file was changed. Explicit approval is required.")
    return 0 if report["ok"] else 1


def _command_edit_lifecycle(args: argparse.Namespace, action: str) -> int:
    root = Path(args.path).expanduser().resolve()
    manifest = _load_manifest(root)
    client_id = _slugify(str(args.client or manifest.get("client_id") or root.name))
    request_id = str(args.request_id or "").strip()
    if not request_id:
        print("--request-id is required.", file=sys.stderr)
        return 2
    method = "GET" if action == "status" else "POST"
    suffix = "" if action == "status" else f"/{action}"
    url = _api_url(args.api_base, f"/api/dashboard/{urllib.parse.quote(client_id)}/change-requests/{urllib.parse.quote(request_id)}{suffix}")
    required_token = action in {"approve", "apply", "rollback"}
    headers, token_error = _admin_edit_headers(required=required_token)
    if token_error and args.submit:
        print(token_error, file=sys.stderr)
        return 2
    if args.submit:
        result = _request_json(method, url, {} if method == "POST" else None, timeout=float(args.timeout), headers=headers)
    else:
        result = {"ok": True, "status": f"{action}_ready", "submitted": False, "url": url, "admin_token_present": bool(headers)}
    report = {
        "ok": bool(result.get("ok")),
        "schema": f"codee.admin-edit-{action}.v1",
        "created_at": _now(),
        "client_id": client_id,
        "request_id": request_id,
        "action": action,
        "submitted": bool(args.submit),
        "result": result,
        "token_stored": False,
    }
    if args.write:
        report_path = _write_report(root, f"latest-admin-edit-{action}.json", report)
        report["report"] = str(report_path)
    if args.json:
        print(json.dumps(report, indent=2))
    else:
        print(f"Codee edit {action}: ok={report['ok']} submitted={args.submit} request_id={request_id}")
    return 0 if report["ok"] else 1


def command_approve_edit(args: argparse.Namespace) -> int:
    return _command_edit_lifecycle(args, "approve")


def command_apply_edit(args: argparse.Namespace) -> int:
    return _command_edit_lifecycle(args, "apply")


def command_rollback_edit(args: argparse.Namespace) -> int:
    return _command_edit_lifecycle(args, "rollback")


def command_edit_status(args: argparse.Namespace) -> int:
    return _command_edit_lifecycle(args, "status")


def _deploy_adapter_commands(root: Path, args: argparse.Namespace) -> dict[str, list[str]]:
    platform = str(args.platform or "").strip()
    source = str(args.source or "").strip()
    target = str(args.target or "").strip()
    live_url = str(args.url or "").strip()
    project = str(args.project or "").strip()
    site = str(args.site or "").strip()
    rollback_source = str(args.rollback_source or "").strip()
    proven = root / "Codee original" / "backend" / "scripts" / "codee_proven_deploy.sh"
    if platform == "gcs-client":
        if target and not target.startswith("gs://clients.codee.chat/"):
            raise ValueError("gcs-client --target must stay under gs://clients.codee.chat/")
        return {
            "apply": ["gcloud", "storage", "cp", source, target],
            "verify": ["bash", str(proven), "verify-url", live_url],
            "rollback": ["gcloud", "storage", "cp", rollback_source, target],
        }
    if platform == "made-for-this-firebase":
        deploy_script = root / "MADE_FOR_THIS_CLIENT_HANDOFF_20260502" / "site-root" / "deploy_now.sh"
        return {
            "apply": ["bash", str(deploy_script)],
            "verify": ["python3", "-c", "import urllib.request,sys; r=urllib.request.urlopen(sys.argv[1],timeout=20); print(r.status); raise SystemExit(0 if r.status==200 else 1)", live_url or "https://madeforthisblog.web.app/"],
            "rollback": ["firebase", "hosting:rollback", site or "madeforthisblog", "--project", project or "madeforthisblog", "--non-interactive"],
        }
    if platform == "firebase-hosting":
        config = str(args.config or "firebase.json")
        if not project or not site:
            raise ValueError("firebase-hosting requires --project and --site")
        return {
            "apply": ["firebase", "deploy", "--config", config, "--only", f"hosting:{site}", "--project", project, "--non-interactive"],
            "verify": ["python3", "-c", "import urllib.request,sys; r=urllib.request.urlopen(sys.argv[1],timeout=20); print(r.status); raise SystemExit(0 if r.status==200 else 1)", live_url],
            "rollback": ["firebase", "hosting:rollback", site, "--project", project, "--non-interactive"],
        }
    if platform == "cloud-run":
        return {
            "apply": ["bash", str(proven), "backend-build-candidate"],
            "verify": ["bash", str(proven), "launch-gate", "--backend-url", live_url],
            "rollback": ["gcloud", "run", "services", "update-traffic", "ai-k9-codee-digiapp", "--project", "digiapp-clients", "--region", "us-central1", "--to-revisions", f"{rollback_source}=100"],
        }
    raise ValueError("Unknown deploy adapter platform")


def command_deploy_adapter(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    phase = str(args.phase or "preview").strip()
    adapter_dir = root / ".codee" / "deploy-adapters"
    approval_path = adapter_dir / f"{args.platform}-approval.json"
    try:
        commands = _deploy_adapter_commands(root, args)
    except ValueError as exc:
        print(str(exc), file=sys.stderr)
        return 2
    selected = commands.get(phase, [])
    token_present = bool(_admin_edit_token())
    approved = approval_path.exists()
    if phase == "approve":
        if not token_present:
            print("Set CODEE_ADMIN_TOKEN in the owner shell before approval.", file=sys.stderr)
            return 2
        selected = []
        approved = True
        if args.write:
            approval_path.parent.mkdir(parents=True, exist_ok=True)
            approval_path.write_text(json.dumps({"schema": "codee.deploy-approval.v1", "platform": args.platform, "approved_at": _now(), "token_stored": False}, indent=2) + "\n", encoding="utf-8")
    if phase in {"apply", "rollback"} and not approved:
        print(f"Approve first: codee deploy-adapter . --platform {args.platform} --phase approve --write", file=sys.stderr)
        return 2
    if phase in {"apply", "verify", "rollback"} and (not selected or any(not part for part in selected)):
        print(f"Missing required adapter input for {phase}.", file=sys.stderr)
        return 2
    execution = {"requested": bool(args.execute), "ran": False, "returncode": None, "output": ""}
    if args.execute and selected:
        completed = subprocess.run(selected, cwd=str(root), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=False, timeout=float(args.timeout))
        execution = {"requested": True, "ran": True, "returncode": completed.returncode, "output": str(completed.stdout or "")[-20000:]}
    payload = {
        "ok": execution["returncode"] in {None, 0},
        "schema": "codee.deploy-adapter.v1",
        "created_at": _now(),
        "platform": args.platform,
        "phase": phase,
        "approved": approved,
        "approval_required": phase in {"apply", "rollback"},
        "command": selected,
        "all_phases": commands,
        "execution": execution,
        "rollback_source": str(args.rollback_source or ""),
        "live_url": str(args.url or ""),
        "token_stored": False,
    }
    if args.write:
        report_path = _write_report(root, f"latest-deploy-adapter-{args.platform}-{phase}.json", payload)
        payload["report"] = str(report_path)
    print(json.dumps(payload, indent=2) if args.json else f"Codee deploy adapter: ok={payload['ok']} platform={args.platform} phase={phase} approved={approved} executed={execution['ran']}")
    return 0 if payload["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] = _all_service_contracts()
    payload: dict[str, Any] = {
        "ok": True,
        "schema": "codee.service-contracts.v1",
        "updated_at": "2026-05-28",
        "domain_support_policy": CODEE_DOMAIN_SUPPORT_POLICY,
        "contracts": contracts,
    }
    if service:
        payload = {
            "ok": service in CODEE_SERVICE_CONTRACTS,
            "schema": "codee.service-contracts.v1",
            "updated_at": "2026-05-28",
            "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(),
        "codex_parity": (root / ".codee" / "codex-parity.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", "expected": [200]},
        {"name": "codee-alpha-pack", "url": CODEE_ALPHA_PACK_URL, "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": "owner-cli-page", "url": CODEE_OWNER_CLI_URL, "expected": [200]},
        {"name": "owner-cli-manifest", "url": CODEE_OWNER_CLI_MANIFEST_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"codee login {root} --email owner@example.com --business \"My Business\" --write",
            f"codee permissions {root} --mode workspace --write --force",
            f"codee registry {root} --write --force",
            f"codee launch {root} --write --force",
            f"codee codeecpa {root} --write --force",
            f"codee company {root} --write --force",
            f"codee checkpoint {root} --label before-next-build",
            f"codee 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"
    codee_alias_path = root / "CODEE"
    windows_launcher_path = root / "CODEE.bat"
    bin_dir = Path(str(args.bin_dir or "~/.local/bin")).expanduser().resolve()
    global_launcher_path = bin_dir / "codee"
    global_codee_alias_path = bin_dir / "CODEE"
    global_cli_path = bin_dir.parent / "share" / "codee" / "codee.py"
    command_prefix = "codee" if args.global_command else "./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" "$@"',
                "",
            ]
        )
        for local_launcher in (launcher_path, codee_alias_path):
            _write_text(local_launcher, launcher, force=True)
            try:
                local_launcher.chmod(0o755)
            except Exception:
                pass
        windows_launcher = "\n".join(
            [
                "@echo off",
                "setlocal",
                "where py >nul 2>nul",
                "if %errorlevel%==0 (",
                '  py -3 "%~dp0codee.py" %*',
                ") else (",
                '  python "%~dp0codee.py" %*',
                ")",
                "",
            ]
        )
        _write_text(windows_launcher_path, windows_launcher, force=True)
        if args.global_command:
            bin_dir.mkdir(parents=True, exist_ok=True)
            global_cli_path.parent.mkdir(parents=True, exist_ok=True)
            if source != global_cli_path:
                _checkpoint_existing_path(global_cli_path, reason="install-global-cli")
                global_cli_path.write_text(source.read_text(encoding="utf-8"), encoding="utf-8")
            _checkpoint_existing_path(global_launcher_path, reason="install-global-launcher")
            global_launcher = "\n".join(
                [
                    "#!/usr/bin/env bash",
                    "set -euo pipefail",
                    f'python3 "{global_cli_path}" "$@"',
                    "",
                ]
            )
            for global_launcher_candidate in (global_launcher_path, global_codee_alias_path):
                _write_text(global_launcher_candidate, global_launcher, force=True)
                try:
                    global_launcher_candidate.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",
                    f"{command_prefix} doctor .",
                    f"{command_prefix} login . --email owner@example.com --business \"My Business\" --write",
                    f"{command_prefix} heel . --teacher-email teacher@example.com --write --force",
                    f"{command_prefix} codex-bridge . --write --force --json",
                    "```",
                    "",
                    "Upgrade:",
                    "",
                    "```bash",
                    f"{command_prefix} self-update . --target ./codee.py --write",
                    "```",
                    "",
                    "Global command:",
                    "",
                    "`CODEE ...` works when `install --global` created a launcher in your user bin folder. If your shell cannot find it, use `./CODEE ...` from this workspace or add the bin folder to PATH. Lowercase `codee ...` is also written as a compatibility alias.",
                    "",
                ]
            ),
            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),
        "codee_alias_path": str(codee_alias_path),
        "windows_launcher_path": str(windows_launcher_path),
        "global_launcher_path": str(global_launcher_path),
        "global_codee_alias_path": str(global_codee_alias_path),
        "global_cli_path": str(global_cli_path),
        "global_command": bool(args.global_command),
        "path_hint": f"Add {bin_dir} to PATH if `CODEE` is not found.",
        "notes_path": str(notes_path),
        "wrote": bool(args.write),
        "next_commands": [
            f"{command_prefix} doctor .",
            f"{command_prefix} login . --email owner@example.com --business \"My Business\" --write",
            f"{command_prefix} heel . --teacher-email teacher@example.com --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:
        color, emoji = _codee_terminal_style(args)
        badge = "🐾 " if emoji else ""
        next_command = "codee" if args.global_command else "./CODEE"
        lines = [
            f"{badge}AI K9 Codee installed",
            f"Version: {VERSION}",
            f"Start: {next_command}",
            "Fallback: ./CODEE (Mac/Linux) or CODEE.bat (Windows)",
        ]
        if args.global_command:
            lines.append(f"PATH folder: {bin_dir}")
        _codee_update_box(lines, color=color)
        print("Details: .codee/reports/latest-install.json")
    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))
    resolved_url = url
    if url == CODEE_DOWNLOAD_URL:
        origin_result = _curl_fetch("GET", CODEE_ORIGIN_DOWNLOAD_URL, timeout=float(args.timeout))
        origin_body = str(origin_result.get("body") or "")
        if origin_result.get("ok") and "VERSION" in origin_body[:5000]:
            result = origin_result
            resolved_url = CODEE_ORIGIN_DOWNLOAD_URL
    body = str(result.get("body") or "")
    official_release = url in {CODEE_DOWNLOAD_URL, CODEE_ORIGIN_DOWNLOAD_URL}
    signature = _verify_official_cli_signature(body, timeout=float(args.timeout)) if official_release and result.get("ok") else {"verified": not official_release, "scheme": "custom-url-unverified", "error": ""}
    ok_body = bool(result.get("ok") and "VERSION" in body[:5000] and signature.get("verified"))
    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,
        "resolved_url": resolved_url,
        "target": str(target),
        "http_status": result.get("status"),
        "wrote": wrote,
        "checkpoint": checkpoint,
        "signature": signature,
        "message": "Downloaded latest CLI. Use --write to replace the target file." if ok_body and not args.write else "",
        "error": (signature.get("error") or 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 _extract_cli_version(source: str) -> str:
    match = re.search(r'^VERSION\s*=\s*"([^"]+)"', source, re.MULTILINE)
    return match.group(1) if match else ""


def _verify_official_cli_signature(source: str, *, timeout: float) -> dict[str, Any]:
    manifest_result = _curl_fetch("GET", CODEE_RELEASE_URL, timeout=timeout)
    try:
        manifest = json.loads(str(manifest_result.get("body") or "")) if manifest_result.get("ok") else {}
    except json.JSONDecodeError:
        manifest = {}
    release = manifest.get("cli_release") if isinstance(manifest.get("cli_release"), dict) else {}
    expected_sha = str(release.get("sha256") or "").strip().lower()
    signature_text = str(release.get("signature_base64") or "").strip()
    actual_sha = hashlib.sha256(source.encode("utf-8")).hexdigest()
    verified = False
    error = ""
    try:
        signature = base64.b64decode(signature_text, validate=True)
        key_bytes = (CODEE_RELEASE_RSA_MODULUS.bit_length() + 7) // 8
        encoded = pow(int.from_bytes(signature, "big"), CODEE_RELEASE_RSA_EXPONENT, CODEE_RELEASE_RSA_MODULUS).to_bytes(key_bytes, "big")
        digest_info = bytes.fromhex("3031300d060960864801650304020105000420") + bytes.fromhex(actual_sha)
        expected_encoded = b"\x00\x01" + (b"\xff" * (key_bytes - len(digest_info) - 3)) + b"\x00" + digest_info
        verified = bool(expected_sha == actual_sha and hmac.compare_digest(encoded, expected_encoded))
        if not verified:
            error = "release_signature_or_sha256_mismatch"
    except Exception as exc:
        error = f"release_signature_invalid:{type(exc).__name__}"
    return {
        "verified": verified,
        "scheme": str(release.get("signature_scheme") or "rsa-pkcs1v15-sha256"),
        "expected_sha256": expected_sha,
        "actual_sha256": actual_sha,
        "manifest_status": manifest_result.get("status"),
        "error": error,
    }


def _codee_terminal_style(args: argparse.Namespace) -> tuple[bool, bool]:
    plain = bool(getattr(args, "plain", False))
    color = bool(
        not plain
        and sys.stdout.isatty()
        and os.getenv("NO_COLOR", "").strip().lower() not in {"1", "true", "yes", "on"}
        and os.getenv("CODEE_NO_COLOR", "").strip().lower() not in {"1", "true", "yes", "on"}
    )
    emoji = bool(
        not plain
        and not bool(getattr(args, "no_emoji", False))
        and os.getenv("CODEE_NO_EMOJI", "").strip().lower() not in {"1", "true", "yes", "on"}
    )
    return color, emoji


def _codee_ansi(text: str, code: str, enabled: bool) -> str:
    return f"\033[{code}m{text}\033[0m" if enabled else text


CODEE_LOGO_SPLIT_COLUMN = 25
CODEE_LOGO_MARK = [
    "             /\\                 /\\",
    "         ___/  \\__          __/[]\\",
    "      __/         \\________/  []  \\",
    "    _/   /\\             |    /[]\\  \\",
    "   /   _/  \\     o      |[o]/ [==]   \\",
    "  |   /     \\           | /    []|   |",
    "  |  /       \\__________|/      _|   |",
    "  | /          /          |\\____/ |   /",
    "  |/     _____/           | []    |  /",
    "   \\____/    \\     _____|_______|_/",
    "       \\      \\___/     | []  /",
    "        \\_____/   \\______|____/",
    "              \\____/      \\",
]

CODEE_LOGO_MARK_NARROW = [
    "        /\\           /\\",
    "     __/  \\_________/[]\\",
    "   _/  /\\      |   /[]  \\",
    "  /  _/  \\  o |[o]/[==]  \\",
    " |  /     \\___|__/  []|  |",
    " | /       /   | \\___/| /",
    "  \\______/ ___|______|/",
    "      \\___/   |[]  /",
    "          \\___|___/",
]


def _print_codee_logo_mark(*, color: bool, emoji: bool) -> None:
    terminal_width = shutil.get_terminal_size((80, 24)).columns
    mark = CODEE_LOGO_MARK_NARROW if terminal_width < 54 else CODEE_LOGO_MARK
    split_column = 15 if mark is CODEE_LOGO_MARK_NARROW else CODEE_LOGO_SPLIT_COLUMN
    for line in mark:
        organic = line[:split_column]
        ai = line[split_column:]
        print(_codee_ansi(organic, "97", color) + _codee_ansi(ai, "96", color))
    caption = "🐾 AI K9 Codee is ready. Local-first. Keys stay yours." if emoji else "AI K9 Codee is ready. Local-first. Keys stay yours."
    print(_codee_ansi(caption, "1;92", color))


def _codee_update_box(lines: list[str], *, color: bool) -> None:
    width = max(42, min(72, max(len(line) for line in lines) + 4))
    top = "╭" + ("─" * (width - 2)) + "╮"
    bottom = "╰" + ("─" * (width - 2)) + "╯"
    border = "96"
    print(_codee_ansi(top, border, color))
    for line in lines:
        clipped = line if len(line) <= width - 4 else line[: width - 7] + "..."
        print(_codee_ansi("│", border, color) + f" {clipped.ljust(width - 4)} " + _codee_ansi("│", border, color))
    print(_codee_ansi(bottom, border, color))


def command_latest(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))
    resolved_url = url
    if url == CODEE_DOWNLOAD_URL:
        origin_result = _curl_fetch("GET", CODEE_ORIGIN_DOWNLOAD_URL, timeout=float(args.timeout))
        origin_body = str(origin_result.get("body") or "")
        if origin_result.get("ok") and _extract_cli_version(origin_body):
            result = origin_result
            resolved_url = CODEE_ORIGIN_DOWNLOAD_URL
    body = str(result.get("body") or "")
    remote_version = _extract_cli_version(body)
    official_release = url in {CODEE_DOWNLOAD_URL, CODEE_ORIGIN_DOWNLOAD_URL}
    signature = _verify_official_cli_signature(body, timeout=float(args.timeout)) if official_release and result.get("ok") else {"verified": not official_release, "scheme": "custom-url-unverified", "error": ""}
    ok_body = bool(result.get("ok") and remote_version and "VERSION" in body[:5000] and signature.get("verified"))
    same_version = bool(remote_version and remote_version == VERSION)
    color, emoji = _codee_terminal_style(args)
    badge = "🐾 " if emoji else ""
    should_write = False
    prompted = False
    if ok_body:
        if args.yes:
            should_write = not same_version
        elif not same_version and sys.stdin.isatty() and not args.json:
            prompted = True
            _codee_update_box(
                [
                    f"{badge}CODEE latest update available",
                    f"Current: {VERSION}",
                    f"Newest:  {remote_version}",
                    "1. Update CODEE now",
                    "2. Continue without update",
                ],
                color=color,
            )
            answer = input(_codee_ansi("Choose 1 or 2: ", "1;96", color)).strip().lower()
            should_write = answer in {"1", "update", "u", "yes", "y"}
        elif same_version and not args.json:
            _codee_update_box(
                [
                    f"{badge}CODEE is current",
                    f"Current: {VERSION}",
                    "No update needed right now.",
                ],
                color=color,
            )
    wrote = False
    checkpoint = ""
    if should_write and ok_body:
        checkpoint = _checkpoint_existing_path(target, reason="latest-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.latest.v1",
        "created_at": _now(),
        "current_version": VERSION,
        "remote_version": remote_version,
        "same_version": same_version,
        "url": url,
        "resolved_url": resolved_url,
        "target": str(target),
        "http_status": result.get("status"),
        "prompted": prompted,
        "wrote": wrote,
        "checkpoint": checkpoint,
        "signature": signature,
        "message": (
            "Could not verify the public CODEECLI release. Try again later."
            if not ok_body
            else "Already on the latest visible public CODEECLI release."
            if same_version
            else "CODEE was updated."
            if wrote
            else "Update ready. Re-run with --yes to apply without a prompt."
        ),
        "error": (signature.get("error") or result.get("error")) if not ok_body else "",
    }
    report_path = _write_report(root, "latest-codee-update.json", payload)
    if args.json:
        print(json.dumps(payload | {"report": str(report_path)}, indent=2))
    else:
        if not ok_body:
            _codee_update_box(
                [
                    f"{badge}CODEE update check could not verify the release",
                    f"Status: {result.get('status') or 'no response'}",
                    "Keep working, then try again later.",
                ],
                color=color,
            )
        elif wrote:
            _codee_update_box(
                [
                    f"{badge}CODEE updated",
                    f"Installed: {remote_version}",
                    f"Checkpoint: {checkpoint or 'none'}",
                ],
                color=color,
            )
        print(f"Codee latest: ok={payload['ok']} current={VERSION} remote={remote_version or 'unknown'} wrote={wrote}")
        if payload.get("message"):
            print(f"message={payload['message']}")
        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 and sys.stdin.isatty() and not bool(getattr(args, "json", False)):
        email = input("Owner email: ").strip().lower()
    if "@" not in email:
        message = 'Run `CODEE login` in Terminal, or use `CODEE login --email owner@example.com --business "My Business" --write`.'
        if bool(getattr(args, "json", False)):
            print(json.dumps({"ok": False, "error": "missing_valid_email", "message": message}, indent=2))
        else:
            print(message)
        return 2
    business = str(args.business or manifest.get("business") or "Codee Client").strip()
    if (not args.business and business == "Codee Client") and sys.stdin.isatty() and not bool(getattr(args, "json", False)):
        business_answer = input("Business name [Codee Client]: ").strip()
        if business_answer:
            business = business_answer
    owner = str(args.owner or manifest.get("owner") or "Business Owner").strip()
    if (not args.owner and owner == "Business Owner") and sys.stdin.isatty() and not bool(getattr(args, "json", False)):
        owner_answer = input("Owner name [Business Owner]: ").strip()
        if owner_answer:
            owner = owner_answer
    client_id = str(args.client_id or manifest.get("client_id") or _slugify(business)).strip()
    service = _normalize_service(str(getattr(args, "service", "") or manifest.get("service") or "codee-support"))
    if not getattr(args, "service", "") and sys.stdin.isatty() and not bool(getattr(args, "json", False)):
        service_answer = input(f"Service lane [{service}]: ").strip()
        if service_answer:
            service = _normalize_service(service_answer)
    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,
        "service": service,
        "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)
        _write_session(
            root,
            {
            "business": business,
            "owner": owner,
            "email": email,
            "client_id": client_id,
            "workspace_id": client_id,
            "codee_user_id": codee_user_id,
            "service": service,
            "api_base": CODEE_BACKEND_API_BASE,
        },
        )
        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"service={service}")
        print(f"report={report_path}")
        if bool(getattr(args, "open", False)):
            webbrowser.open(CODEE_OWNER_CLI_URL)
    return 0 if result.get("ok") else 1


def command_session(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    root.mkdir(parents=True, exist_ok=True)
    current = _session_payload(root)
    updates: dict[str, Any] = {}
    for key in ("email", "business", "owner", "client_id", "service", "api_base"):
        value = str(getattr(args, key, "") or "").strip()
        if value:
            updates[key] = _normalize_service(value) if key == "service" else value.rstrip("/") if key == "api_base" else value
    if args.clear:
        session_path = root / ".codee" / "session.json"
        state = _load_state(root)
        state.pop("session", None)
        _write_state(root, state)
        if session_path.exists():
            _checkpoint_existing_path(session_path, reason="session-clear")
            session_path.unlink()
        payload = {"ok": True, "schema": "codee.session-clear.v1", "root": str(root), "cleared": True}
        if args.json:
            print(json.dumps(payload, indent=2))
        else:
            print("Codee session cleared.")
        return 0
    payload = {**current, **updates, "updated_at": _now()}
    wrote = False
    session_path = root / ".codee" / "session.json"
    if args.write or updates:
        session_path = _write_session(root, payload)
        _append_event(root, "SessionConfigured", {"client_id": payload.get("client_id"), "service": payload.get("service")})
        wrote = True
    _write_report(root, "latest-session.json", payload | {"wrote": wrote, "session_path": str(session_path)})
    if args.json:
        print(json.dumps(payload | {"ok": True, "wrote": wrote, "session_path": str(session_path)}, indent=2))
    else:
        print("Codee session")
        print(f"client_id={payload.get('client_id')}")
        print(f"service={payload.get('service')}")
        print(f"email={payload.get('email') or 'not-set'}")
        print(f"api_base={payload.get('api_base')}")
        print(f"wrote={wrote}")
        print("Start like Codex/Claude: run `codee` for prompt mode, then type a request.")
    return 0


def _admin_queue_proof_mode(request_text: str, service: str, priority: str, explicit: str = "") -> str:
    if explicit in {"lite", "standard", "heavy"}:
        return explicit
    text = f"{request_text} {service} {priority}".lower()
    heavy_terms = ("deploy", "payment", "stripe", "checkout", "production", "backend", "database", "oauth", "facebook", "meta", "live posting", "publish")
    standard_terms = ("route", "404", "site", "homepage", "about", "image", "frontend", "social", "connect", "client", "support")
    if priority in {"urgent", "high"} or any(term in text for term in heavy_terms):
        return "heavy"
    if any(term in text for term in standard_terms):
        return "standard"
    return "lite"


def _admin_queue_commands(root: Path, payload: dict[str, Any]) -> list[str]:
    mode = str(payload.get("proof_mode") or "lite")
    client_id = shlex.quote(str(payload.get("client_id") or root.name))
    service = shlex.quote(str(payload.get("service") or "codee-support"))
    request = shlex.quote(str(payload.get("request") or "Review this request")[:180])
    commands = [
        "python3 tools/codee_budget_smoke.py --mode lite",
    ]
    if mode in {"standard", "heavy"}:
        commands.append("python3 tools/codee_budget_smoke.py --mode standard")
    if mode == "heavy":
        commands.append("python3 tools/codee_admin_cli_readiness.py --client codee-ai-k9 --live --json")
    if str(payload.get("service")) == "social-connect":
        commands.append(f"python3 tools/codee_cli.py social-connect . --client {client_id} --platform facebook")
        commands.append(f"python3 tools/codee_cli.py owner-support . --client {client_id} --service social-connect --request {request} --write --force")
    else:
        commands.append(f"python3 tools/codee_cli.py owner-dev . --client {client_id} --service {service} --request {request} --write --force")
    return commands


def _admin_queue_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee Admin Queue Request",
        "",
        f"Request ID: {payload.get('request_id')}",
        f"Created: {payload.get('created_at')}",
        f"Client: {payload.get('client_id')}",
        f"Service: {payload.get('service')}",
        f"Priority: {payload.get('priority')}",
        f"Proof mode: {payload.get('proof_mode')}",
        "",
        "## Request",
        "",
        str(payload.get("request") or ""),
        "",
        "## Decision",
        "",
        str(payload.get("decision_reason") or ""),
        "",
        "## Commands",
        "",
    ]
    for command in payload.get("commands") or []:
        lines.append(f"```bash\n{command}\n```")
    return "\n".join(lines) + "\n"


def command_admin_queue(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    session = _session_payload(root)
    client_id = _slugify(str(args.client or session.get("client_id") or root.name))
    request_text = str(args.request or "").strip()
    if not request_text:
        print("admin-queue requires --request \"Describe the client/admin request\"")
        return 2
    requested_service = str(args.service or "").strip()
    if requested_service:
        service = _normalize_service(requested_service)
    elif any(term in request_text.lower() for term in ("facebook", "instagram", "social", "meta", "oauth", "connect page")):
        service = "social-connect"
    else:
        service = "codee-owner-dev"
    priority = str(args.priority or "normal").strip().lower()
    proof_mode = _admin_queue_proof_mode(request_text, service, priority, str(args.proof_mode or "auto"))
    request_id = f"aq_{hashlib.sha256(f'{client_id}:{service}:{request_text}:{_now()}'.encode('utf-8')).hexdigest()[:16]}"
    payload = {
        "ok": True,
        "schema": "codee.admin-queue.request.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "request_id": request_id,
        "client_id": client_id,
        "service": service,
        "priority": priority,
        "proof_mode": proof_mode,
        "request": request_text,
        "decision_reason": f"Codee selected {proof_mode} proof based on request words, service, and priority. Lite saves credits; standard adds route checks; heavy is for backend, deploy, OAuth, payment, or urgent production work.",
        "session": session,
        "commands": [],
        "status": "queued",
        "guardrails": [
            "No passwords, OAuth tokens, card data, private keys, or .env files in queue requests.",
            "Run lite proof first unless the request touches production, payment, OAuth, deploy, or backend changes.",
            "Heavy proof can be queued, but live checkout and browser-grade scans remain explicit gated actions.",
        ],
    }
    payload["commands"] = _admin_queue_commands(root, payload)
    queue_dir = root / ".codee" / "admin-queue"
    packet_path = queue_dir / f"{request_id}.json"
    markdown_path = queue_dir / f"{request_id}.md"
    wrote = False
    if args.write:
        _write_json(packet_path, payload, force=args.force)
        _write_text(markdown_path, _admin_queue_markdown(payload), force=args.force)
        _write_report(root, "latest-admin-queue.json", payload | {"packet": str(packet_path), "markdown": str(markdown_path)})
        _append_event(root, "AdminQueueRequestCreated", {"request_id": request_id, "client_id": client_id, "proof_mode": proof_mode})
        wrote = True
    if args.run_proof:
        script = Path(__file__).resolve().parent / "codee_budget_smoke.py"
        proof_cmd = [sys.executable, str(script), "--mode", proof_mode if proof_mode != "heavy" else "standard", "--json"]
        run = subprocess.run(proof_cmd, cwd=str(root), text=True, capture_output=True, timeout=max(30, int(float(args.timeout))))
        payload["proof_run"] = {"ok": run.returncode == 0, "exit_code": run.returncode, "stdout": run.stdout[-4000:], "stderr": run.stderr[-2000:]}
        _write_report(root, "latest-admin-queue.json", payload | {"packet": str(packet_path), "markdown": str(markdown_path)})
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "packet": str(packet_path), "markdown": str(markdown_path)}, indent=2))
    else:
        print(f"Codee admin queue: ok=True id={request_id} proof_mode={proof_mode} wrote={wrote}")
        print(f"client_id={client_id}")
        print(f"service={service}")
        print("commands:")
        for command in payload["commands"]:
            print(f"- {command}")
        if wrote:
            print(f"packet={packet_path}")
            print(f"markdown={markdown_path}")
    return 0


CODEE_PUBLIC_TOOLS = [
    ("site_audit", "Free Audit", "Find the clearest issue and next useful lane."),
    ("codeeqr", "QRCodee · $49", "Host one dependable, saveable QR destination with logic."),
    ("codeeflyer", "CodeeFlyer · $99", "Create or redesign one hosted flyer with verified QR logic, up to three actions, and 30 days support."),
    ("codeeaffiliate", "Affiliate Intake", "Create tracked links for the two paid public lanes and enter weekly payout review."),
]


def _codee_local_brain_answer(message: str) -> dict[str, Any]:
    text = message.lower()
    if any(term in text for term in ("affiliate", "referral", "commission")):
        lane = "codeeaffiliate"
    elif any(term in text for term in ("flyer", "poster", "campaign", "flyer100", "flyer250", "flyer300")):
        lane = "codeeflyer"
    elif any(term in text for term in ("qr", "scan code", "hosted code")):
        lane = "codeeqr"
    else:
        lane = "site_audit"
    label = next((label for tool_id, label, _ in CODEE_PUBLIC_TOOLS if tool_id == lane), "Free Audit")
    if any(term in text for term in ("update", "upgrade", "latest version")):
        answer = "Run `codee update`. Codee checks the public release and checkpoints the installed file before replacing it."
    elif any(term in text for term in ("price", "cost", "pay", "stripe")):
        answer = f"Start with {label}, then use its hosted Codee checkout. Advice and a local preview do not count as payment or live fulfillment."
    else:
        reasons = {
            "site_audit": "It gives you a proof-first starting point before anyone pays for the wrong tool.",
            "codeeqr": "It keeps one scan destination dependable and lets you change the logic without reprinting the code.",
            "codeeflyer": "It can create from your prompt, redesign a reference, or use both, then host up to three actions behind a verified QRCodee.",
            "codeeaffiliate": "Codee collects the referral request inside chat, creates tracked links for QRCodee and CodeeFlyer, and puts verified sales into weekly payout review.",
        }
        answer = f"I’d start with {label}. {reasons.get(lane, reasons['site_audit'])} Next, run `codee exec \"describe the campaign result you need\"`; Codee will prepare a guarded local task without pretending it is paid or live."
    return {
        "ok": True,
        "schema": "codee.cli.brain.v1",
        "answer": answer,
        "brain_mode": "local-rules",
        "service": lane,
        "suggested_commands": ["codee tools", f'codee exec "Help me with {lane}"'],
    }


def _codee_brain_answer(
    root: Path,
    message: str,
    *,
    history: list[dict[str, str]] | None = None,
    local_only: bool = False,
    timeout: float = 20,
) -> dict[str, Any]:
    session = _session_payload(root)
    if local_only:
        return _codee_local_brain_answer(message)
    payload = {
        "message": message[:2000],
        "cli_version": VERSION,
        "install_id": str(session.get("codee_user_id") or session.get("client_id") or root.name),
        "codee_user_id": str(session.get("codee_user_id") or ""),
        "client_id": str(session.get("client_id") or root.name),
        "business": str(session.get("business") or "Codee Client"),
        "service": str(session.get("service") or "free-audit"),
        "history": list(history or [])[-4:],
    }
    result = _request_json_with_api_fallbacks(
        "POST",
        str(session.get("api_base") or CODEE_BACKEND_API_BASE),
        "/api/codee/cli/brain",
        payload,
        timeout=timeout,
        fallback_bases=[CODEE_BACKEND_API_BASE],
    )
    if result.get("ok") and str(result.get("answer") or "").strip():
        return result
    fallback = _codee_local_brain_answer(message)
    fallback["live_error"] = str(result.get("error") or f"http_{result.get('http_status') or 0}")[:180]
    return fallback


def command_ask(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    message = " ".join(str(item) for item in (args.message or [])).strip()
    if not message:
        print('Usage: codee ask "What should I use for my campaign?"')
        return 2
    result = _codee_brain_answer(root, message, local_only=bool(args.local_only), timeout=float(args.timeout))
    if args.json:
        print(json.dumps(result, indent=2))
    else:
        print(str(result.get("answer") or "Codee could not answer that yet."))
        print(f"brain={result.get('brain_mode')} tool={result.get('service')}")
    return 0 if result.get("ok") else 1


def command_tools(args: argparse.Namespace) -> int:
    payload = {
        "ok": True,
        "schema": "codee.simple-tools.v1",
        "tools": [
            {"id": tool_id, "name": label, "purpose": purpose}
            for tool_id, label, purpose in CODEE_PUBLIC_TOOLS
        ],
        "private_note": "MiniCodeeSite stays in the private audit/owner-review lane.",
    }
    if args.json:
        print(json.dumps(payload, indent=2))
    else:
        print("Codee tools")
        for tool_id, label, purpose in CODEE_PUBLIC_TOOLS:
            print(f"- {label} ({tool_id}): {purpose}")
        print("Private audit lane: MiniCodeeSite is not in the normal public menu.")
    return 0


def command_catalog(args: argparse.Namespace) -> int:
    result = _curl_fetch("GET", str(args.url or CODEE_PUBLIC_CATALOG_URL), timeout=float(args.timeout))
    try:
        payload = json.loads(str(result.get("body") or "")) if result.get("ok") else {}
    except json.JSONDecodeError:
        payload = {}
    offers = payload.get("offers") if isinstance(payload.get("offers"), list) else []
    ok = bool(result.get("ok") and payload.get("schema") == "codee.public-catalog.v2" and len(offers) == 4)
    response = {
        "ok": ok,
        "schema": "codee.cli-catalog.v1",
        "catalog_version": payload.get("version") or "",
        "offers": offers,
        "url": str(args.url or CODEE_PUBLIC_CATALOG_URL),
        "http_status": result.get("status"),
        "error": "" if ok else str(result.get("error") or "invalid_public_catalog"),
    }
    if args.json:
        print(json.dumps(response, indent=2))
    elif ok:
        print(f"Codee public offers · {response['catalog_version']}")
        for row in offers:
            price = "Free" if not int(row.get("price_cents") or 0) else f"${int(row['price_cents']) // 100}"
            print(f"- {row.get('label')}: {price} · {row.get('intake_url')}")
    else:
        print(f"Codee catalog unavailable: {response['error']}")
    return 0 if ok else 1


def command_prompt(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    session = _session_payload(root)
    color, emoji = _codee_terminal_style(args)
    _print_codee_logo_mark(color=color, emoji=emoji)
    print(_codee_ansi(f"Codee CLI · {root.name} · {session.get('service')}", "1", color))
    print("Ask Codee anything · /task · /tools · /update · /exit")
    conversation: list[dict[str, str]] = []
    while True:
        try:
            line = input("codee> ").strip()
        except (EOFError, KeyboardInterrupt):
            print("")
            return 0
        if not line:
            continue
        if line.lower() in {"exit", "quit", "/exit", ":q"}:
            return 0
        if line.lower() in {"/help", "help", "?"}:
            print("/session  show this workspace identity")
            print("/tools    show the four public Codee offers")
            print("/update   check the global Codee release")
            print("/task     queue a guarded task: /task fix my flyer")
            print("/exit     leave Codee")
            print("Any other text gets a live Codee answer with a local fallback.")
            continue
        if line.lower() in {"/session", "session", "whoami", "account"}:
            command_session(argparse.Namespace(path=str(root), email="", business="", owner="", client_id="", service="", api_base="", write=False, clear=False, json=False))
            continue
        if line.lower() in {"/tools", "tools"}:
            command_tools(argparse.Namespace(json=False))
            continue
        if line.lower() in {"/update", "update"}:
            command_latest(argparse.Namespace(path=str(root), target="", url=CODEE_DOWNLOAD_URL, timeout="30", yes=False, plain=bool(args.plain), no_emoji=bool(args.no_emoji), json=False))
            continue
        if line.lower().startswith("/task "):
            request_text = line.split(" ", 1)[1].strip()
            ns = argparse.Namespace(path=str(root), client=session.get("client_id"), service=str(session.get("service") or "codee-support"), request=request_text, priority="normal", proof_mode="auto", write=True, force=True, run_proof=False, timeout="120", json=False)
            command_admin_queue(ns)
            continue
        result = _codee_brain_answer(root, line, history=conversation)
        answer = str(result.get("answer") or "Codee could not answer that yet.")
        print(answer)
        print(_codee_ansi(f"[{result.get('brain_mode')} · {result.get('service')}]", "2;96", color))
        conversation.extend([{"role": "client", "content": line[:500]}, {"role": "codee", "content": answer[:500]}])
        conversation = conversation[-4:]


def command_exec(args: argparse.Namespace) -> int:
    goal = " ".join(str(item) for item in (args.prompt or [])).strip()
    if not goal:
        print('Usage: codee exec "Describe the task"')
        return 2
    return command_agent_run(
        argparse.Namespace(
            path=args.path,
            goal=goal,
            service=args.service,
            agent="",
            mode=args.mode,
            use_model=bool(args.use_model),
            provider="",
            model="",
            endpoint="",
            model_command="",
            file="",
            find="",
            replace="",
            apply=False,
            test_cmd="",
            allow_shell=False,
            url=list(args.url or []),
            timeout=args.timeout,
            write=True,
            force=True,
            json=bool(args.json),
        )
    )


def command_resume(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    session = _session_payload(root)
    if args.json:
        print(json.dumps({"ok": True, "schema": "codee.resume.v1", "root": str(root), "session": session}, indent=2))
        return 0
    print(f"Resuming Codee: workspace={root.name} client={session.get('client_id')} service={session.get('service')}")
    if not sys.stdin.isatty():
        print("Run `codee resume` in an interactive Terminal to continue the prompt.")
        return 0
    return command_prompt(argparse.Namespace(path=str(root), plain=bool(args.plain), no_emoji=bool(args.no_emoji)))


CODEE_SIMPLE_COMMANDS = [
    ("codee", "talk to Codee's live brain"),
    ('codee ask "question"', "ask once and return"),
    ('codee exec "task"', "run one guarded task"),
    ("codee resume", "resume this workspace prompt"),
    ("codee tools", "show the four public offers"),
    ("codee doctor", "check this workspace"),
    ("codee update", "check and apply the latest release"),
]


def _print_simple_codee_help(args: argparse.Namespace) -> None:
    color, emoji = _codee_terminal_style(args)
    if bool(getattr(args, "json", False)):
        payload = {
            "ok": True,
            "schema": "codee.simple-help.v1",
            "version": VERSION,
            "commands": [{"command": command, "purpose": purpose} for command, purpose in CODEE_SIMPLE_COMMANDS],
            "folder_note": "Use codee after global setup. Inside the starter folder use ./CODEE on Mac/Linux or CODEE.bat on Windows.",
        }
        print(json.dumps(payload, indent=2))
        return
    _print_codee_logo_mark(color=color, emoji=emoji)
    badge = "🐾 " if emoji else ""
    _codee_update_box(
        [
            f"{badge}AI K9 CODEE command line",
            f"Version: {VERSION}",
            "Codex-style start: type codee from any folder.",
            "Starter fallback: ./CODEE on Mac/Linux, CODEE.bat on Windows.",
        ],
        color=color,
    )
    print("")
    for command, purpose in CODEE_SIMPLE_COMMANDS:
        print(f"{_codee_ansi(command, '1;96', color):<22} {purpose}")
    print("")
    print("Setup: codee login")
    print("Everything else: codee advanced-help")


def command_start(args: argparse.Namespace) -> int:
    _print_simple_codee_help(args)
    return 0


def command_check(args: argparse.Namespace) -> int:
    if getattr(args, "url", None):
        scan_args = argparse.Namespace(
            path=args.path,
            url=args.url,
            expected=args.expected,
            timeout=args.timeout,
            json=args.json,
        )
        return command_scan(scan_args)
    doctor_args = argparse.Namespace(
        path=args.path,
        timeout=args.timeout,
        local_only=bool(getattr(args, "local_only", False)),
        json=args.json,
    )
    return command_doctor(doctor_args)


def _codee_app_report_status(root: Path, report_name: str) -> dict[str, Any]:
    path = root / ".codee" / "reports" / report_name
    data = _read_json_if_exists(path)
    return {
        "name": report_name,
        "exists": path.exists(),
        "ok": bool(data.get("ok")) if data else False,
        "path": str(path),
        "label": report_name.replace("latest-", "").replace(".json", "").replace("-", " ").title(),
    }


def _codee_app_dashboard_html(payload: dict[str, Any]) -> str:
    esc = html.escape
    business = esc(str(payload.get("business") or "Codee Client"))
    owner = esc(str(payload.get("owner") or "Business Owner"))
    service = esc(str(payload.get("service") or "codee-support"))
    workspace = esc(str(payload.get("workspace_id") or "local-workspace"))
    version = esc(str(payload.get("cli_version") or VERSION))
    commands = payload.get("commands") if isinstance(payload.get("commands"), list) else []
    reports = payload.get("reports") if isinstance(payload.get("reports"), list) else []
    command_cards = "\n".join(
        f"""
        <article class="command-card">
          <span>{esc(str(item.get('label') or 'Command'))}</span>
          <code>{esc(str(item.get('command') or 'CODEE start'))}</code>
          <button data-copy="{esc(str(item.get('command') or ''), quote=True)}">Copy</button>
        </article>"""
        for item in commands
    )
    proof_rows = "\n".join(
        f"""
        <li class="proof {'pass' if item.get('ok') else 'pending'}">
          <strong>{esc(str(item.get('label') or item.get('name') or 'Proof'))}</strong>
          <span>{'PASS' if item.get('ok') else 'Pending' if item.get('exists') else 'Not created yet'}</span>
        </li>"""
        for item in reports
    )
    return f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Codee Business Dashboard</title>
  <style>
    :root {{
      color-scheme: light;
      --bg:#f4f7fb; --panel:#ffffff; --ink:#111827; --muted:#5f6f84;
      --line:#dbe3ef; --blue:#0756d8; --green:#087f5b; --gold:#a66a00; --dark:#0d1726;
    }}
    * {{ box-sizing:border-box; }}
    body {{ margin:0; font-family:Avenir Next, SF Pro Display, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color:var(--ink); background:var(--bg); }}
    .app {{ min-height:100vh; display:grid; grid-template-columns:260px minmax(0,1fr); }}
    aside {{ background:var(--dark); color:white; padding:24px; }}
    aside h1 {{ margin:0; font-size:1.35rem; letter-spacing:-.02em; }}
    aside p {{ color:#afbdce; line-height:1.5; }}
    nav {{ display:grid; gap:10px; margin-top:24px; }}
    nav a {{ color:white; text-decoration:none; padding:11px 12px; border:1px solid rgba(255,255,255,.12); border-radius:10px; background:rgba(255,255,255,.06); font-weight:800; }}
    main {{ padding:24px; }}
    .topbar {{ display:flex; justify-content:space-between; gap:16px; align-items:flex-start; margin-bottom:18px; }}
    .title h2 {{ margin:0; font-size:clamp(2rem,5vw,4.5rem); line-height:.92; letter-spacing:-.055em; }}
    .title p {{ margin:10px 0 0; color:var(--muted); }}
    .badge {{ display:inline-flex; border:1px solid var(--line); border-radius:999px; padding:8px 12px; background:white; color:var(--blue); font-weight:900; }}
    .grid {{ display:grid; grid-template-columns:repeat(12,1fr); gap:14px; }}
    section {{ background:var(--panel); border:1px solid var(--line); border-radius:12px; padding:18px; box-shadow:0 16px 50px rgba(15,23,42,.06); }}
    .span-8 {{ grid-column:span 8; }} .span-4 {{ grid-column:span 4; }} .span-6 {{ grid-column:span 6; }} .span-12 {{ grid-column:span 12; }}
    h3 {{ margin:0 0 12px; font-size:1.05rem; letter-spacing:-.015em; }}
    .kpis {{ display:grid; grid-template-columns:repeat(4,1fr); gap:10px; }}
    .kpi {{ border:1px solid var(--line); border-radius:10px; padding:12px; background:#f8fafc; }}
    .kpi span {{ display:block; color:var(--muted); font-size:.78rem; font-weight:800; text-transform:uppercase; }}
    .kpi strong {{ display:block; margin-top:6px; font-size:1.05rem; overflow-wrap:anywhere; }}
    .commands {{ display:grid; gap:10px; }}
    .command-card {{ display:grid; grid-template-columns:140px minmax(0,1fr) auto; gap:10px; align-items:center; border:1px solid var(--line); border-radius:10px; padding:10px; background:#f8fafc; }}
    .command-card span {{ font-weight:900; color:#26364c; }}
    code {{ display:block; color:#e8fbff; background:#07131f; border-radius:8px; padding:9px; white-space:nowrap; overflow:auto; }}
    button,.button {{ border:0; border-radius:9px; padding:10px 12px; background:var(--blue); color:white; font-weight:900; text-decoration:none; cursor:pointer; }}
    .button.secondary {{ background:#edf3fb; color:var(--ink); border:1px solid var(--line); }}
    .actions {{ display:flex; flex-wrap:wrap; gap:10px; }}
    .proof-list {{ display:grid; gap:8px; padding:0; margin:0; list-style:none; }}
    .proof {{ display:flex; justify-content:space-between; gap:12px; border:1px solid var(--line); border-radius:10px; padding:10px; background:#f8fafc; }}
    .proof span {{ color:var(--gold); font-weight:900; }} .proof.pass span {{ color:var(--green); }}
    .gate {{ display:grid; gap:8px; color:var(--muted); line-height:1.55; }}
    .gate strong {{ color:var(--ink); }}
    @media (max-width:900px) {{ .app {{ grid-template-columns:1fr; }} aside {{ padding:18px; }} .topbar {{ flex-direction:column; }} .span-8,.span-4,.span-6 {{ grid-column:span 12; }} .kpis {{ grid-template-columns:1fr 1fr; }} .command-card {{ grid-template-columns:1fr; }} }}
  </style>
</head>
<body>
  <div class="app">
    <aside>
      <h1>Codee Business Dashboard</h1>
      <p>Local command center for intake, idea-to-service, proof, and support. Hosted deploy, Stripe, and delivery rooms stay owner or paid-gated.</p>
      <nav>
        <a href="https://codee.chat/" target="_blank" rel="noreferrer">Open Codee.chat</a>
        <a href="https://clients.codee.chat/codee-video-sesh.html" target="_blank" rel="noreferrer">CODEE_VIDEO_SESH</a>
        <a href="https://clients.codee.chat/codee-delivery.html" target="_blank" rel="noreferrer">Delivery Room</a>
      </nav>
    </aside>
    <main>
      <div class="topbar">
        <div class="title">
          <span class="badge">Local-first business workspace</span>
          <h2>{business}</h2>
          <p>Owner: {owner} | Workspace: {workspace} | Service: {service}</p>
        </div>
        <span class="badge">Codee {version}</span>
      </div>
      <div class="grid">
        <section class="span-12">
          <div class="kpis">
            <div class="kpi"><span>Next sale lane</span><strong>{service}</strong></div>
            <div class="kpi"><span>Local dashboard</span><strong>Ready</strong></div>
            <div class="kpi"><span>Secrets stored</span><strong>None</strong></div>
            <div class="kpi"><span>Cloud gates</span><strong>Paid/owner</strong></div>
          </div>
        </section>
        <section class="span-8">
          <h3>Run the business</h3>
          <div class="commands">{command_cards}</div>
        </section>
        <section class="span-4">
          <h3>Proof status</h3>
          <ul class="proof-list">{proof_rows}</ul>
        </section>
        <section class="span-6">
          <h3>Fast routes</h3>
          <div class="actions">
            <a class="button" href="https://clients.codee.chat/codee-chat.html?service=codeeqr&autostart=1" target="_blank" rel="noreferrer">QRCodee Intake</a>
            <a class="button secondary" href="https://clients.codee.chat/free-audit/" target="_blank" rel="noreferrer">Free Audit</a>
            <a class="button secondary" href="https://clients.codee.chat/codee-affiliate.html" target="_blank" rel="noreferrer">Affiliate Lane</a>
          </div>
        </section>
        <section class="span-6">
          <h3>Honest gates</h3>
          <div class="gate">
            <div><strong>Free/local:</strong> intake packets, idea previews, route checks, support request files.</div>
            <div><strong>Paid/cloud:</strong> live hosting, Stripe checkout, delivery room activation, backend services, white-label support.</div>
            <div><strong>Owner-only:</strong> deploy credentials, Stripe secrets, OAuth tokens, admin controls.</div>
          </div>
        </section>
      </div>
    </main>
  </div>
  <script>
    document.querySelectorAll("[data-copy]").forEach((button) => {{
      button.addEventListener("click", async () => {{
        const value = button.getAttribute("data-copy") || "";
        try {{ await navigator.clipboard.writeText(value); button.textContent = "Copied"; }}
        catch (error) {{ button.textContent = "Copy failed"; }}
        setTimeout(() => button.textContent = "Copy", 1200);
      }});
    }});
  </script>
</body>
</html>
"""


def command_dashboard(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 {}
    session = _session_payload(root)
    business = str(args.business or manifest.get("business") or session.get("business") or root.name or "Codee Client").strip()
    owner = str(args.owner or manifest.get("owner") or session.get("owner") or "Business Owner").strip()
    service = _normalize_service(str(args.service or manifest.get("service") or session.get("service") or "codeeqr"))
    commands = [
        {"label": "Start", "command": "CODEE start"},
        {"label": "Update", "command": "CODEE update"},
        {"label": "Login", "command": "CODEE login"},
        {"label": "Intake", "command": f'CODEE intake . --service {service} --business "{business}" --target-url https://example.com --dry-run'},
        {"label": "Idea", "command": 'CODEE idea . --title "First service lane" --idea "Turn this client request into a hosted service preview" --write'},
        {"label": "Check", "command": "CODEE check . --url https://example.com"},
        {"label": "Help", "command": 'CODEE help-me "Fix my flyer link"'},
    ]
    payload = {
        "ok": True,
        "schema": "codee.business-dashboard.v1",
        "created_at": _now(),
        "cli_version": VERSION,
        "root": str(root),
        "business": business,
        "owner": owner,
        "service": service,
        "workspace_id": str(manifest.get("client_id") or session.get("client_id") or root.name),
        "commands": commands,
        "reports": [
            _codee_app_report_status(root, "latest-login.json"),
            _codee_app_report_status(root, "latest-client-intake.json"),
            _codee_app_report_status(root, "latest-service-seed.json"),
            _codee_app_report_status(root, "latest-route-scan.json"),
            _codee_app_report_status(root, "latest-support-request.json"),
        ],
    }
    dashboard_path = root / "CODEE_DASHBOARD.html"
    dashboard_html = _codee_app_dashboard_html(payload)
    dashboard_path.write_text(dashboard_html, encoding="utf-8")
    legacy_path = root / "CODEE_APP.html"
    legacy_path.write_text(dashboard_html, encoding="utf-8")
    report_path = _write_report(root, "latest-business-dashboard.json", payload | {"dashboard": str(dashboard_path)})
    _write_report(root, "latest-business-app.json", payload | {"dashboard": str(dashboard_path), "legacy_report": True})
    if args.open:
        webbrowser.open(dashboard_path.as_uri())
    if args.json:
        print(json.dumps(payload | {"dashboard": str(dashboard_path), "legacy_dashboard": str(legacy_path), "report": str(report_path)}, indent=2))
    else:
        print(f"Codee dashboard: ok=True dashboard={dashboard_path}")
        print(f"business={business} service={service}")
        print("open the dashboard file or run with --open")
    return 0


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")
    latest_codex_parity = _read_json_if_exists(root / ".codee" / "codex-parity.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("codex-parity", "Codex parity sync", bool(latest_codex_parity.get("codex", {}).get("version") if isinstance(latest_codex_parity.get("codex"), dict) else False), "Codex version and Codee parity can be synced with `codee codex-sync --write --force`.")
    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": "model-bridge", "purpose": "Configure local-rules, BYO model command, or OpenAI-compatible endpoint metadata without storing model secrets."},
        {"command": "agent-run", "purpose": "Run a guarded local agent loop: inspect, plan, optional checkpointed edit, optional model command, route checks, and report."},
        {"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, CodeeFlyer, CodeeCard, or MiniCodeeSite 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 {"model-bridge", "model", "byo-model"}:
        return [
            f"Run `python3 codee.py agent-run {root} --goal \"Improve this workspace and identify the next customer-safe edit\" --write --force` to start the guarded local loop.",
            "Set `CODEE_MODEL_COMMAND` only if you want a bring-your-own local model command; Codee will not store the key or command output as a secret.",
            f"Run `python3 codee.py compare codex --json` to see what Codee now matches and what stays owner-gated.",
        ]
    if command in {"agent-run", "agent", "run-agent"}:
        return [
            f"Run `python3 codee.py verify {root} --service codeeqr` to turn the agent run into service proof.",
            f"Run `python3 codee.py support {root} --service codeeqr --message \"Review the latest agent-run report and tell me the next customer-safe step.\"` if the next step needs owner/backend support.",
            f"Run `python3 codee.py deploy-plan {root} --plan biz --write --force` if the agent run says hosting or checkout needs owner-gated 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 {"heel", "heal", "codee-heel", "codee-heal", "owner-dev", "admin-codee", "edit-stack", "codex-bridge", "codex"}:
        return [
            "Run `codee heel . --teacher-email teacher@example.com --write --force` to create the teacher/support packet before handoff.",
            "Run `codee checkpoint . --label before-owner-dev-edit` before changing frontend or backend files.",
            "Run `codee codex-bridge . --write --force --json` so Codex has the live URLs, file inventory, and enhancement backlog.",
            "Run `codee doctor . --local-only` after the edit packet is written.",
            "Run `codee scan . --url https://clients.codee.chat/codee-owner-cli.html` when a public page changed.",
            "If `tools/codee_cli.py` changed, sync `assets/downloads/codee-cli.py` before telling users to download.",
        ]
    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 str(getattr(args, "command", "") or "") in {
        "start", "dashboard", "app", "install", "prompt", "chat", "ask",
        "resume", "continue", "latest", "update", "self-update", "upgrade-cli",
    }:
        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):
        display_item = (
            item.replace("`python3 codee.py ", "`codee ")
            .replace("`python3 codee.py`", "`codee`")
        )
        print(f"{index}. {display_item}")


def _model_bridge_manifest(root: Path, args: argparse.Namespace) -> dict[str, Any]:
    provider = str(getattr(args, "provider", "") or os.getenv("CODEE_MODEL_PROVIDER") or "local-rules").strip()
    model = str(getattr(args, "model", "") or os.getenv("CODEE_MODEL") or os.getenv("OPENAI_MODEL") or "").strip()
    endpoint = str(getattr(args, "endpoint", "") or os.getenv("CODEE_MODEL_ENDPOINT") or "").strip()
    model_command = str(getattr(args, "model_command", "") or os.getenv("CODEE_MODEL_COMMAND") or "").strip()
    env_keys = {
        "CODEE_MODEL_PROVIDER": bool(os.getenv("CODEE_MODEL_PROVIDER")),
        "CODEE_MODEL": bool(os.getenv("CODEE_MODEL")),
        "CODEE_MODEL_ENDPOINT": bool(os.getenv("CODEE_MODEL_ENDPOINT")),
        "CODEE_MODEL_COMMAND": bool(os.getenv("CODEE_MODEL_COMMAND")),
        "CODEE_MODEL_API_KEY": bool(os.getenv("CODEE_MODEL_API_KEY")),
        "OPENAI_API_KEY": bool(os.getenv("OPENAI_API_KEY")),
    }
    return {
        "schema": "codee.model-bridge.v1",
        "ok": True,
        "created_at": _now(),
        "cli_version": VERSION,
        "root": str(root),
        "provider": provider,
        "model": model,
        "endpoint": endpoint,
        "model_command": model_command,
        "env_present": env_keys,
        "public_cli_rule": "CodeeCLI does not bundle or store model API keys. Use environment variables, a local model command, or Codee backend after payment/owner approval.",
        "supported_modes": [
            {"id": "local-rules", "description": "Deterministic Codee planner with no external model call."},
            {"id": "command", "description": "Run a local model command supplied by CODEE_MODEL_COMMAND or --model-command. The prompt is sent over stdin."},
            {"id": "openai-compatible", "description": "Run a chat-completions-compatible HTTPS endpoint. Secret keys stay in the environment or owner backend."},
        ],
        "next_commands": [
            "python3 codee.py agent-run . --goal \"Improve this workspace\" --write --force",
            "CODEE_MODEL_COMMAND='your-model-command' python3 codee.py agent-run . --goal \"Improve this workspace\" --use-model --write --force",
            "CODEE_MODEL_PROVIDER=openai-compatible CODEE_MODEL_ENDPOINT='https://api.openai.com/v1/chat/completions' CODEE_MODEL_API_KEY='env-only' python3 codee.py agent-run . --goal \"Improve this workspace\" --use-model --write --force",
            "python3 codee.py compare codex",
        ],
    }


def _model_bridge_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee Model Bridge",
        "",
        f"Provider: {payload.get('provider')}",
        f"Model: {payload.get('model') or 'not configured'}",
        f"Endpoint: {payload.get('endpoint') or 'not configured'}",
        "",
        "## Rule",
        "",
        str(payload.get("public_cli_rule") or ""),
        "",
        "## Supported Modes",
        "",
    ]
    for item in payload.get("supported_modes") or []:
        lines.append(f"- {item.get('id')}: {item.get('description')}")
    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_model_bridge(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    root.mkdir(parents=True, exist_ok=True)
    payload = _model_bridge_manifest(root, args)
    wrote = False
    if args.write:
        wrote = _write_json(root / ".codee" / "model-bridge.json", payload, force=args.force)
        _write_text(root / ".codee" / "MODEL_BRIDGE.md", _model_bridge_markdown(payload), force=args.force)
        _append_event(root, "ModelBridgeConfigured", {"provider": payload.get("provider"), "model": payload.get("model"), "wrote": wrote})
    report_path = _write_report(root, "latest-model-bridge.json", payload | {"wrote": wrote})
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "report": str(report_path)}, indent=2))
    else:
        print("Codee model bridge")
        print(f"provider={payload.get('provider')}")
        print(f"model={payload.get('model') or 'not-configured'}")
        print(f"model_command={'configured' if payload.get('model_command') else 'not-configured'}")
        print("keys_stored=false")
        print(f"report={report_path}")
    return 0


def _agent_run_id(goal: str, root: Path) -> str:
    digest = hashlib.sha256(f"{root}:{goal}:{_now()}".encode("utf-8")).hexdigest()[:16]
    return f"car_{digest}"


def _agent_run_agent_for_goal(goal: str, service: str) -> str:
    lowered = goal.lower()
    if any(term in lowered for term in ("deploy", "hosting", "firebase", "cloud run", "domain")):
        return "launch"
    if any(term in lowered for term in ("bug", "broken", "404", "fail", "test", "scan", "audit")):
        return "auditor"
    if any(term in lowered for term in ("stripe", "checkout", "income", "price", "product", "invoice")):
        return "business"
    if any(term in lowered for term in ("support", "complaint", "refund", "customer")):
        return "support"
    if service and service not in {"codee-support", "codee-cli"}:
        return "builder"
    return "operator"


def _agent_run_prompt(root: Path, goal: str, payload: dict[str, Any]) -> str:
    inventory = payload.get("folder_inventory") if isinstance(payload.get("folder_inventory"), dict) else {}
    report_names = ", ".join(str(item.get("name")) for item in payload.get("recent_reports") or [])
    return "\n".join(
        [
            "You are CodeeCLI, a guarded business-delivery agent.",
            "Return concise next steps only. Do not request secrets. Do not claim live deploy unless proof exists.",
            f"Workspace: {root}",
            f"Goal: {goal}",
            f"Service: {payload.get('service')}",
            f"Agent: {payload.get('agent')}",
            f"Has index.html: {inventory.get('has_index')}",
            f"File counts: {inventory.get('counts')}",
            f"Recent reports: {report_names or 'none'}",
            "Required output: plan, risks, proof commands, and whether a paid/owner-gated action is needed.",
            "",
        ]
    )


def _agent_run_recent_reports(root: Path) -> list[dict[str, Any]]:
    report_dir = root / ".codee" / "reports"
    if not report_dir.exists():
        return []
    reports: list[dict[str, Any]] = []
    for path in sorted(report_dir.glob("latest-*.json"), key=lambda item: item.stat().st_mtime if item.exists() else 0, reverse=True)[:8]:
        data = _read_json_if_exists(path)
        reports.append({"name": path.name, "ok": bool(data.get("ok")), "path": str(path)})
    return reports


def _agent_run_rule_plan(payload: dict[str, Any]) -> list[str]:
    goal = str(payload.get("goal") or "").lower()
    service = str(payload.get("service") or "codee-support")
    steps = [
        "Inspect workspace identity, files, sensitive-file risk, and latest proof reports.",
        "Create a checkpoint before changing any file.",
    ]
    if any(term in goal for term in ("stripe", "checkout", "income", "invoice", "product")):
        steps.append("Prepare an owner-gated Stripe or income-lane request packet instead of storing Stripe secrets locally.")
    if any(term in goal for term in ("deploy", "hosting", "domain")):
        steps.append("Write a deploy plan and keep live deploy behind owner/backend credential gates.")
    if any(term in goal for term in ("edit", "fix", "change", "update")):
        steps.append("Use `codee edit` for exact replacements, then run the requested test command.")
    if any(term in goal for term in ("scan", "404", "visual", "page")):
        steps.append("Run `codee scan` or `codee browser-scan` against the route that matters.")
    steps.extend(
        [
            f"Run `python3 codee.py verify . --service {service}` to refresh service proof.",
            "Save the agent-run report under `.codee/reports/latest-agent-run.json` for customer support history.",
        ]
    )
    return steps


def _split_user_command(command: str) -> list[str]:
    """Split a command without breaking an unquoted executable path containing spaces."""
    parts = shlex.split(str(command or "").strip())
    if not parts or Path(parts[0]).exists():
        return parts
    # Friendly recovery for commands built from sys.executable or copied from
    # Finder paths such as `/Users/name/Library/Mobile Documents/.../python`.
    # No shell is used; only an existing file can become the executable.
    for end in range(2, len(parts) + 1):
        candidate = " ".join(parts[:end])
        if Path(candidate).is_file():
            return [candidate, *parts[end:]]
    return parts


def _run_agent_model_command(command: str, prompt: str, timeout: float) -> dict[str, Any]:
    if not command.strip():
        return {"ok": False, "skipped": True, "error": "model_command_not_configured"}
    try:
        proc = subprocess.run(_split_user_command(command), input=prompt, text=True, capture_output=True, timeout=timeout)
        return {
            "ok": proc.returncode == 0,
            "skipped": False,
            "command": command,
            "returncode": proc.returncode,
            "stdout": proc.stdout[-6000:],
            "stderr": proc.stderr[-2000:],
        }
    except Exception as exc:
        return {"ok": False, "skipped": False, "command": command, "error": f"{type(exc).__name__}: {str(exc)[:240]}"}


def _normalize_chat_completions_endpoint(endpoint: str) -> str:
    url = str(endpoint or "").strip().rstrip("/")
    if not url:
        return ""
    if url.endswith("/chat/completions"):
        return url
    if url.endswith("/v1"):
        return f"{url}/chat/completions"
    return f"{url}/v1/chat/completions"


def _run_agent_model_endpoint(bridge: dict[str, Any], prompt: str, timeout: float) -> dict[str, Any]:
    endpoint = _normalize_chat_completions_endpoint(str(bridge.get("endpoint") or os.getenv("CODEE_MODEL_ENDPOINT") or ""))
    model = str(bridge.get("model") or os.getenv("CODEE_MODEL") or os.getenv("OPENAI_MODEL") or "").strip()
    api_key = str(os.getenv("CODEE_MODEL_API_KEY") or os.getenv("OPENAI_API_KEY") or "").strip()
    if not endpoint:
        return {"ok": False, "skipped": True, "provider": "openai-compatible", "error": "model_endpoint_not_configured"}
    if not model:
        return {"ok": False, "skipped": True, "provider": "openai-compatible", "endpoint": endpoint, "error": "model_not_configured"}
    body = {
        "model": model,
        "messages": [
            {"role": "system", "content": "You are CodeeCLI, a guarded local business-delivery assistant. Be concise. Do not request secrets."},
            {"role": "user", "content": prompt},
        ],
        "temperature": 0.2,
        "max_tokens": 900,
    }
    headers = {
        "Content-Type": "application/json",
        "User-Agent": f"CodeeCLI/{VERSION}-model-bridge",
    }
    if api_key:
        headers["Authorization"] = f"Bearer {api_key}"
    req = urllib.request.Request(endpoint, data=json.dumps(body).encode("utf-8"), headers=headers, method="POST")
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            raw = resp.read().decode("utf-8", errors="replace")
        parsed = json.loads(raw or "{}")
        choices = parsed.get("choices") if isinstance(parsed.get("choices"), list) else []
        first = choices[0] if choices and isinstance(choices[0], dict) else {}
        message = first.get("message") if isinstance(first.get("message"), dict) else {}
        content = str(message.get("content") or first.get("text") or "").strip()
        return {
            "ok": bool(content),
            "skipped": False,
            "provider": "openai-compatible",
            "endpoint": endpoint,
            "model": model,
            "api_key_present": bool(api_key),
            "stdout": content[:6000],
            "usage": parsed.get("usage") if isinstance(parsed.get("usage"), dict) else {},
        }
    except urllib.error.HTTPError as exc:
        error_body = exc.read().decode("utf-8", errors="replace")[:1200]
        return {"ok": False, "skipped": False, "provider": "openai-compatible", "endpoint": endpoint, "model": model, "status": int(exc.code), "api_key_present": bool(api_key), "error": error_body}
    except Exception as exc:
        return {"ok": False, "skipped": False, "provider": "openai-compatible", "endpoint": endpoint, "model": model, "api_key_present": bool(api_key), "error": f"{type(exc).__name__}: {str(exc)[:240]}"}


def _agent_run_markdown(payload: dict[str, Any]) -> str:
    lines = [
        "# Codee Agent Run",
        "",
        f"Status: {'PASS' if payload.get('ok') else 'NEEDS REVIEW'}",
        f"Goal: {payload.get('goal')}",
        f"Agent: {payload.get('agent')}",
        f"Service: {payload.get('service')}",
        "",
        "## Plan",
        "",
    ]
    for step in payload.get("plan") or []:
        lines.append(f"- {step}")
    if payload.get("model_result"):
        model_result = payload["model_result"]
        lines.extend(["", "## Model Result", "", "```text", str(model_result.get("stdout") or model_result.get("error") or "")[:6000], "```"])
    if payload.get("edit_result"):
        lines.extend(["", "## Edit Result", "", f"- ok: {payload['edit_result'].get('ok')}", f"- report: {payload['edit_result'].get('report')}"])
    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_agent_run(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    root.mkdir(parents=True, exist_ok=True)
    goal = str(args.goal or "").strip()
    if not goal:
        print("--goal is required for agent-run.")
        return 2
    manifest = _load_manifest(root)
    service = _normalize_service(str(args.service or manifest.get("service") or "codee-support"))
    agent = str(args.agent or "").strip() or _agent_run_agent_for_goal(goal, service)
    run_id = _agent_run_id(goal, root)
    bridge = _read_json_if_exists(root / ".codee" / "model-bridge.json")
    if not bridge:
        bridge = _model_bridge_manifest(root, argparse.Namespace(provider="", model="", endpoint="", model_command="", write=False, force=False))
    for key in ("provider", "model", "endpoint", "model_command"):
        value = str(getattr(args, key, "") or "").strip()
        if value:
            bridge[key] = value
    payload: dict[str, Any] = {
        "schema": "codee.agent-run.v1",
        "ok": True,
        "created_at": _now(),
        "cli_version": VERSION,
        "run_id": run_id,
        "root": str(root),
        "goal": goal,
        "service": service,
        "agent": agent,
        "mode": str(args.mode or "suggest"),
        "folder_inventory": _folder_inventory(root),
        "recent_reports": _agent_run_recent_reports(root),
        "model_bridge": {
            "provider": bridge.get("provider") or "local-rules",
            "model": bridge.get("model") or "",
            "endpoint_configured": bool(bridge.get("endpoint") or os.getenv("CODEE_MODEL_ENDPOINT")),
            "model_command_configured": bool(bridge.get("model_command") or os.getenv("CODEE_MODEL_COMMAND")),
            "api_key_present": bool(os.getenv("CODEE_MODEL_API_KEY") or os.getenv("OPENAI_API_KEY")),
            "keys_stored": False,
        },
        "plan": [],
        "model_result": {},
        "edit_result": {},
        "test_result": {},
        "route_results": [],
        "guardrails": [
            "No model, Stripe, OAuth, Firebase, or Google secret is stored by agent-run.",
            "File writes require --apply and use checkpointed exact replacement only.",
            "Shell/model execution requires explicit --use-model or --allow-shell flags.",
            "Live deploy and paid activation remain owner/backend gated unless the customer provides their own local command.",
        ],
    }
    payload["plan"] = _agent_run_rule_plan(payload)
    prompt = _agent_run_prompt(root, goal, payload)
    payload["prompt_preview"] = prompt[:2000]

    if bool(args.use_model):
        provider = str(bridge.get("provider") or os.getenv("CODEE_MODEL_PROVIDER") or "local-rules").strip().lower()
        command = str(args.model_command or bridge.get("model_command") or os.getenv("CODEE_MODEL_COMMAND") or "").strip()
        endpoint = str(bridge.get("endpoint") or os.getenv("CODEE_MODEL_ENDPOINT") or "").strip()
        if command:
            payload["model_result"] = _run_agent_model_command(command, prompt, float(args.timeout))
        elif provider in {"openai-compatible", "chat-completions", "http"} or endpoint:
            payload["model_result"] = _run_agent_model_endpoint(bridge, prompt, float(args.timeout))
        else:
            payload["model_result"] = {"ok": False, "skipped": True, "error": "model_command_or_endpoint_not_configured"}
        if not payload["model_result"].get("ok") and not payload["model_result"].get("skipped"):
            payload["ok"] = False

    if args.file and args.find and args.replace:
        edit_ns = argparse.Namespace(
            path=str(root),
            request=goal,
            file=args.file,
            find=args.find,
            replace=args.replace,
            apply=bool(args.apply),
            test_cmd=str(args.test_cmd or ""),
            json=True,
        )
        target = Path(args.file).expanduser()
        if not target.is_absolute():
            target = root / target
        if not target.exists() or target.is_dir() or _is_sensitive_path(target):
            payload["edit_result"] = {"ok": False, "error": "edit_target_missing_or_sensitive", "file": str(target)}
            payload["ok"] = False
        else:
            original_stdout = sys.stdout
            from io import StringIO

            capture = StringIO()
            try:
                sys.stdout = capture
                edit_code = command_edit(edit_ns)
            finally:
                sys.stdout = original_stdout
            try:
                edit_payload = json.loads(capture.getvalue() or "{}")
            except Exception:
                edit_payload = {"stdout": capture.getvalue()[-2000:]}
            payload["edit_result"] = edit_payload | {"exit_code": edit_code}
            if edit_code != 0:
                payload["ok"] = False

    if args.test_cmd and not payload.get("edit_result") and bool(args.allow_shell):
        try:
            proc = subprocess.run(_split_user_command(str(args.test_cmd)), cwd=root, text=True, capture_output=True, timeout=float(args.timeout))
            payload["test_result"] = {
                "ok": proc.returncode == 0,
                "command": str(args.test_cmd),
                "returncode": proc.returncode,
                "stdout": proc.stdout[-2000:],
                "stderr": proc.stderr[-2000:],
            }
            if proc.returncode != 0:
                payload["ok"] = False
        except Exception as exc:
            payload["test_result"] = {"ok": False, "command": str(args.test_cmd), "error": f"{type(exc).__name__}: {str(exc)[:240]}"}
            payload["ok"] = False
    elif args.test_cmd and not payload.get("edit_result"):
        payload["test_result"] = {"ok": True, "skipped": True, "reason": "Pass --allow-shell to run a standalone test command."}

    route_urls = [str(item).strip() for item in (args.url or []) if str(item).strip()]
    for url in route_urls:
        if url.startswith(("http://", "https://")):
            payload["route_results"].append(_route_check({"name": "agent-run-url", "url": url, "expected": [200, 301, 302, 303, 307, 308]}, float(args.timeout)))
    if payload["route_results"] and not all(item.get("ok") for item in payload["route_results"]):
        payload["ok"] = False

    payload["next_commands"] = [
        f"python3 codee.py verify {shlex.quote(str(root))} --service {shlex.quote(service)}",
        f"python3 codee.py support {shlex.quote(str(root))} --service {shlex.quote(service)} --message {shlex.quote('Review the latest agent-run report and advise the next customer-safe step.')}",
        f"python3 codee.py compare codex --json",
    ]
    run_dir = root / ".codee" / "agent-runs"
    wrote = False
    if args.write:
        wrote = _write_json(run_dir / f"{run_id}.json", payload, force=args.force)
        _write_text(run_dir / f"{run_id}.md", _agent_run_markdown(payload), force=args.force)
        _append_event(root, "AgentRun", {"run_id": run_id, "ok": bool(payload.get("ok")), "agent": agent, "service": service})
    report_path = _write_report(root, "latest-agent-run.json", payload | {"wrote": wrote})
    _write_text(root / ".codee" / "AGENT_RUN.md", _agent_run_markdown(payload), force=True)
    if args.json:
        print(json.dumps(payload | {"wrote": wrote, "report": str(report_path)}, indent=2))
    else:
        print(f"Codee agent-run: ok={payload['ok']} run_id={run_id} agent={agent} service={service}")
        print(f"model={'used' if payload.get('model_result') else 'local-rules'}")
        if payload.get("edit_result"):
            print(f"edit_ok={payload['edit_result'].get('ok')}")
        if payload.get("route_results"):
            print(f"routes={len(payload['route_results'])} passed={sum(1 for item in payload['route_results'] if item.get('ok'))}")
        print(f"report={report_path}")
    return 0 if payload.get("ok") else 1


def command_edit(args: argparse.Namespace) -> int:
    root = Path(args.path).expanduser().resolve()
    root.mkdir(parents=True, exist_ok=True)
    target = Path(args.file).expanduser()
    if not target.is_absolute():
        target = root / target
    target = target.resolve()
    request = str(getattr(args, "request", "") or "").strip()
    find_text = str(getattr(args, "find", "") or "")
    replace_text = str(getattr(args, "replace", "") or "")
    test_cmd = str(getattr(args, "test_cmd", "") or "").strip()
    apply_edit = bool(getattr(args, "apply", False))

    payload: dict[str, Any] = {
        "schema": "codee.edit.v1",
        "ok": False,
        "created_at": _now(),
        "cli_version": VERSION,
        "root": str(root),
        "request": request,
        "file": str(target),
        "applied": False,
        "changed_files": [],
        "checkpoint": {"files": []},
        "test": {"ok": True, "skipped": True, "command": test_cmd},
        "rule": "Codee edit only changes local files after a checkpoint and optional test command.",
    }
    if not target.exists() or target.is_dir():
        payload["error"] = "target_file_not_found"
        report_path = _write_report(root, "latest-edit.json", payload)
        if args.json:
            print(json.dumps(payload | {"report": str(report_path)}, indent=2))
        else:
            print(f"Codee edit failed: target file not found: {target}")
            print(f"report={report_path}")
        return 1
    if not find_text:
        payload["error"] = "missing_find_text"
        report_path = _write_report(root, "latest-edit.json", payload)
        if args.json:
            print(json.dumps(payload | {"report": str(report_path)}, indent=2))
        else:
            print("Codee edit failed: --find is required.")
            print(f"report={report_path}")
        return 2

    original = target.read_text(encoding="utf-8", errors="replace")
    if find_text not in original:
        payload["error"] = "find_text_not_found"
        payload["preview"] = {"would_apply": False}
        report_path = _write_report(root, "latest-edit.json", payload)
        if args.json:
            print(json.dumps(payload | {"report": str(report_path)}, indent=2))
        else:
            print("Codee edit failed: find text was not found.")
            print(f"report={report_path}")
        return 1

    updated = original.replace(find_text, replace_text, 1)
    payload["preview"] = {
        "would_apply": True,
        "replacements": 1,
        "find_length": len(find_text),
        "replace_length": len(replace_text),
    }
    if apply_edit:
        checkpoint = _checkpoint_existing_path(target, reason="codee-edit")
        if checkpoint:
            payload["checkpoint"]["files"].append({"source": str(target), "checkpoint": checkpoint})
        target.write_text(updated, encoding="utf-8")
        payload["applied"] = True
        payload["changed_files"] = [str(target)]
        _append_event(root, "LocalEditApplied", {"file": str(target), "request": request[:180], "checkpoint": checkpoint})

    if test_cmd:
        try:
            proc = subprocess.run(_split_user_command(test_cmd), cwd=root, text=True, capture_output=True, timeout=120)
            payload["test"] = {
                "ok": proc.returncode == 0,
                "skipped": False,
                "command": test_cmd,
                "returncode": proc.returncode,
                "stdout": proc.stdout[-2000:],
                "stderr": proc.stderr[-2000:],
            }
        except Exception as exc:
            payload["test"] = {
                "ok": False,
                "skipped": False,
                "command": test_cmd,
                "error": f"{type(exc).__name__}: {str(exc)[:240]}",
            }

    payload["ok"] = bool(payload["preview"]["would_apply"] and (not test_cmd or payload["test"].get("ok")))
    report_path = _write_report(root, "latest-edit.json", payload)
    if args.json:
        print(json.dumps(payload | {"report": str(report_path)}, indent=2))
    else:
        state = "applied" if payload["applied"] else "previewed"
        print(f"Codee edit {state}: ok={payload['ok']} file={target}")
        if payload["checkpoint"]["files"]:
            print(f"checkpoint={payload['checkpoint']['files'][0]['checkpoint']}")
        if test_cmd:
            print(f"test_ok={payload['test'].get('ok')} command={test_cmd}")
        print(f"report={report_path}")
    return 0 if payload["ok"] else 1


def _business_command_base(args: argparse.Namespace, action: str) -> tuple[Path, dict[str, Any]]:
    root = Path(getattr(args, "path", ".") or ".").expanduser().resolve()
    root.mkdir(parents=True, exist_ok=True)
    manifest = _load_manifest(root)
    business = str(getattr(args, "business", "") or manifest.get("business") or root.name or "Codee Client").strip()
    service = _normalize_service(str(getattr(args, "service", "") or manifest.get("service") or "business-suite"))
    plan = _normalize_plan_id(str(getattr(args, "plan", "") or manifest.get("plan") or "business-suite"))
    email = str(getattr(args, "email", "") or manifest.get("owner_email") or "").strip().lower()
    target_url = str(getattr(args, "target_url", "") or manifest.get("target_url") or "").strip()
    price_cents_raw = str(getattr(args, "price_cents", "") or "").strip()
    price_raw = str(getattr(args, "price", "") or "").strip()
    price_cents = 0
    if price_cents_raw:
        try:
            price_cents = int(float(price_cents_raw))
        except ValueError:
            price_cents = 0
    elif price_raw:
        try:
            price_cents = int(round(float(re.sub(r"[^0-9.]+", "", price_raw) or "0") * 100))
        except ValueError:
            price_cents = 0
    if price_cents <= 0 and plan == "business-suite":
        price_cents = 250000
    payload = {
        "schema": f"codee.{action}.v1",
        "ok": True,
        "created_at": _now(),
        "cli_version": VERSION,
        "root": str(root),
        "business": business,
        "service": service,
        "plan": plan,
        "email": email,
        "target_url": target_url,
        "price_cents": price_cents,
        "public_cli": True,
        "owner_gated": True,
        "mode": "local-proof-request",
        "delivery_room_url": _delivery_room_url(manifest | {"business": business}, service=service),
        "support_command": f"python3 codee.py support {shlex.quote(str(root))} --service {shlex.quote(service)} --message \"Please review this {action} packet.\"",
    }
    return root, payload


def _write_business_command_report(root: Path, report_name: str, payload: dict[str, Any], args: argparse.Namespace) -> int:
    report_path = _write_report(root, report_name, payload)
    if bool(getattr(args, "write", False)):
        request_dir = root / ".codee" / "business-requests"
        request_dir.mkdir(parents=True, exist_ok=True)
        request_path = request_dir / report_name
        request_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
        payload["request_path"] = str(request_path)
    payload["report"] = str(report_path)
    if bool(getattr(args, "json", False)):
        print(json.dumps(payload, indent=2))
    else:
        print(f"Codee {payload.get('action', 'business')} request: ok={payload.get('ok')} owner_gated={payload.get('owner_gated')}")
        print(f"business={payload.get('business')} service={payload.get('service')} plan={payload.get('plan')}")
        if payload.get("deploy_status"):
            print(f"deploy_status={payload['deploy_status'].get('state')}")
        if payload.get("checkout"):
            print(f"checkout={payload['checkout'].get('status')}")
        if payload.get("product_request"):
            print(f"product_request={payload['product_request'].get('status')}")
        print(f"report={report_path}")
    return 0 if payload.get("ok") else 1


def command_deploy_plan(args: argparse.Namespace) -> int:
    root, payload = _business_command_base(args, "deploy-plan")
    payload |= {
        "action": "deploy-plan",
        "deploy_status": {
            "state": "owner_gated_plan_ready",
            "can_deploy_from_public_cli": False,
            "reason": "Public downloads do not ship Firebase, GCloud, Stripe, DNS, or storage secrets.",
            "handoff": "Use this report as the deploy request packet after payment/assets are verified.",
        },
        "proof_gates": [
            "assets collected",
            "payment or sponsored approval verified",
            "route selected",
            "environment secrets present in owner backend",
            "live smoke test captured",
        ],
        "next_commands": [
            "python3 codee.py verify . --service business-suite",
            "python3 codee.py support . --service business-suite --message \"Review my deploy plan.\"",
        ],
    }
    return _write_business_command_report(root, "latest-deploy-plan.json", payload, args)


def command_income_lane(args: argparse.Namespace) -> int:
    root, payload = _business_command_base(args, "income-lane")
    payload |= {
        "action": "income-lane",
        "checkout": {
            "status": "owner_review_required",
            "stripe_action": "create_checkout_or_invoice_after_owner_approval",
            "price_cents": payload["price_cents"],
            "payment_methods": ["card", "Apple Pay when browser/device eligible", "Klarna when enabled on Stripe account"],
        },
        "lane": {
            "offer": str(getattr(args, "offer", "") or payload["service"]),
            "fulfillment": "delivery room, proof report, client workspace, and support window",
        },
    }
    return _write_business_command_report(root, "latest-income-lane.json", payload, args)


def command_stripe_product(args: argparse.Namespace) -> int:
    root, payload = _business_command_base(args, "stripe-product")
    product_name = str(getattr(args, "name", "") or payload["business"] + " Codee Biz Bundle").strip()
    payload |= {
        "action": "stripe-product",
        "product_request": {
            "status": "owner_review_required",
            "name": product_name,
            "price_cents": payload["price_cents"],
            "currency": "usd",
            "public_cli_has_stripe_secret": False,
            "fulfillment_after_payment": ["QRCodee", "CodeeFlyer100", "CodeeFlyer250", "CodeeCard", "MiniCodeeSite/shop lane"],
        },
    }
    return _write_business_command_report(root, "latest-stripe-product-request.json", payload, args)


def command_biz_launch(args: argparse.Namespace) -> int:
    root, payload = _business_command_base(args, "biz-launch")
    payload |= {
        "action": "biz-launch",
        "deliverables": ["QRCodee", "CodeeFlyer100", "CodeeFlyer250", "CodeeCard", "MiniCodeeSite/shop lane", "shell site", "video handoff", "30-day edit room"],
        "proof_gates": [
            {"name": "payment_verified", "ok": False, "owner_gated": True},
            {"name": "client_assets_collected", "ok": bool(payload.get("target_url")), "owner_gated": False},
            {"name": "workspace_report_written", "ok": True, "owner_gated": False},
            {"name": "live_route_smoke", "ok": False, "owner_gated": True},
            {"name": "handoff_video_ready", "ok": False, "owner_gated": True},
        ],
        "customer_service": {
            "complaint_path": "support command and delivery room stay visible in the report",
            "refund_rule": "refund decisions stay tied to Stripe status, delivery proof, and owner policy",
        },
    }
    return _write_business_command_report(root, "latest-biz-launch.json", payload, args)


def command_deploy(args: argparse.Namespace) -> int:
    root, payload = _business_command_base(args, "deploy")
    payload |= {
        "action": "deploy",
        "deploy_status": {
            "state": "queued_for_owner_deploy",
            "can_deploy_from_public_cli": False,
            "forced": bool(getattr(args, "force", False)),
            "write_requested": bool(getattr(args, "write", False)),
            "message": "Public CodeeCLI prepares deploy proof. Owner backend performs live deploy after credentials and payment are verified.",
        },
    }
    return _write_business_command_report(root, "latest-deploy-request.json", payload, args)


def command_compare(args: argparse.Namespace) -> int:
    target = str(getattr(args, "target", "") or "").strip().lower() or "codex"
    payload = {
        "schema": "codee.compare.v1",
        "ok": True,
        "created_at": _now(),
        "cli_version": VERSION,
        "target": target,
        "summary": "CodeeCLI is a business-delivery agent for paid service folders, proof reports, QR/flyer/card/site lanes, and owner-gated deploy or Stripe handoff. It is not a full Codex replacement because it does not bundle a local model runtime or autonomous hosted coding agent.",
        "matches": [
            "terminal-first workflow",
            "workspace inspection",
            "checkpointed local edits",
            "proof reports",
            "guided commands",
            "guarded local agent-run loop",
            "bring-your-own model bridge",
        ],
        "codee_differentiators": [
            "business bundle planning",
            "QRCodee, CodeeFlyer100, CodeeFlyer250, CodeeCard, and MiniCodeeSite/shop delivery reports",
            "Stripe/Klarna request packets",
            "owner-gated deploy handoff",
            "client workspace and support-room path",
        ],
        "missing_for_codex_parity": [
            "no proprietary LLM/model key is bundled in the public ZIP",
            "general coding autonomy is guarded by local permissions, exact-edit operations, and optional BYO model command",
            "live deploy credentials stay owner/backend gated",
            "real Stripe webhook activation requires live checkout or invoice proof",
            "third-party OAuth/social posting remains app-approval and secret gated",
        ],
    }
    if bool(getattr(args, "json", False)):
        print(json.dumps(payload, indent=2))
    else:
        print(payload["summary"])
        print("Missing for Codex parity:")
        for item in payload["missing_for_codex_parity"]:
            print(f"- {item}")
    return 0


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 = (
        "start,ask,tools,offers,dashboard,update,login,intake,idea,check,help-me,prompt,exec,resume,session,admin-queue,explain,install,self-update,latest,registry,model-bridge,agent-run,checkpoint,edit,eval,preview,audit,test,launch,deploy-plan,income-lane,stripe-product,biz-launch,deploy,compare,saas,portal,entitlements,starter,remote,heel,owner-dev,owner-support,social-connect,codex-bridge,codex-sync,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,"
        "services,maintain,maintenance,admin-cli,service-seed,idea-to-service,veteran-mission,mission-qrcodee,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 + "}")

    start = sub.add_parser("start", aliases=["go", "menu"], help="Show the simple Codee command menu.")
    start.add_argument("path", nargs="?", default=".")
    start.add_argument("--plain", action="store_true", help="Use plain text with no color styling.")
    start.add_argument("--no-emoji", action="store_true", help="Do not print emoji in the Codee terminal mark.")
    start.add_argument("--json", action="store_true")
    start.set_defaults(func=command_start)

    dashboard = sub.add_parser("dashboard", aliases=["app", "home"], help="Create/open the local Codee business dashboard for this workspace.")
    dashboard.add_argument("path", nargs="?", default=".")
    dashboard.add_argument("--business", default="")
    dashboard.add_argument("--owner", default="")
    dashboard.add_argument("--service", default="")
    dashboard.add_argument("--open", action="store_true")
    dashboard.add_argument("--json", action="store_true")
    dashboard.set_defaults(func=command_dashboard)

    prompt = sub.add_parser("prompt", aliases=["chat"], help="Open the interactive Codee brain, like Codex.")
    prompt.add_argument("path", nargs="?", default=".")
    prompt.add_argument("--plain", action="store_true", help="Use plain text with no color styling.")
    prompt.add_argument("--no-emoji", action="store_true", help="Do not print emoji in the Codee terminal mark.")
    prompt.set_defaults(func=command_prompt)

    ask = sub.add_parser("ask", help="Ask Codee one question and return the answer.")
    ask.add_argument("message", nargs="+", help="Question for Codee.")
    ask.add_argument("--path", default=".")
    ask.add_argument("--local-only", action="store_true", help="Use the built-in logical brain without a network call.")
    ask.add_argument("--timeout", default="20")
    ask.add_argument("--json", action="store_true")
    ask.set_defaults(func=command_ask)

    tools_cmd = sub.add_parser("tools", help="Show the four public Codee offers.")
    tools_cmd.add_argument("--json", action="store_true")
    tools_cmd.set_defaults(func=command_tools)

    catalog_cmd = sub.add_parser("offers", aliases=["public-catalog"], help="Show the verified live public offer catalog.")
    catalog_cmd.add_argument("--url", default=CODEE_PUBLIC_CATALOG_URL)
    catalog_cmd.add_argument("--timeout", default="20")
    catalog_cmd.add_argument("--json", action="store_true")
    catalog_cmd.set_defaults(func=command_catalog)

    exec_cmd = sub.add_parser("exec", aliases=["run"], help="Run one guarded task, similar to `codex exec`.")
    exec_cmd.add_argument("prompt", nargs="+", help="Task request for Codee.")
    exec_cmd.add_argument("--path", default=".")
    exec_cmd.add_argument("--service", default="")
    exec_cmd.add_argument("--mode", default="suggest", choices=[str(item["id"]) for item in CODEE_PERMISSION_MODES])
    exec_cmd.add_argument("--use-model", action="store_true", help="Use the configured BYO model bridge when available.")
    exec_cmd.add_argument("--url", action="append", help="Optional live route to check. Can be repeated.")
    exec_cmd.add_argument("--timeout", default="30")
    exec_cmd.add_argument("--json", action="store_true")
    exec_cmd.set_defaults(func=command_exec)

    resume = sub.add_parser("resume", aliases=["continue"], help="Resume the interactive prompt with this folder's saved Codee session.")
    resume.add_argument("path", nargs="?", default=".")
    resume.add_argument("--plain", action="store_true")
    resume.add_argument("--no-emoji", action="store_true")
    resume.add_argument("--json", action="store_true")
    resume.set_defaults(func=command_resume)

    session = sub.add_parser("session", aliases=["config"], help="Show or save Codee login/session defaults for this folder.")
    session.add_argument("path", nargs="?", default=".")
    session.add_argument("--email", default="")
    session.add_argument("--business", default="")
    session.add_argument("--owner", default="")
    session.add_argument("--client-id", default="")
    session.add_argument("--service", default="")
    session.add_argument("--api-base", default="")
    session.add_argument("--write", action="store_true")
    session.add_argument("--clear", action="store_true")
    session.add_argument("--json", action="store_true")
    session.set_defaults(func=command_session)

    admin_queue = sub.add_parser("admin-queue", aliases=["queue", "request"], help="Queue an admin request and let Codee pick lite, standard, or heavy proof.")
    admin_queue.add_argument("path", nargs="?", default=".")
    admin_queue.add_argument("--client", default="")
    admin_queue.add_argument("--service", default="")
    admin_queue.add_argument("--request", required=True)
    admin_queue.add_argument("--priority", default="normal", choices=["low", "normal", "high", "urgent"])
    admin_queue.add_argument("--proof-mode", default="auto", choices=["auto", "lite", "standard", "heavy"])
    admin_queue.add_argument("--write", action="store_true")
    admin_queue.add_argument("--force", action="store_true")
    admin_queue.add_argument("--run-proof", action="store_true")
    admin_queue.add_argument("--timeout", default="180")
    admin_queue.add_argument("--json", action="store_true")
    admin_queue.set_defaults(func=command_admin_queue)

    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 ./CODEE, ./codee, and CODEE.bat launchers.")
    install.add_argument("--global", dest="global_command", action="store_true", help="Also write user-level `CODEE` and `codee` launchers, like Codex or Claude CLI.")
    install.add_argument("--bin-dir", default="~/.local/bin", help="User bin folder for --global.")
    install.add_argument("--plain", action="store_true", help="Use plain text with no color styling.")
    install.add_argument("--no-emoji", action="store_true", help="Do not print emoji in the Codee terminal mark.")
    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)

    latest = sub.add_parser("latest", aliases=["update"], help="Check the public CODEECLI release and ask before applying an update.")
    latest.add_argument("path", nargs="?", default=".")
    latest.add_argument("--target", default="", help="CLI file to replace. Defaults to this running file.")
    latest.add_argument("--url", default=CODEE_DOWNLOAD_URL)
    latest.add_argument("--timeout", default="30")
    latest.add_argument("--yes", action="store_true", help="Apply the update without the interactive prompt when a public release is available.")
    latest.add_argument("--plain", action="store_true", help="Use plain text with no color styling.")
    latest.add_argument("--no-emoji", action="store_true", help="Do not print emoji in update prompts.")
    latest.add_argument("--json", action="store_true")
    latest.set_defaults(func=command_latest)

    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", default="", help="Owner email. If omitted in Terminal, Codee asks for it.")
    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("--open", action="store_true", help="Open the owner CLI after saving the login.")
    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)

    model_bridge = sub.add_parser("model-bridge", aliases=["model", "byo-model"], help="Configure the safe bring-your-own model bridge without storing secrets.")
    model_bridge.add_argument("path", nargs="?", default=".")
    model_bridge.add_argument("--provider", default="", help="local-rules, command, openai-compatible, or another BYO provider label.")
    model_bridge.add_argument("--model", default="", help="Optional model name. Secrets stay in environment variables.")
    model_bridge.add_argument("--endpoint", default="", help="Optional OpenAI-compatible or local endpoint URL.")
    model_bridge.add_argument("--model-command", default="", help="Optional local command that reads the prompt from stdin.")
    model_bridge.add_argument("--write", action="store_true")
    model_bridge.add_argument("--force", action="store_true")
    model_bridge.add_argument("--json", action="store_true")
    model_bridge.set_defaults(func=command_model_bridge)

    agent_run = sub.add_parser("agent-run", aliases=["agent", "run-agent"], help="Run a guarded local Codee agent loop with optional BYO model and checkpointed edit.")
    agent_run.add_argument("path", nargs="?", default=".")
    agent_run.add_argument("--goal", required=True)
    agent_run.add_argument("--service", default="")
    agent_run.add_argument("--agent", default="")
    agent_run.add_argument("--mode", default="suggest", choices=[str(item["id"]) for item in CODEE_PERMISSION_MODES])
    agent_run.add_argument("--use-model", action="store_true", help="Call CODEE_MODEL_COMMAND, --model-command, or configured chat endpoint. No model key is stored.")
    agent_run.add_argument("--provider", default="", help="Optional provider override such as local-rules, command, or openai-compatible.")
    agent_run.add_argument("--model", default="", help="Optional model override for chat-completions-compatible endpoints.")
    agent_run.add_argument("--endpoint", default="", help="Optional chat-completions-compatible endpoint override.")
    agent_run.add_argument("--model-command", default="", help="Local command to run with the agent prompt on stdin.")
    agent_run.add_argument("--file", default="", help="Optional file for exact replacement.")
    agent_run.add_argument("--find", default="", help="Exact text to replace once when --file is used.")
    agent_run.add_argument("--replace", default="", help="Replacement text when --file is used.")
    agent_run.add_argument("--apply", action="store_true", help="Apply the exact replacement after checkpoint.")
    agent_run.add_argument("--test-cmd", default="", help="Optional test command. Runs with edit, or standalone only with --allow-shell.")
    agent_run.add_argument("--allow-shell", action="store_true", help="Allow a standalone --test-cmd without an edit.")
    agent_run.add_argument("--url", action="append", help="Optional live route to check. Can be repeated.")
    agent_run.add_argument("--timeout", default="30")
    agent_run.add_argument("--write", action="store_true")
    agent_run.add_argument("--force", action="store_true")
    agent_run.add_argument("--json", action="store_true")
    agent_run.set_defaults(func=command_agent_run)

    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)

    edit = sub.add_parser("edit", help="Apply one checkpointed local text replacement and optional test command.")
    edit.add_argument("path", nargs="?", default=".")
    edit.add_argument("--request", default="", help="Human description of the edit.")
    edit.add_argument("--file", required=True, help="File to edit, relative to path unless absolute.")
    edit.add_argument("--find", required=True, help="Exact text to replace once.")
    edit.add_argument("--replace", required=True, help="Replacement text.")
    edit.add_argument("--apply", action="store_true", help="Write the replacement after creating a checkpoint.")
    edit.add_argument("--test-cmd", default="", help="Optional local command to run after the edit.")
    edit.add_argument("--json", action="store_true")
    edit.set_defaults(func=command_edit)

    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("--domain-preference", default="", help="CODEE LINK, OWN DOMAIN, NOT SURE, or pasted domain.")
    preview.add_argument("--custom-domain", default="", help="Optional client-owned domain to prepare for later white-label support.")
    preview.add_argument("--white-label", action="store_true", help="Mark that the client wants white-label/custom-domain support after activation.")
    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)

    audit = sub.add_parser("audit", aliases=["free-audit", "site-audit"], help="Create the audit-first CodeeChat flow: free report, delivery room, and smallest paid upsell.")
    audit.add_argument("path", nargs="?", default=".")
    audit.add_argument("--service", default="free-audit", help="Audit lane: free-audit or audit-site.")
    audit.add_argument("--recommended-service", default="codeeqr", help="First paid lane to recommend after audit, usually codeeqr.")
    audit.add_argument("--business", default="")
    audit.add_argument("--owner", default="")
    audit.add_argument("--email", default="")
    audit.add_argument("--target-url", default="")
    audit.add_argument("--goal", default="")
    audit.add_argument("--write", action="store_true")
    audit.add_argument("--force", action="store_true")
    audit.add_argument("--json", action="store_true")
    audit.set_defaults(func=command_audit)

    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)

    deploy_plan = sub.add_parser("deploy-plan", help="Write an owner-gated deploy plan packet for a paid Codee business lane.")
    deploy_plan.add_argument("path", nargs="?", default=".")
    deploy_plan.add_argument("--service", default="business-suite")
    deploy_plan.add_argument("--plan", default="biz")
    deploy_plan.add_argument("--business", default="")
    deploy_plan.add_argument("--email", default="")
    deploy_plan.add_argument("--target-url", default="")
    deploy_plan.add_argument("--price", default="")
    deploy_plan.add_argument("--price-cents", default="")
    deploy_plan.add_argument("--write", action="store_true")
    deploy_plan.add_argument("--force", action="store_true")
    deploy_plan.add_argument("--json", action="store_true")
    deploy_plan.set_defaults(func=command_deploy_plan)

    income_lane = sub.add_parser("income-lane", help="Create a local proof packet for a checkout/income lane request.")
    income_lane.add_argument("path", nargs="?", default=".")
    income_lane.add_argument("--service", default="business-suite")
    income_lane.add_argument("--plan", default="biz")
    income_lane.add_argument("--business", default="")
    income_lane.add_argument("--email", default="")
    income_lane.add_argument("--target-url", default="")
    income_lane.add_argument("--offer", default="")
    income_lane.add_argument("--price", default="")
    income_lane.add_argument("--price-cents", default="")
    income_lane.add_argument("--write", action="store_true")
    income_lane.add_argument("--force", action="store_true")
    income_lane.add_argument("--json", action="store_true")
    income_lane.set_defaults(func=command_income_lane)

    stripe_product = sub.add_parser("stripe-product", help="Prepare an owner-reviewed Stripe product request packet.")
    stripe_product.add_argument("path", nargs="?", default=".")
    stripe_product.add_argument("--service", default="business-suite")
    stripe_product.add_argument("--plan", default="biz")
    stripe_product.add_argument("--business", default="")
    stripe_product.add_argument("--email", default="")
    stripe_product.add_argument("--target-url", default="")
    stripe_product.add_argument("--name", default="")
    stripe_product.add_argument("--price", default="")
    stripe_product.add_argument("--price-cents", default="")
    stripe_product.add_argument("--write", action="store_true")
    stripe_product.add_argument("--force", action="store_true")
    stripe_product.add_argument("--json", action="store_true")
    stripe_product.set_defaults(func=command_stripe_product)

    biz_launch = sub.add_parser("biz-launch", help="Write a Codee Biz launch bundle proof packet.")
    biz_launch.add_argument("path", nargs="?", default=".")
    biz_launch.add_argument("--service", default="business-suite")
    biz_launch.add_argument("--plan", default="biz")
    biz_launch.add_argument("--business", default="")
    biz_launch.add_argument("--email", default="")
    biz_launch.add_argument("--target-url", default="")
    biz_launch.add_argument("--price", default="")
    biz_launch.add_argument("--price-cents", default="")
    biz_launch.add_argument("--write", action="store_true")
    biz_launch.add_argument("--force", action="store_true")
    biz_launch.add_argument("--json", action="store_true")
    biz_launch.set_defaults(func=command_biz_launch)

    deploy = sub.add_parser("deploy", help="Queue an owner-gated deploy request packet from the public CLI.")
    deploy.add_argument("path", nargs="?", default=".")
    deploy.add_argument("--service", default="business-suite")
    deploy.add_argument("--plan", default="biz")
    deploy.add_argument("--business", default="")
    deploy.add_argument("--email", default="")
    deploy.add_argument("--target-url", default="")
    deploy.add_argument("--price", default="")
    deploy.add_argument("--price-cents", default="")
    deploy.add_argument("--write", action="store_true")
    deploy.add_argument("--force", action="store_true")
    deploy.add_argument("--json", action="store_true")
    deploy.set_defaults(func=command_deploy)

    compare = sub.add_parser("compare", help="Compare CodeeCLI against Codex-style terminal workflows.")
    compare.add_argument("target", nargs="?", default="codex")
    compare.add_argument("--json", action="store_true")
    compare.set_defaults(func=command_compare)

    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_PLAN_ALIASES.keys(), *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)

    heel = sub.add_parser("heel", aliases=["heal", "codee-heel", "codee-heal", "teacher-packet"], help="Military K9-style teacher/support packet with login, diagnosis, and safe repair commands.")
    heel.add_argument("path", nargs="?", default=".")
    heel.add_argument("--teacher-email", default="", help="Email for the teacher/support helper login command.")
    heel.add_argument("--email", default="", help="Alias for --teacher-email.")
    heel.add_argument("--student-email", default="")
    heel.add_argument("--teacher", default="Codee Teacher")
    heel.add_argument("--client", default="", help="Client ID or workspace slug.")
    heel.add_argument("--business", default="")
    heel.add_argument("--owner", default="Sean")
    heel.add_argument("--service", default="codee-heel")
    heel.add_argument("--request", default="", help="What the teacher/support helper needs to fix or teach.")
    heel.add_argument("--route", default="", help="Page or route the teacher should verify.")
    heel.add_argument("--require-email", action="store_true", help="Fail when no teacher email is supplied.")
    heel.add_argument("--live-check", action="store_true", help="Check the live CLI download and teacher manifest.")
    heel.add_argument("--timeout", default="20")
    heel.add_argument("--write", action="store_true")
    heel.add_argument("--force", action="store_true")
    heel.add_argument("--open", action="store_true")
    heel.add_argument("--json", action="store_true")
    heel.set_defaults(func=command_heel)

    owner_dev = sub.add_parser("owner-dev", aliases=["admin-codee", "edit-stack"], help="Write the owner-grade frontend/backend edit workflow packet.")
    owner_dev.add_argument("path", nargs="?", default=".")
    owner_dev.add_argument("--mode", default="fullstack", choices=["frontend", "backend", "fullstack", "social", "deploy"])
    owner_dev.add_argument("--client", default="", help="Client ID or workspace slug.")
    owner_dev.add_argument("--business", default="")
    owner_dev.add_argument("--owner", default="Sean")
    owner_dev.add_argument("--service", default="codee-owner-dev")
    owner_dev.add_argument("--request", default="", help="Frontend/backend edit request to plan and prove.")
    owner_dev.add_argument("--route", default="", help="Public page or API route that should be proven after the edit.")
    owner_dev.add_argument("--file", action="append", default=[], help="Specific file expected to change. Can be repeated.")
    owner_dev.add_argument("--write", action="store_true")
    owner_dev.add_argument("--force", action="store_true")
    owner_dev.add_argument("--open", action="store_true")
    owner_dev.add_argument("--json", action="store_true")
    owner_dev.set_defaults(func=command_owner_dev)

    owner_support = sub.add_parser("owner-support", aliases=["support-team"], help="Write the owner-only frontend support and outdated-CLI rescue packet.")
    owner_support.add_argument("path", nargs="?", default=".")
    owner_support.add_argument("--client", default="", help="Client ID or workspace slug.")
    owner_support.add_argument("--business", default="")
    owner_support.add_argument("--owner", default="Sean")
    owner_support.add_argument("--service", default="codee-support")
    owner_support.add_argument("--request", default="", help="Frontend update or support request to package.")
    owner_support.add_argument("--route", default="", help="Page or route needing support.")
    owner_support.add_argument("--priority", default="normal", choices=["low", "normal", "high", "urgent"])
    owner_support.add_argument("--team", action="append", default=[], help="Support team member or role. Can be repeated.")
    owner_support.add_argument("--write", action="store_true")
    owner_support.add_argument("--force", action="store_true")
    owner_support.add_argument("--open", action="store_true")
    owner_support.add_argument("--json", action="store_true")
    owner_support.set_defaults(func=command_owner_support)

    social_connect = sub.add_parser("social-connect", aliases=["codee-social-connect"], help="Show the AI K9 Codee Social Connect link and status URLs for a client.")
    social_connect.add_argument("path", nargs="?", default=".")
    social_connect.add_argument("--client", default="", help="Client ID or workspace slug.")
    social_connect.add_argument("--platform", default="facebook", choices=["facebook", "instagram", "pinterest", "youtube", "tiktok"])
    social_connect.add_argument("--open", action="store_true")
    social_connect.add_argument("--json", action="store_true")
    social_connect.set_defaults(func=command_social_connect)

    codex_bridge = sub.add_parser("codex-bridge", aliases=["codex", "bridge"], help="Write a Codex-readable live CLI bridge packet.")
    codex_bridge.add_argument("path", nargs="?", default=".")
    codex_bridge.add_argument("--client", default="", help="Client ID or workspace slug.")
    codex_bridge.add_argument("--business", default="")
    codex_bridge.add_argument("--owner", default="Sean")
    codex_bridge.add_argument("--request", default="", help="CLI/site/backend enhancement request to hand off to Codex.")
    codex_bridge.add_argument("--file", action="append", default=[], help="Specific file Codex should inspect. Can be repeated.")
    codex_bridge.add_argument("--live-check", action="store_true", help="Check the live Ai K9 CODEE page, download, and manifests.")
    codex_bridge.add_argument("--timeout", default="20")
    codex_bridge.add_argument("--write", action="store_true")
    codex_bridge.add_argument("--force", action="store_true")
    codex_bridge.add_argument("--open", action="store_true")
    codex_bridge.add_argument("--json", action="store_true")
    codex_bridge.set_defaults(func=command_codex_bridge)

    codex_sync = sub.add_parser("codex-sync", aliases=["codex-update", "sync-codex"], help="Detect local Codex version changes and refresh Codee parity/update files.")
    codex_sync.add_argument("path", nargs="?", default=".")
    codex_sync.add_argument("--apply-codee-update", action="store_true", help="If Codex changed or this is the first sync, refresh this Codee CLI from the public Codee release.")
    codex_sync.add_argument("--timeout", default="20")
    codex_sync.add_argument("--write", action="store_true")
    codex_sync.add_argument("--force", action="store_true")
    codex_sync.add_argument("--json", action="store_true")
    codex_sync.set_defaults(func=command_codex_sync)

    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)

    check = sub.add_parser("check", aliases=["proof"], help="Simple check: run doctor locally, or scan URLs when --url is provided.")
    check.add_argument("path", nargs="?", default=".")
    check.add_argument("--url", action="append", help="Route to scan. Can be passed more than once.")
    check.add_argument("--expected", default="200", help="Comma-separated acceptable status codes when --url is used.")
    check.add_argument("--timeout", default=str(DEFAULT_ROUTE_TIMEOUT))
    check.add_argument("--local-only", action="store_true")
    check.add_argument("--json", action="store_true")
    check.set_defaults(func=command_check)

    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, codeeflyer100, codeeflyer300, codeecard, or minicodeesite.")
    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, codeeflyer300, codeecard, or minicodeesite.")
    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)

    services = sub.add_parser("services", aliases=["service-menu", "catalog"], help="Show the Codee.chat service menu mirrored into Codee CLI.")
    services.add_argument("--public-only", action="store_true", help="Only show normal public Codee.chat services.")
    services.add_argument("--include-review", action="store_true", help="Also show owner-review or paused service lanes.")
    services.add_argument("--json", action="store_true")
    services.set_defaults(func=command_services)

    maintain = sub.add_parser("maintain", aliases=["maintenance"], help="Run the repo-local Codee maintenance worker and write proof reports.")
    maintain.add_argument("path", nargs="?", default=".")
    maintain.add_argument("--profile", default="core", choices=["core", "full"])
    maintain.add_argument("--timeout", default="90")
    maintain.add_argument("--skip-intake-smoke", action="store_true")
    maintain.add_argument("--skip-workspace-smoke", action="store_true")
    maintain.add_argument("--live", action="store_true")
    maintain.add_argument("--strict", action="store_true")
    maintain.add_argument("--write-report", action="store_true")
    maintain.add_argument("--json", action="store_true")
    maintain.set_defaults(func=command_maintain)

    admin_cli = sub.add_parser("admin-cli", aliases=["admin"], help="Smart owner/admin shortcut that routes a plain-English request to edit, deploy, support, or admin-ops.")
    admin_cli.add_argument("path", nargs="?", default=".")
    admin_cli.add_argument("--request", required=True, help="Plain-English admin request.")
    admin_cli.add_argument("--client", default="")
    admin_cli.add_argument("--business", default="")
    admin_cli.add_argument("--owner", default="Sean")
    admin_cli.add_argument("--service", default="codee-owner-dev")
    admin_cli.add_argument("--route", default="")
    admin_cli.add_argument("--file", action="append", default=[], help="Specific file expected to change. Can be repeated.")
    admin_cli.add_argument("--state", action="append", default=[])
    admin_cli.add_argument("--all-states", action="store_true")
    admin_cli.add_argument("--month", default="")
    admin_cli.add_argument("--focus", default="land housing mission")
    admin_cli.add_argument("--team", action="append", default=[])
    admin_cli.add_argument("--write", action="store_true")
    admin_cli.add_argument("--force", action="store_true")
    admin_cli.add_argument("--open", action="store_true")
    admin_cli.add_argument("--json", action="store_true")
    admin_cli.set_defaults(func=command_admin_cli)

    preview_edit = sub.add_parser("preview-edit", help="Create a bounded frontend copy-edit preview. Never changes the live file.")
    preview_edit.add_argument("path", nargs="?", default=".")
    preview_edit.add_argument("--client", default="")
    preview_edit.add_argument("--site-key", default="")
    preview_edit.add_argument("--page", default="home")
    preview_edit.add_argument("--section", default="hero")
    preview_edit.add_argument("--request", required=True)
    preview_edit.add_argument("--copy", required=True, help="Structured replacement copy, e.g. 'headline: New headline'.")
    preview_edit.add_argument("--priority", default="normal", choices=["low", "normal", "high", "urgent"])
    preview_edit.add_argument("--requester", default="")
    preview_edit.add_argument("--email", default="")
    preview_edit.add_argument("--submit", action="store_true", help="Store the request and generate the backend preview. No live edit is applied.")
    preview_edit.add_argument("--api-base", default=CODEE_BACKEND_API_BASE)
    preview_edit.add_argument("--timeout", default="30")
    preview_edit.add_argument("--write", action="store_true")
    preview_edit.add_argument("--json", action="store_true")
    preview_edit.set_defaults(func=command_preview_edit)

    for command_name, help_text, handler in (
        ("approve-edit", "Explicitly approve a safe generated edit preview.", command_approve_edit),
        ("apply-edit", "Apply an explicitly approved edit and retain its rollback backup.", command_apply_edit),
        ("rollback-edit", "Restore an applied edit from its retained backup.", command_rollback_edit),
        ("edit-status", "Read one edit request, preview, approval, apply, and rollback state.", command_edit_status),
    ):
        edit_command = sub.add_parser(command_name, help=help_text)
        edit_command.add_argument("path", nargs="?", default=".")
        edit_command.add_argument("--client", default="")
        edit_command.add_argument("--request-id", required=True)
        edit_command.add_argument("--submit", action="store_true", help="Call the backend action. Owner actions read CODEE_ADMIN_TOKEN from the environment.")
        edit_command.add_argument("--api-base", default=CODEE_BACKEND_API_BASE)
        edit_command.add_argument("--timeout", default="30")
        edit_command.add_argument("--write", action="store_true")
        edit_command.add_argument("--json", action="store_true")
        edit_command.set_defaults(func=handler)

    deploy_adapter = sub.add_parser("deploy-adapter", help="Guarded preview, approval, apply, verification, and rollback adapters for owner deployments.")
    deploy_adapter.add_argument("path", nargs="?", default=".")
    deploy_adapter.add_argument("--platform", required=True, choices=["gcs-client", "made-for-this-firebase", "firebase-hosting", "cloud-run"])
    deploy_adapter.add_argument("--phase", default="preview", choices=["preview", "approve", "apply", "verify", "rollback"])
    deploy_adapter.add_argument("--source", default="")
    deploy_adapter.add_argument("--target", default="")
    deploy_adapter.add_argument("--url", default="")
    deploy_adapter.add_argument("--project", default="")
    deploy_adapter.add_argument("--site", default="")
    deploy_adapter.add_argument("--config", default="firebase.json")
    deploy_adapter.add_argument("--rollback-source", default="", help="Previous GCS object or Cloud Run revision used only for rollback.")
    deploy_adapter.add_argument("--execute", action="store_true", help="Execute the exact selected adapter command after its approval gate.")
    deploy_adapter.add_argument("--timeout", default="900")
    deploy_adapter.add_argument("--write", action="store_true")
    deploy_adapter.add_argument("--json", action="store_true")
    deploy_adapter.set_defaults(func=command_deploy_adapter)

    service_seed = sub.add_parser("service-seed", aliases=["idea-to-service", "idea"], help="Create a private Codee Idea-to-Service preview with paid hosting activation gates.")
    service_seed.add_argument("path", nargs="?", default=".")
    service_seed.add_argument("--title", default="")
    service_seed.add_argument("--idea", default="")
    service_seed.add_argument("--idea-file", default="")
    service_seed.add_argument("--business", default="")
    service_seed.add_argument("--client-id", default="")
    service_seed.add_argument("--plan", default="free", help="free, chief, partner, service_creator, or business_suite")
    service_seed.add_argument("--write", action="store_true")
    service_seed.add_argument("--force", action="store_true")
    service_seed.add_argument("--submit", action="store_true", help="Submit the seed to the live Codee workspace backend.")
    service_seed.add_argument("--api-base", default=CODEE_BACKEND_API_BASE)
    service_seed.add_argument("--timeout", default="30")
    service_seed.add_argument("--open", action="store_true")
    service_seed.add_argument("--json", action="store_true")
    service_seed.set_defaults(func=command_service_seed)

    owner_generate = sub.add_parser("owner-generate", aliases=["admin-generate", "owner-service"], help="Generate an owner/admin no-paywall local service workspace.")
    owner_generate.add_argument("path", nargs="?", default=".")
    owner_generate.add_argument("--service", default="codeeqr", help="Service lane, e.g. codeeqr, codeeflyer300, codeecard, minicodeesite, or codee-business-suite.")
    owner_generate.add_argument("--business", default="")
    owner_generate.add_argument("--owner", default="Sean")
    owner_generate.add_argument("--client-id", default="")
    owner_generate.add_argument("--codee-user-id", default="")
    owner_generate.add_argument("--target-url", default="")
    owner_generate.add_argument("--goal", default="")
    owner_generate.add_argument("--public-base", default=DEFAULT_API_BASE)
    owner_generate.add_argument("--write", action="store_true")
    owner_generate.add_argument("--force", action="store_true")
    owner_generate.add_argument("--open", action="store_true")
    owner_generate.add_argument("--json", action="store_true")
    owner_generate.set_defaults(func=command_owner_generate)

    veteran_mission = sub.add_parser("veteran-mission", aliases=["mission-qrcodee", "veteran-qrcodee"], help="Create a free veteran Codee app and QRCodee referral proof packet.")
    veteran_mission.add_argument("path", nargs="?", default=".")
    veteran_mission.add_argument("--name", default="", help="Public-safe veteran display name.")
    veteran_mission.add_argument("--veteran-id", default="", help="Stable public profile id.")
    veteran_mission.add_argument("--cohort", default="homeless-or-disabled-veteran")
    veteran_mission.add_argument("--weekly-status", default="ready_for_owner_selection")
    veteran_mission.add_argument("--story-public", default="", help="Owner-approved public-safe story copy.")
    veteran_mission.add_argument("--support-need", default="", help="Owner-approved public support need.")
    veteran_mission.add_argument("--cash-tag", default="AIK9Codee")
    veteran_mission.add_argument("--support-url", default="", help="Support button destination. Defaults to Cash App cashtag.")
    veteran_mission.add_argument("--support-label", default="", help="Public support destination label.")
    veteran_mission.add_argument("--support-button-label", default="Support this veteran")
    veteran_mission.add_argument("--qr-target-url", default="", help="QR target. Defaults to the veteran Codee app URL.")
    veteran_mission.add_argument("--qr-image-url", default="", help="Existing QR image URL to show on the app.")
    veteran_mission.add_argument("--business-service", default="codeeqr", help="Primary business lane to offer behind the QR path.")
    veteran_mission.add_argument("--ref", default="", help="Referral code. Defaults to mission-<veteran-id>.")
    veteran_mission.add_argument("--write", action="store_true")
    veteran_mission.add_argument("--force", action="store_true")
    veteran_mission.add_argument("--json", action="store_true")
    veteran_mission.set_defaults(func=command_veteran_mission)

    pricing = sub.add_parser("pricing", help="Show client tool and hosting offers; CODEECLI remains free.")
    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("--include-review", action="store_true", help="Include owner-review and paused internal lanes in local pricing.")
    pricing.add_argument("--json", action="store_true")
    pricing.set_defaults(func=command_pricing)

    human_proof = sub.add_parser("human-proof", aliases=["live-proof"], help="Show or write the live human-proof screen-recording checklist.")
    human_proof.add_argument("path", nargs="?", default=".")
    human_proof.add_argument("--promo-code", default=CODEE_LIVE_PROOF_PROMO_CODE)
    human_proof.add_argument("--write", action="store_true")
    human_proof.add_argument("--json", action="store_true")
    human_proof.set_defaults(func=command_human_proof)

    upgrade = sub.add_parser("upgrade", help="Create a Stripe-hosted checkout link for a client tool or hosting offer.")
    upgrade.add_argument("path", nargs="?", default=".")
    upgrade.add_argument("--plan", default="qrcodee_lane", help="Offer: qrcodee_lane, codeeflyer_lane, or hosting_care. Legacy flyer plan names resolve to codeeflyer_lane.")
    upgrade.add_argument("--email", default="")
    upgrade.add_argument("--business", default="")
    upgrade.add_argument("--owner", default="")
    upgrade.add_argument("--ref", default="codee-cli")
    upgrade.add_argument("--promo-code", "--promotion-code", default="", help="Optional Stripe promotion code to apply to the hosted checkout.")
    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="Owner-review invoice command; current $49/$99/$19 offers use Checkout.")
    invoice.add_argument("path", nargs="?", default=".")
    invoice.add_argument("--plan", default="codeeflyer_lane", help="Current public offers do not support invoices.")
    invoice.add_argument("--email", default="")
    invoice.add_argument("--business", default="")
    invoice.add_argument("--owner", default="")
    invoice.add_argument("--ref", default="codee-cli-invoice")
    invoice.add_argument("--promo-code", "--promotion-code", default="", help="Optional promo code saved in the request metadata.")
    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 Ai K9 CODEE 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", aliases=["intake"], 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, codeeflyer300, codeecard, or minicodeesite.")
    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("--domain-preference", default="", help="CODEE LINK, OWN DOMAIN, NOT SURE, or pasted domain.")
    client.add_argument("--custom-domain", default="", help="Optional client-owned domain to prepare for later white-label support.")
    client.add_argument("--white-label", action="store_true", help="Mark that the client wants white-label/custom-domain support after activation.")
    client.add_argument("--promo-code", default="", help="Optional Stripe promotion code to preload into the paywall proof path.")
    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, codeecard, or minicodeesite.")
    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("--domain-preference", default="", help="CODEE LINK, OWN DOMAIN, NOT SURE, or pasted domain.")
    connect.add_argument("--custom-domain", default="", help="Optional client-owned domain to prepare for later white-label support.")
    connect.add_argument("--white-label", action="store_true", help="Attach white-label/custom-domain support to this backend connection.")
    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, codeecard, or minicodeesite.")
    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("--domain-preference", default="", help="CODEE LINK, OWN DOMAIN, NOT SURE, or pasted domain.")
    activate.add_argument("--custom-domain", default="", help="Optional client-owned domain to prepare for later white-label support.")
    activate.add_argument("--white-label", action="store_true", help="Attach white-label/custom-domain support to this activation.")
    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)

    help_me = sub.add_parser("help-me", aliases=["helpme"], help="Create a support request with one plain-English sentence.")
    help_me.add_argument("message", nargs="*", help='Example: CODEE help-me "Fix my flyer link"')
    help_me.add_argument("--path", default=".", help="Workspace folder. Defaults to the current folder.")
    help_me.add_argument("--service", default="codee-support")
    help_me.add_argument("--type", default="site-update")
    help_me.add_argument("--title", default="")
    help_me.add_argument("--route", default="")
    help_me.add_argument("--attachment", action="append", help="File path or public URL to attach. Can be passed more than once.")
    help_me.add_argument("--priority", default="normal")
    help_me.add_argument("--email", default="")
    help_me.add_argument("--business", default="")
    help_me.add_argument("--owner", default="")
    help_me.add_argument("--delivery-room-url", default="")
    help_me.add_argument("--api-base", default=DEFAULT_API_BASE)
    help_me.add_argument("--timeout", default="30")
    help_me.add_argument("--submit", action="store_true", help="Send the request to Codee backend.")
    help_me.add_argument("--dry-run", action="store_true")
    help_me.add_argument("--open", action="store_true")
    help_me.add_argument("--json", action="store_true")
    help_me.set_defaults(func=command_help_me)

    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:
    argv = _normalize_cli_argv(list(sys.argv[1:] if argv is None else argv))
    if not argv:
        argv = ["prompt"]
    elif all(item in {"--plain", "--no-emoji"} for item in argv):
        argv = ["prompt", *argv]
    elif argv[0] in {"--help", "-h", "help"}:
        _print_simple_codee_help(
            argparse.Namespace(
                plain="--plain" in argv,
                no_emoji="--no-emoji" in argv,
                json="--json" in argv,
            )
        )
        return 0
    elif argv[0] in {"advanced-help", "all-commands", "commands"}:
        parser = build_parser()
        parser.print_help()
        return 0
    parser = build_parser()
    command_names: set[str] = set()
    for action in parser._actions:
        if isinstance(action, argparse._SubParsersAction):
            command_names.update(action.choices)
    if argv and not argv[0].startswith("-") and argv[0] not in command_names:
        argv = ["ask", *argv]
    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:]))
