# WebCrawlers Platform Technical & Architecture Reference

**Document Version:** 1.0.0  
**Target Environment:** PHP 8.5 / CodeIgniter 4 / MySQL 5.7+  
**Primary Repository Location:** `/var/www/php85/<username>/webcrawlers_latest.com/`

---

## Table of Contents

1. [Executive Summary & Purpose](#1-executive-summary--purpose)
2. [Technology Stack](#2-technology-stack)
3. [System Architecture](#3-system-architecture)
4. [Directory & File Organization](#4-directory--file-organization)
5. [URL Routing & Request Flow](#5-url-routing--request-flow)
6. [Authentication, Authorization & Security](#6-authentication-authorization--security)
7. [Background Jobs & Automation Queue](#7-background-jobs--automation-queue)
8. [Core Functional Modules](#8-core-functional-modules)
9. [Database & Data Modeling](#9-database--data-modeling)
10. [External Integrations](#10-external-integrations)
11. [Current Development Branch Context](#11-current-development-branch-context)
12. [Known Technical Debt & Recommendations](#12-known-technical-debt--recommendations)

---

## 1. Executive Summary & Purpose

**WebCrawlers** is an enterprise-grade SEO automation and search intelligence platform. It provides automated technical auditing, keyword research, SERP position monitoring, AI-assisted content drafting and scoring, Generative AI visibility tracking, opportunity discovery, and outcome attribution.

The platform is designed to serve:
- Logged-in web dashboard users managing multiple client websites across isolated team workspaces.
- Automated background workers continuously crawling sites, tracking rankings, and simulating AI engine responses.
- Client websites running an embedded proprietary tracking pixel (`px.js`) to capture real-time pageviews, conversion events, and Core Web Vitals.
- Mobile applications and external consumers via a versioned REST API (`/api/v1/*`).

---

## 2. Technology Stack

- **Backend Framework:** CodeIgniter 4 (v4.7.4) running on PHP 8.5.
- **Database Engine:** MySQL 5.7+ accessed via MySQLi driver, `utf8mb4_unicode_ci` collation across all tables.
- **Frontend Layer:** Server-rendered CodeIgniter 4 view templates (`app/Views/dashboard/`), hydrated dynamically in the browser using custom vanilla JavaScript (`public/assets/js/`) and `window.wcFetch()`.
- **Charting & Data Visualization:** Chart.js, Lucide icon set, and custom modular styling (`public/assets/css/`).
- **Asynchronous / Worker Model:** Database-backed queue (`wc_automation_queue`, `wc_serp_metric_jobs`) executed via CLI spark commands invoked by system cron. No Redis or Supervisor process managers are required.
- **Testing:** Standalone, network-independent test suites under `tests/standalone/` along with unit test fixtures under `tests/unit/`.

---

## 3. System Architecture

The application enforces a strict **Controller $\rightarrow$ Service/Library $\rightarrow$ Model $\rightarrow$ Database** pattern. Controllers remain thin: they validate incoming requests, verify authorization, delegate domain operations to the service layer in `app/Libraries/`, and return formatted responses.

```mermaid
flowchart TD
    subgraph Client ["Client Layer"]
        Browser["Desktop & Mobile Browsers"]
        Pixel["Client Websites (px.js)"]
    end

    subgraph Routing ["Routing & Entry Points (public/index.php)"]
        Marketing["Public Site & Auth (/signin, /signup, /about)"]
        DashboardUI["Dashboard UI (Flat /<module> routes)"]
        RestAPI["REST API (/api/v1/*)"]
        PixelIngest["Pixel Ingest (/px/*)"]
        Webhooks["DataForSEO Webhooks (/webhooks/*)"]
    end

    subgraph Filters ["Middleware / Filters"]
        AuthFilter["AuthFilter (Session + Plan Gate)"]
        ApiAuthFilter["ApiAuthFilter (Bearer HMAC / Session)"]
        CsrfFilter["CsrfFilter (Graceful Regeneration)"]
    end

    subgraph Services ["Service Layer (app/Libraries/)"]
        DfsService["DfsDatasetService & DataForSeo"]
        AuditService["AuditSyncService & CrawlEngine"]
        RankService["RankTrackingService & SharedKeywordSerp"]
        AiContent["AiContentService & ContentScoring"]
        AiVisibility["AiVisibilityService & Simulator"]
        MeasureService["MeasureGoogleSource & AttributionMeasurement"]
        BillingService["StickyLibrary & PlanAccess"]
    end

    subgraph Persistence ["Persistence & Background Workers"]
        MySQL[("MySQL 5.7 Database (64 wc_* tables + migrations)")]
        AutoQueue["wc_automation_queue & serp_metric_jobs"]
        CronWorkers["CLI Cron (webcrawlers_cron.sh)"]
    end

    subgraph Providers ["External API Integrations"]
        DFS["DataForSEO API (OnPage, Labs, SERP)"]
        LLM["OpenAI GPT & Google Gemini"]
        Google["Google APIs (GSC, GA4, GBP)"]
        Sticky["Sticky.io Billing Gateway"]
        Zepto["ZeptoMail (Transactional Email)"]
    end

    Browser -->|Session Requests| DashboardUI
    DashboardUI --> AuthFilter
    Browser -->|wcFetch Bearer/Session| RestAPI
    RestAPI --> ApiAuthFilter
    Pixel -->|CORS POST /px/*| PixelIngest
    DFS -->|POST pingback| Webhooks

    AuthFilter --> Services
    ApiAuthFilter --> Services
    PixelIngest --> Services
    Webhooks --> Services

    Services --> MySQL
    Services --> AutoQueue
    CronWorkers --> AutoQueue
    CronWorkers --> Services

    Services --> DFS
    Services --> LLM
    Services --> Google
    Services --> Sticky
    Services --> Zepto
```

---

## 4. Directory & File Organization

```
webcrawlers_latest.com/
├── app/
│   ├── Commands/              # CLI Spark commands (automation, crawls, SERP, DFS reporting)
│   │   ├── AutomationProcess.php
│   │   ├── AutomationSchedule.php
│   │   ├── CrawlPoll.php
│   │   ├── CrawlSchedule.php
│   │   ├── DfsDatasetsStatus.php
│   │   └── SerpBandMetricsProcess.php
│   ├── Config/                # Framework and domain configuration
│   │   ├── App.php            # Environment detection and dynamic baseURL/indexPage
│   │   ├── Constants.php      # WC_* API keys and configuration constants
│   │   ├── Filters.php        # Global and route-specific filter registrations
│   │   ├── Routes.php         # Central route definition file
│   │   └── SubscriptionPlans.php # Tier limits, quotas, and pricing definitions
│   ├── Controllers/           # Application controllers
│   │   ├── Api/
│   │   │   ├── V1/            # Version 1 REST API controllers (extend BaseApiController)
│   │   │   └── KeywordResearchController.php
│   │   ├── Auth.php           # Sign-in, sign-up, OTP, password recovery
│   │   ├── DashboardModule.php# Base controller for dashboard views (render, token injection)
│   │   └── <Module>Controller.php # Thin dashboard controllers (53 modules)
│   ├── Database/
│   │   ├── Migrations/        # 43 consolidated database migration files
│   │   └── Seeds/             # DatabaseSeeder and dictionary data seeders
│   ├── Filters/               # Security and lifecycle request filters
│   │   ├── ApiAuthFilter.php  # Dual-mode (Bearer HMAC token / Session) API guard
│   │   ├── AuthFilter.php     # Session authentication & plan checkout guard
│   │   └── CsrfFilter.php     # Resilient CSRF filter with automatic form resubmission
│   ├── Helpers/               # Global procedural view/service helpers (e.g. research_helper.php)
│   ├── Libraries/             # Domain service layer (23 core service classes)
│   │   ├── AiContentService.php
│   │   ├── AiVisibilityService.php
│   │   ├── AuditSyncService.php
│   │   ├── CrawlEngine.php
│   │   ├── DataForSeo.php
│   │   ├── DfsDatasetService.php
│   │   ├── MeasureGoogleSource.php
│   │   ├── PlanAccess.php
│   │   ├── RankTrackingService.php
│   │   ├── SiteOverviewService.php
│   │   ├── TeamAccess.php
│   │   └── TopPagesService.php
│   ├── Models/                # CodeIgniter 4 Active Record models (33 models)
│   └── Views/
│       ├── dashboard/         # Server-rendered dashboard views
│       │   ├── layout/        # HTML shell: top.php, bottom.php, nav.php, components.php
│       │   └── <module>.php   # Module view templates (hydrated by assets/js/<module>.js)
│       └── layouts/           # Public marketing site layouts
├── docs/                      # Technical documentation and implementation roadmaps
├── public/                    # Web root directory
│   ├── index.php              # Bootstrap entry point (detects CI_ENVIRONMENT)
│   ├── px.js                  # Proprietary JavaScript tracking pixel
│   └── assets/                # Live frontend assets loaded by the application
│       ├── css/               # Modular CSS (dashboard.css + per-module files)
│       └── js/                # Modular JS (dashboard.js + per-module files)
├── tests/
│   ├── standalone/            # Network-independent regression test scripts
│   └── unit/                  # PHPUnit unit test cases
├── schema.md                  # Complete database schema reference and deployment runbook
└── webcrawlers_cron.sh        # Automation queue CLI cron script
```

---

## 5. URL Routing & Request Flow

The application divides its routes into distinct functional spaces in `app/Config/Routes.php`:

### 5.1 Public Marketing & Auth
- `/`: Marketing landing page (`Pages::index`).
- `/signin`, `/signup`: Password and OTP verification (`Auth`).
- `/auth/google`, `/auth/google/callback`: OAuth2 social authentication.
- `/lp/(:segment)/(:num)`: Dynamic marketing landing pages.
- `/thank-you`, `/pricing`, `/about`, `/contact`: Static marketing content.

### 5.2 Flat Dashboard Routes
Dashboard routes are flat paths mapped directly to their respective controllers and guarded individually with `['filter' => 'auth']`:
- `/dashboard`: Main executive dashboard (`Dashboard::index`).
- `/website`: Website configuration and verification (`WebsiteController::index`).
- `/site-overview`: Site Explorer analytics (`SiteOverviewController::index`).
- `/top-pages`: Top Pages report (`TopPagesController::index`).
- `/crawl`, `/crawl/history`: Real-time and historical technical audits (`CrawlController`, `CrawlHistoryController`).
- `/keywords`, `/rank-tracking`, `/keyword-research`: Rank tracking and gap analysis.
- `/ai-content`, `/ai-content/analyze`: AI content creation and on-page optimization.
- `/ai-visibility`: LLM citation and search brand monitoring.
- `/opportunities`: Automated opportunity discovery and review pipeline.
- `/search-performance`, `/conversions`, `/attribution`, `/locations`: Measurement and attribution views.
- `/settings/*`: Workspaces, team users, permissions, integrations, and billing.

### 5.3 REST API Endpoints (`/api/v1/*`)
All endpoints in this group run under the `apiauth` filter and namespace `App\Controllers\Api\V1`. Controllers inherit from `BaseApiController` and return standardized responses:
- `GET/POST /api/v1/dashboard`: Aggregated dashboard metrics.
- `GET/POST /api/v1/websites`: Multi-site management, verification, and schedule settings.
- `POST /api/v1/site-overview`: Cached domain metrics and scoped refreshes (`overview`, `signals`, `content`, `all`).
- `POST /api/v1/top-pages/search`, `POST /api/v1/top-pages/refresh`: Cache-only search and 24-hr refreshed organic pages.
- `POST /api/v1/top-pages/citations/refresh`: Scoped Google AI Overview citations refresh.
- `GET/POST /api/v1/rank-tracking/*`: Rank tracking projects, keywords, SERP history, and exports.
- `POST /api/v1/ai-content/*`: Section generation, AI rewriting, and suggestions.
- `POST /api/v1/ai-visibility/*`: Prompt simulation, sentiment analysis, and topic tracking.
- `GET/POST /api/v1/reports/*`: Audit reports, issues, pages, and PDF/Excel/CSV exports.
- `GET/POST /api/v1/search-performance`, `conversions`, `attribution`, `locations`: Measurement reporting.

### 5.4 Ingest & Webhooks
- `/px/*`: High-throughput tracking pixel ingest (CORS enabled, preflight handled).
- `/webhooks/dataforseo/*`: DataForSEO asynchronous crawl and SERP pingbacks.

---

## 6. Authentication, Authorization & Security

### 6.1 Dashboard Session Authentication
- Sign-in sends a 6-digit OTP to the user's email via ZeptoMail.
- Upon verification, CodeIgniter session stores `user_id`, `role`, and `logged_in = true`.
- `AuthFilter` intercepts requests, validates the session, reloads the database user record, and invokes `PlanAccess::requiresCheckout()` to redirect accounts with unpaid or expired subscriptions to `/payment`.

### 6.2 API Token Authentication
`ApiAuthFilter` supports two complementary authentication mechanisms:
1. **Bearer Token Authentication:** Used by external integrations and client JS calls. The token is minted on page load by `DashboardModule::generateApiToken()` and injected into `<meta name="api-token">`:
   $$\text{Token} = \text{base64}(\text{JSON}\{\text{uid}, \text{iat}\}) \,.\, \text{HMAC-SHA256}(\text{payload}, \text{WC\_ENCRYPTION\_KEY})$$
   Tokens are valid for 24 hours and verified using constant-time string comparison (`hash_equals`).
2. **Session Fallback:** When the `Authorization` header is omitted, `ApiAuthFilter` falls back to the dashboard session, allowing internal frontend scripts to interact with the API seamlessly.

### 6.3 Team Isolation & Role-Based Access Control (RBAC)
- **Roles:** `owner`, `admin`, `member`.
- **Workspace Isolation:** `TeamAccess::visibleUserIds()` determines the pool of user IDs accessible to the current user. Team members share access to workspace websites, rankings, and audits while keeping distinct client accounts segregated.
- **Plan Enforcement:** `PlanAccess` checks limits defined in `Config/SubscriptionPlans.php` (domain caps, monthly crawl limits, AI draft limits, team seat counts).
- **Module Permission Mapping:** The sidebar navigation in `app/Views/dashboard/layout/nav.php` dynamically filters items based on `wc_modules` and `wc_module_permission_mapping` matching the active plan.

### 6.4 Resilient CSRF Filter
`CsrfFilter` extends CodeIgniter's native CSRF handler. Instead of throwing an unhandled `SecurityException` upon token mismatch (such as after multi-tab usage or session expiry), it regenerates the token and redirects back with the user's input intact. Automated API routes, pixel ingest, and DataForSEO webhooks are exempt from CSRF checks.

---

## 7. Background Jobs & Automation Queue

Because the dev server environment disallows long-running supervisor daemons, asynchronous processing relies on database queuing:

```
[Trigger: User action / Schedule due]
                │
                ▼
      wc_automation_queue
      (pending → processing → completed / failed)
                │
                ▼
Cron Runner: webcrawlers_cron.sh (every 5 mins)
  ├─ spark automation:schedule  (find due website crawl schedules)
  ├─ spark automation:process   (claim pending queue rows & dispatch)
  └─ spark serp:metrics         (calculate SERP strength metrics)
```

- **Retry Policy:** Failed jobs retry up to 3 times with exponential backoff before being marked as `failed`.
- **Crawl Polling:** `php8.5 spark crawl:poll --limit=20` polls DataForSEO for running crawls and imports page data into `wc_audit_pages` upon crawl completion.

---

## 8. Core Functional Modules

### 8.1 Technical Audit & In-House Crawler
- Integrates both DataForSEO OnPage API and an internal PHP `CrawlEngine`.
- Tracks site health scores, HTTP status distributions, broken links, metadata deficiencies, canonical tags, and Core Web Vitals.
- Audits are stored in `wc_audits`, with individual URLs in `wc_audit_pages` and identified problems cataloged in `wc_audit_issues`.

### 8.2 Site Overview & Top Pages (Shared Dataset Architecture)
- Uses `DfsDatasetService` to cache and share DataForSEO Labs responses (`domain_rank_overview`, `ranked_keywords`, `relevant_pages`) across Site Explorer and Top Pages.
- **MySQL Named Locks:** Concurrent requests for the same dataset utilize `GET_LOCK()` to prevent redundant external billing; duplicate concurrent callers receive HTTP 409 or wait for cache release.
- **Scoped Refreshes:** Site Explorer defaults to refreshing core domain overview metrics only (`overview`), preventing expensive full re-crawls unless explicitly triggered by the user (`all`).
- **Google AI Overview Citations:** Top Pages provides a dedicated citation refresh endpoint (`/api/v1/top-pages/citations/refresh`) that extracts AI overview links without purchasing new organic ranking lists.

### 8.3 AI Content Engine & Analyzer
- **AI Content Generator:** Leverages OpenAI GPT with Google Gemini fallback to generate SEO articles, headers, meta descriptions, and section rewrites.
- **Content Scoring & Briefs:** Evaluates draft content against top SERP competitors, measuring keyword frequency, readability, heading hierarchy, and search intent.
- **AI Content Analyzer:** Analyzes live pages from the latest audit, producing targeted optimization recommendations that users can accept, reject, or edit in real time.

### 8.4 AI Visibility & Brand Monitoring
- Tracks brand mentions and sentiment across LLM search engines.
- Records simulated prompt questions, scrapes model answers, and tracks competitor visibility shares in `wc_ai_visibility_*` tables.

### 8.5 Opportunity Engine & Review Pipeline
- Analyzes audit issues, keyword gaps, and ranking drops to create actionable items in `wc_opportunities`.
- Automated drafts are generated in `wc_opportunity_drafts` and checked against brand guidelines (`wc_evidence_brand_rules`).
- Editorial approval workflow permits admins/owners to review, approve, reject, or schedule content changes.

### 8.6 Outcome Attribution & Tracking Pixel
- Proprietary pixel script (`public/px.js`) served directly from the platform.
- Records conversions, custom events, and performance vitals in `wc_pixel_*` tables.
- `AttributionMeasurement` pairs 14-day pre- and post-deployment cohorts to estimate traffic impact and correlate ranking changes with published content.

---

## 9. Database & Data Modeling

The platform database consists of **66 tables** (65 prefixed with `wc_*` plus the CodeIgniter `migrations` tracking table). The authoritative reference is maintained in [`schema.md`](schema.md).

### Key Table Groups

| Group | Primary Tables | Purpose |
| :--- | :--- | :--- |
| **Core & Users** | `wc_users`, `wc_countries`, `wc_workspace_settings`, `wc_otp_codes` | User credentials, roles, workspace options, OTP verification. |
| **Sites & Config** | `wc_websites`, `wc_website_integrations`, `wc_deployments` | Domains, verification tokens, crawling options, OAuth links. |
| **Competitors** | `wc_competitors` | Cross-module shared competitor tracking, domain metrics, ranking fallbacks. |
| **Audits & Pages** | `wc_audits`, `wc_audit_pages`, `wc_audit_issues` | Technical crawl history, page inventory, duplicate content similarity pairs, detected errors. |
| **Keywords & SERP** | `wc_seo_keywords`, `wc_tracked_keywords`, `wc_serp_snapshots`, `wc_serp_metric_jobs` | Keyword research library, rank tracking positions, SERP snapshots. |
| **DFS Cache** | `wc_dfs_datasets`, `wc_site_overview_cache`, `wc_dataforseo_logs` | Shared DataForSEO response store, raw JSON payloads, request costs, spend counters. |
| **AI Content** | `wc_ai_content`, `wc_ai_page_analyses`, `wc_ai_page_suggestions` | Generated drafts, page recommendations, edit histories. |
| **AI Visibility** | `wc_ai_visibility_projects`, `wc_ai_visibility_queries`, `wc_ai_visibility_responses`, `wc_ai_visibility_competitors` | LLM prompt monitoring, sentiment scoring, share of voice. |
| **Opportunities** | `wc_opportunities`, `wc_opportunity_drafts`, `wc_opportunity_signals` | Algorithmic improvement backlog, content review workflow. |
| **Evidence & QA** | `wc_evidence`, `wc_evidence_pages`, `wc_evidence_services`, `wc_evidence_reviews`, `wc_evidence_brand_rules` | Trust credentials, customer reviews, brand voice guardrails. |
| **Tracking Pixel** | `wc_pixel_views`, `wc_pixel_events`, `wc_pixel_vitals` | Client website visitor sessions, conversion actions, Core Web Vitals. |
| **Subscriptions** | `wc_subscription_plans`, `wc_subscription`, `wc_subscription_history`, `wc_cancel_subscriptions` | Sticky.io billing plans, customer tokens, payment records. |
| **Background Ops**| `wc_automation_queue`, `wc_notifications`, `wc_activity_events` | Asynchronous task scheduling, system alerts, user audit logs. |

---

## 10. External Integrations

| Provider | Purpose | Configuration Constant | Responsible Service |
| :--- | :--- | :--- | :--- |
| **DataForSEO** | Technical audits, SERP rank tracking, Labs research, Backlink analysis, Duplicate content | `WC_DATAFORSEO_LOGIN`<br>`WC_DATAFORSEO_PASSWORD`<br>`WC_DATAFORSEO_API_KEY` | [`DataForSeo`](file:///var/www/php85/koushik/webcrawlers_latest.com/app/Libraries/DataForSeo.php)<br>[`DfsDatasetService`](file:///var/www/php85/koushik/webcrawlers_latest.com/app/Libraries/DfsDatasetService.php) |
| **OpenAI** | Primary content generation, content brief scoring, page analysis | `WC_OPENAI_API_KEY`<br>`WC_OPENAI_MODEL` | [`AiContentService`](file:///var/www/php85/koushik/webcrawlers_latest.com/app/Libraries/AiContentService.php)<br>[`AiContentAnalyzerService`](file:///var/www/php85/koushik/webcrawlers_latest.com/app/Libraries/AiContentAnalyzerService.php) |
| **Google Gemini** | Fallback LLM provider for content generation | `WC_GEMINI_API_KEY`<br>`WC_GEMINI_MODEL` | [`AiContentService`](file:///var/www/php85/koushik/webcrawlers_latest.com/app/Libraries/AiContentService.php) |
| **Google APIs** | Search Console (GSC), GA4 analytics, Google Business Profile (GBP) reviews | `WC_GOOGLE_CLIENT_ID`<br>`WC_GOOGLE_CLIENT_SECRET`<br>`WC_GOOGLE_REDIRECT_URI` | [`GoogleApiService`](file:///var/www/php85/koushik/webcrawlers_latest.com/app/Libraries/GoogleApiService.php)<br>[`GoogleSearchDataService`](file:///var/www/php85/koushik/webcrawlers_latest.com/app/Libraries/GoogleSearchDataService.php)<br>[`GoogleAnalyticsDataService`](file:///var/www/php85/koushik/webcrawlers_latest.com/app/Libraries/GoogleAnalyticsDataService.php) |
| **Sticky.io** | Recurring subscription billing, card payments, invoice history | `WC_STICKY_API_URL`<br>`WC_STICKY_API_USERNAME`<br>`WC_STICKY_API_PASSWORD` | [`StickyLibrary`](file:///var/www/php85/koushik/webcrawlers_latest.com/app/Libraries/StickyLibrary.php) |
| **ZeptoMail** | Transactional emails (OTP sign-in, invitations, alerts) | `ZEPTOMAIL_API_URL`<br>`ZEPTOMAIL_API_KEY` | [`Otp`](file:///var/www/php85/koushik/webcrawlers_latest.com/app/Libraries/Otp.php)<br>[`UserController`](file:///var/www/php85/koushik/webcrawlers_latest.com/app/Controllers/UserController.php) |

---

## 11. Current Development Branch Context

**Current Branch:** `wc-suggestions` (tracked with `origin/release/develop`)  
**Key Completed Improvements:**
- **Audit Reports & Issues:** Human-readable HTTP status text (`200=OK`, `301=Moved Permanently`), broken sub-resources inspection with live status codes, non-indexable and XML sitemap diagnostic details, and on-demand duplicate content comparison with SimHash similarity scores.
- **Competitors & Backlink Gap:** Unified `wc_competitors` storage, `/competitors/{website_id}` routing, active-tab state persistence, automatic initial data fetch, and Backlink Gap domain intersection analysis.
- **Top Pages & Shared DFS Infrastructure:** Centralized `DfsDatasetService` dispatcher with tiered TTLs (14d backlinks, 7d competitors/pages, 3d domain overview, 2d keywords, 24h fallback), in-flight mutex coalescing, live spend counters (`php8.5 spark dfs:datasets`), and hidden non-functional device dropdown.
- **Search Performance & Keyword SERP:** Clear GSC connection requirement guidance for custom date ranges, shared SERP snapshot reuse across modules, and background metric enrichment.
- **Maintenance:** Owner-only CodeIgniter log viewer at `/settings/logs`, CI4 controller standardizations, and full standalone test suite.

### Validated Standalone Test Commands
The test suite contains 17 network-isolated verification scripts that execute directly on the server:

```bash
# Verify Competitors & Backlink Gap workflows
php8.5 tests/standalone/competitors.php
php8.5 tests/standalone/backlink-gap.php
node tests/standalone/backlink-gap-ui.js

# Verify Audit Reports duplicate content & crawl coverage
php8.5 tests/standalone/reports-duplicate-content.php
php8.5 tests/standalone/crawl-coverage.php

# Verify DataForSEO shared dataset caching & lock mechanisms
php8.5 tests/standalone/dfs-datasets.php
php8.5 tests/standalone/dfs-datasets-database.php

# Verify Top Pages cached enrichment, citations, and client reload
php8.5 tests/standalone/top-pages-enrichment.php
php8.5 tests/standalone/top-pages-citation-refresh.php
node tests/standalone/top-pages-reload.js

# Verify Site Explorer scoped refresh & Brand Insights
php8.5 tests/standalone/site-overview-refresh.php
node tests/standalone/site-overview-brand.js

# Verify Measure periods, currency conversions, and attribution cohorts
php8.5 tests/standalone/measure.php
php8.5 tests/standalone/measure-google-cache.php
php8.5 tests/standalone/measure-database.php

# Verify Search Performance view contracts
php8.5 tests/standalone/search-performance-view.php

# Verify Public Homepage & Navigation CTA switching for subscribed users
php8.5 tests/standalone/homepage-subscription-cta.php
```

All 17 standalone tests pass cleanly without external HTTP calls.

---

## 12. Known Technical Debt & Recommendations

1. **Credentials Stored in Version Control:**
   - Active third-party API keys currently reside in `app/Config/Constants.php`.
   - *Recommendation:* Prior to any production rollout, transfer all secrets to server environment variables or a `.gitignore`d `.env` file, and rotate all existing keys.
2. **First-Run Table Migrations (Resolved):**
   - Migrations for evidence tables, `wc_dfs_datasets`, and `wc_competitors` are fully applied, establishing strict schemas across all environments.
3. **Controller Inheritance Standardization (Resolved):**
   - Controllers extend `BaseApiController` or `DashboardModule`, standardizing response formatting (`ok()`, `error()`, `notFound()`) across all REST endpoints.
4. **Log Viewer (Resolved):**
   - Owner-accessible log inspection UI is available at `/settings/logs`, eliminating the need to SSH onto servers to diagnose operational issues.
5. **Documentation & Git Tracking:**
   - Active documentation files (including `docs/project.md`, `README.md`, `schema.md`, `docs/DFS-plan.md`, `docs/TASKS-Improvemnet-plan.md`, and `docs/DFS-dependency-reduction-roadmap.md`) are kept synchronized with code architecture.

