Creating a dedicated documentation file named **`newapp.standards.md`** in your repository root is the ideal approach. It serves as an immutable master guide for creating any future application or expanding existing ones within your architecture without drifting into code duplication or hardcoded paths.

Here is a comprehensive template for **`newapp.standards.md`** that captures every golden rule, path standard, and architectural pattern we have established:

```markdown
# Standards & Guide: Building a New App (`newapp.standards.md`)

This document outlines the non-negotiable architectural standards for creating, structuring, and testing applications within the system. Adhering to these rules guarantees DRY (Don't Repeat Yourself), modularity, and dual CLI/Web compatibility.

---

## 1. Core Architecture Principles
* **Single Source of Truth (DRY):** Never duplicate path resolution, configuration loading, database connections, or request handling boilerplate across apps or endpoints.
* **Shared Infrastructure:** Core PHP libraries, JavaScript modules, CSS styles, and path registries live in the shared system directory (`/Users/rbutare/websites/system/`).
* **Environment-Driven Configuration:** System settings and app overrides are managed exclusively via `.env` files. No hardcoded file paths or database credentials inside application logic.

---

## 2. Directory Structure & Naming Conventions
Each application resides under the apps directory (`/Users/rbutare/websites/apps/<APP_NAME>/`) and follows a standardized layout:

```

/Users/rbutare/websites/
├── system/
│   ├── php/paths.php         # Master structural path & .env bootstrap
│   └── config/
│       ├── .env              # Global system settings
│       └── apps/<APP_NAME>/  # App-specific overrides (.env)
└── apps/
└── <APP_NAME>/
├── php/              # App-specific business logic & core helpers
└── api/              # API endpoints
├── api_bootstrap.php # App API wrapper (loads system paths & router)
└── endpoint.php      # Lean, specific controllers

```

---

## 3. Configuration & Path Resolution Standard
Every app entry point or API bootstrap file **must** define the application name and load the master system `paths.php` using its absolute path:

```php
<?php
declare(strict_types=1);

if (!defined('APP_NAME')) {
    define('APP_NAME', 'your_app_name');
}

// Load master system paths and configuration (Handles .env merging automatically)
require_once '/Users/rbutare/websites/system/php/paths.php';

```

### Configuration Cascading (`.env`)

1. **Global Settings:** Loaded from `system/config/.env`.
2. **App Overrides:** Loaded from `system/config/apps/<APP_NAME>/.env`.
3. App values automatically override global values in the merged `$GLOBALS['APP_ENV']` array.

---

## 4. API Endpoint Standardization

All API endpoints must remain lean controllers containing **only** their specific data queries and payload formatting.

### The Universal Wrapper (`wx_run_endpoint`)

Endpoints must utilize a centralized bootstrap that implements `wx_run_endpoint()` to handle headers, station validation, exception catching, and response formatting automatically:

```php
<?php
declare(strict_types=1);
/**
 * Endpoint: Description of Data
 * TEST CURL:
 *   curl -k -s "[https://rickweb.test:8443/appname/api/endpoint.php?param=value](https://rickweb.test:8443/appname/api/endpoint.php?param=value)" | json_pp
 * TEST CLI:
 *   QUERY_STRING="param=value" php endpoint.php
 */

require_once __DIR__ . '/api_bootstrap.php';

wx_run_endpoint(function($loc, $locationId) {
    // 1. Perform database queries using shared helpers (e.g., wx_row / wx_all)
    // 2. Return clean array data
    return [
        'status' => 'success',
        'data' => []
    ];
});

```

---

## 5. Dual CLI & Web Execution Parity

* **Automatic Query Binding:** `api_bootstrap.php` must automatically map `$_SERVER['QUERY_STRING']` to `$_GET` and `$_REQUEST` during CLI executions:
```php
if (empty($_GET) && !empty($_SERVER['QUERY_STRING'])) {
    parse_str($_SERVER['QUERY_STRING'], $_GET);
    $_REQUEST = array_merge($_REQUEST, $_GET);
}

```


* **Self-Documenting Headers:** Every script header must include exact test commands for both browser/curl and direct CLI execution.

---

## 6. How to Build a New App (Step-by-Step)

1. **Create App Directory:** Set up your folder under `apps/<APP_NAME>/`.
2. **Configure Environment:** Create an app-specific configuration folder under `system/config/apps/<APP_NAME>/` and add your `.env` file (defining `APP_URL`, etc.).
3. **Establish API Bootstrap (`api_bootstrap.php`):** Define `APP_NAME`, require `/Users/rbutare/websites/system/php/paths.php`, and set up the `wx_run_endpoint` wrapper.
4. **Build Lean Endpoints:** Write individual endpoint scripts that include `api_bootstrap.php` and focus purely on returning business data.
5. **Verify Both Environments:** Test your new endpoints using both `curl` (via your local web server) and `QUERY_STRING="..." php endpoint.php` (via CLI).

```
To maintain strict DRY (Don't Repeat Yourself) modularity and separate core infrastructure from app-specific business logic, every app folder under `apps/<APP_NAME>/` should follow a standardized four-file structure.

Here is the purpose of each file, what is **editable**, and what is **locked/shared** to prevent code duplication:

---

### App File Structure & Responsibilities

| File Name | Purpose | What is Editable / Custom | What is Locked / Non-Editable (DRY) |
| --- | --- | --- | --- |
| **`setup.php`** | App initialization, defining `APP_NAME`, requiring system `paths.php`, and setting app-specific constants. | Only the app name definition (`define('APP_NAME', 'your_app')`). | The inclusion path to the master system `paths.php` (`/Users/rbutare/websites/system/php/paths.php`). |
| **`config.php`** | App-specific database handles, local parameters, or route configurations that extend system defaults. | App-specific configuration keys, custom database connection tweaks, or widget settings. | Core database drivers and global security rules defined in system-level configs. |
| **`index.php`** | The public router or landing controller for the app (or API gateway entry point). | End-user UI rendering, dashboard layout views, or mapping incoming request routes. | Core bootstrap execution (`require_once 'setup.php';`) and global security headers. |
| **`view.php`** | Presentation layer (HTML templates, frontend UI components, or JSON response formatting). | HTML structure, CSS classes, JavaScript frontend logic, or template markup. | Raw database queries and business logic (which belong in controllers/APIs). |

---

### Golden Rules for App Files

1. **Never duplicate bootstrap logic:** Every file must inherit its paths from `setup.php`, which points directly to the shared system `paths.php`.
2. **Strict Separation of Concerns:** `index.php` handles request routing/control, `view.php` handles presentation, and `config.php`/`setup.php` handle environment and paths. No raw SQL or configuration strings should ever be hardcoded inside `view.php`.

Here are the production-ready starter templates for `setup.php` and `index.php` that align with your DRY architecture, shared path standards, and `.env` configuration cascading.

---

### 1. `setup.php`

This file initializes the application name, connects to the master system `paths.php`, and loads the shared core libraries. It serves as the single point of entry for all app files.

```php
<?php
declare(strict_types=1);

/**
 * App Setup & Bootstrap
 * Defines the application context and loads system-wide paths and environment settings.
 */

// 1. Define the unique application name (Must match directory name in apps/)
if (!defined('APP_NAME')) {
    define('APP_NAME', 'weatherdash'); // Change to your new app name
}

// 2. Load the master system paths and .env configuration registry
require_once '/Users/rbutare/websites/system/php/paths.php';

// 3. Load core system libraries and database helpers
require_once SYSTEM_ROOT . '/php/weather.core.php';
require_once SYSTEM_ROOT . '/php/weather.db.php';

```

---

### 2. `index.php`

This file acts as the public controller or landing router for the app. By requiring `setup.php`, it inherits all path and environment constants instantly without repeating code.

```php
<?php
declare(strict_types=1);
/**
 * App Entry Point / Router: index.php
 * TEST CURL:
 *   curl -k -s "https://rickweb.test:8443/weatherdash/" | head -n 20
 */

// Require the central app setup
require_once __DIR__ . '/setup.php';

try {
    // 1. App-specific request handling or routing logic goes here
    $appNameFormatted = ucfirst(APP_NAME);

    // 2. Render or load the presentation view layer
    // Example passing data to a view:
    $pageTitle = "Welcome to {$appNameFormatted}";

    // For an API-driven app or traditional view render:
    echo json_encode([
        'app' => APP_NAME,
        'status' => 'online',
        'root' => APP_ROOT,
        'message' => "Welcome to {$pageTitle}"
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => true,
        'message' => $e->getMessage()
    ]);
}

```
Here are the production-ready starter templates for `config.php` and `view.php` designed to plug seamlessly into your DRY architecture and shared path system.

---

### 1. `config.php`

This file isolates app-specific configuration settings, runtime defaults, or local parameters. It relies on the constants established by `setup.php` and your `.env` cascading rules, ensuring no hardcoded paths exist.

```php
<?php
declare(strict_types=1);
/**
 * App Configuration: config.php
 * Handles app-specific settings, UI defaults, or feature flags.
 */

// Ensure setup has already been loaded
if (!defined('APP_ROOT')) {
    require_once __DIR__ . '/setup.php';
}

return [
    'app_title' => ucfirst(APP_NAME) . ' Dashboard',
    'version'   => '1.0.0',
    'debug'     => defined('APP_ENV') && APP_ENV === 'development',
    // App-specific UI or behavioral toggles can be added here
    'features'  => [
        'auto_refresh' => true,
        'refresh_interval_sec' => 60,
    ]
];

```

---

### 2. `view.php`

This is the presentation layer. It contains **zero business logic or database queries**; it strictly accepts pre-formatted data arrays or configuration variables and renders the HTML markup or frontend template.

```php
<?php
declare(strict_types=1);
/**
 * Presentation View: view.php
 * Renders the HTML structure for the application UI.
 * Expected variables passed from controller/index.php:
 *   - $pageTitle (string)
 *   - $config (array)
 *   - $data (array)
 */
$pageTitle = $pageTitle ?? ucfirst(APP_NAME) . ' System';
$config = $config ?? [];
$data = $data ?? [];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?></title>
    <!-- Use system asset URL helper for shared stylesheets -->
    <link rel="stylesheet" href="<?= htmlspecialchars(system_asset_url('css/shared.css'), ENT_QUOTES, 'UTF-8') ?>">
</head>
<body>
    <header class="app-header">
        <h1><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?></h1>
        <span class="badge">Environment: <?= htmlspecialchars(APP_ENV ?? 'production', ENT_QUOTES, 'UTF-8') ?></span>
    </header>

    <main class="app-content">
        <section class="card">
            <h2>System Status</h2>
            <pre><?= htmlspecialchars(json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), ENT_QUOTES, 'UTF-8') ?></pre>
        </section>
    </main>

    <footer class="app-footer">
        <p>&copy; <?= date('Y') ?> <?= htmlspecialchars(ucfirst(APP_NAME), ENT_QUOTES, 'UTF-8') ?>. Powered by shared system infrastructure.</p>
    </footer>
</body>
</html>

```
Here is your consolidated, master architectural document **`newapp.standards.md`**. It combines your four-file app structure, `.env` cascading rules, shared system paths, validation requirements, redesign/testing guidelines, and file header commenting standards.

---

```markdown
# WeatherDash Architecture & Engineering Standards (`newapp.standards.md`)

This master specification defines the non-negotiable architectural rules for creating, structuring, validating, and testing applications within the WeatherDash ecosystem. Adherence to these guidelines guarantees strict DRY (Don't Repeat Yourself) modularity, unified path resolution, and universal web/CLI execution parity.

---

## 1. Core Architectural Principles
* **Single Source of Truth (DRY):** Never duplicate configuration loading, database connection logic, path resolution, or request-handling boilerplate across applications or endpoints.
* **Shared System Infrastructure:** Core PHP libraries, database helpers, CSS styles, and structural path definitions live exclusively in `/Users/rbutare/websites/system/`.
* **Two-Tier Environment Configuration (`.env`):** Global defaults are managed in `system/config/.env`, with app-specific overrides residing in `system/config/apps/<APP_NAME>/.env`. No hardcoded paths or credentials are permitted inside application logic.

---

## 2. Standard Application File Structure (`apps/<APP_NAME>/`)
Every application under the `apps/` directory must follow a strict four-file separation of concerns:

| File Name | Purpose | What is Editable / Custom | What is Locked / Non-Editable (DRY) |
| :--- | :--- | :--- | :--- |
| **`setup.php`** | App initialization, defining `APP_NAME`, requiring system `paths.php`, and loading core libraries. | Only the unique application name definition (`define('APP_NAME', 'your_app')`). | The absolute inclusion path to the master system `paths.php` (`/Users/rbutare/websites/system/php/paths.php`). |
| **`config.php`** | App-specific configuration settings, UI defaults, or feature toggles. | App-specific keys, parameters, or widget configurations. | Core database drivers and global security rules defined in system-level configs. |
| **`index.php`** | Public router, landing controller, or API gateway entry point. | End-user UI routing, controller logic, or request mapping. | Core setup inclusion (`require_once __DIR__ . '/setup.php';`) and global security headers. |
| **`view.php`** | Presentation layer (HTML templates, frontend UI components). | HTML structure, CSS layouts, and frontend markup. | Raw database queries and business logic (which belong strictly in controllers/APIs). |

---

## 3. Standardized File Header Comments
Every file within an application (especially entry points, routers, and API endpoints) must include standard documentation headers containing metadata and executable test commands:

```php
<?php
declare(strict_types=1);
/**
 * Application: <APP_NAME>
 * File: index.php / endpoint.php
 * Version: 1.0.0
 * Description: Brief explanation of the file's responsibility.
 *
 * TEST CURL (Web):
 *   curl -k -s "[https://rickweb.test:8443/](https://rickweb.test:8443/)<app_name>/endpoint.php?station=home" | json_pp
 *
 * TEST CLI:
 *   QUERY_STRING="station=home" php endpoint.php
 */

```

---

## 4. What Needs to be Validated (Checklist)

* **Path Resolution:** Ensure all scripts derive their root directories from `paths.php` using absolute paths (`__DIR__` or system constants like `SYSTEM_ROOT`), avoiding fragile relative traversal (`../../`).
* **Environment Integrity:** Confirm that `APP_NAME` is strictly declared *before* requiring `paths.php`.
* **Parameter Binding:** Verify that API endpoints rely on `api_bootstrap.php` to handle `QUERY_STRING` mapping for CLI compatibility.
* **Output Security:** Check that API routes suppress raw HTML errors (`display_errors = 0`) and strictly utilize `wx_api_success()` or `wx_api_error()`.

---

## 5. What Needs to be Added & Redesigned (Guidelines)

* **New App Creation:** When spinning up a new app, clone the standard structure (`setup.php`, `config.php`, `index.php`, `view.php`), create its configuration directory under `system/config/apps/<APP_NAME>/`, and establish its `.env` overrides.
* **API Standardization:** Refactor legacy endpoints to wrap their core business logic inside the universal `wx_run_endpoint(function($loc, $locationId) { ... })` handler.
* **Asset Centralization:** Always pull shared stylesheets and scripts via the system asset helper (`system_asset_url()`).

---

## 6. Testing & Verification Protocol

1. **Web Verification:** Test the endpoint or application route through your local web server using `curl` with the `-k` (insecure/self-signed SSL) flag.
2. **CLI Verification:** Test dual-compatibility by passing parameters via `QUERY_STRING` directly in the terminal:
```bash
QUERY_STRING="station=home" php endpoint.php

```


3. **Validation Check:** Confirm that JSON payloads return proper HTTP status codes (`200`, `400`, `404`, `500`) and structured error codes across both execution environments.

```

```
