# Changelog

All notable changes to Deployra will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.5.1] - 2026-11-01

### 🐛 Fixes
- **Deployments stuck in `queued`**: the job worker used workmatic's default 30s lease, which is never renewed. Any deployment longer than 30s was re-claimed repeatedly; the copies filled every worker slot behind the project chain, starving all other deployments, and later re-ran the finished deployment. The lease now defaults to 6 hours (`DEPLOYRA_JOB_LEASE_MS` overrides it), duplicate deliveries of a running deployment are dropped immediately, and only `queued` deployments are ever executed.
- A job picked up without a configured pipeline runner now marks its deployment `failed` instead of leaving it `queued`.

### 🛡️ Self-Repair
- **Service healing no longer breaks units**: crashed services are started from their existing systemd unit instead of being re-registered, so zero-downtime services stay in supervisor mode and keep their env. Start-limit `failed` units are reset first.
- **Backoff, limit and alert**: failed recoveries are retried with exponential backoff (30s → 15m); after `selfRepair.maxRestarts` consecutive failures Deployra gives up and sends one failure notification instead of restarting every 30s forever.
- **Health-based recovery**: running services whose `deploy.ready` checks fail `selfRepair.healthFailureThreshold` times in a row are restarted; every recovery is verified with the ready checks.
- **New `selfRepair` config** (`enabled`, `healthCheck`, `healthFailureThreshold`, `maxRestarts`) to tune or disable healing per project.
- **Watchdog safety**: cycles never overlap; running deployments the worker still owns are no longer failed after 15 minutes; queued deployments never picked up (with free worker slots) are failed so the watcher retries them.
- **Failed commit retries** use an exponential cooldown (1m, 2m, 4m) instead of a fixed 60s.

---

## [0.5.0] - 2026-10-31

### ⚠️ Breaking
- **Webhooks require a secret by default**: requests are rejected with `401` when neither `webhook.secret` nor `DEPLOYRA_WEBHOOK_SECRET` is set. Set `webhook.allowUnsigned: true` to keep accepting unsigned webhooks.
- **Runtime env reaches the service**: `deploy.env` and `deploy.envFile` are now passed to the managed service (`Environment=` / `EnvironmentFile=`), not only to build commands. Zero-downtime services are re-registered once (brief restart) when this env changes.

### 🐛 Fixes
- **Zero-downtime migration**: a public port held by the service's own non-zero-downtime unit is migrated to supervisor mode instead of failing pre-flight; Deployra waits for the supervisor IPC socket before deploying.
- **No downtime from `install` in zero-downtime mode**: the supervisor is no longer stopped before `install`, and `stopBeforeBuild` is ignored with a warning. A registered but stopped supervisor is started under systemd instead of deploying inside the Deployra process.
- **Rollback only undoes what changed**: failures before the workspace reset (e.g. pre-flight) no longer roll back; zero-downtime generations are only switched back if the service action ran; the service is not restarted when the failed deployment never touched it.
- **Rollback rebuilds like a deployment**: rollback `install`/`build` commands get `deploy.env`, `envFile`, `CI=true` and `deploy.timeout`.
- **Isolated sync keeps runtime files**: `rsync --delete` no longer removes `.env`, `.env.*`, `deploy.envFile` or paths listed in the new `deploy.syncExclude`. The copy fallback no longer skips `.github` / `.gitignore`.
- **Project lock heartbeat**: locks are refreshed every 30s, so builds longer than 5 minutes cannot be overtaken by a second deployment.
- **Safe superseding (`queueMode: latest`)**: a deployment that already stopped or switched the service runs to completion instead of being aborted halfway; an explicitly cancelled deployment restores the service.
- **Pre-flight uses the committed config**: the port check re-runs after `refresh-config` when the config changed and honours `service.zeroDowntime`.
- **Cancellation detection** no longer treats any error message containing "cancelled" as a cancellation (which skipped rollback).
- **Command output** keeps the last 10 MB instead of the first, so build errors at the end of long logs are preserved.

---

## [0.4.5] - 2026-10-18

### 🛡️ Port Conflict Prevention, Self-Healing & Supervisor Defense
- **Pre-Flight Zero-Downtime Port Availability Defense**:
  - Added `src/security/port-check.ts` providing `isPortOccupied` and `checkZeroDowntimePort(serviceName, port)`.
  - Added `portCheck: boolean` to `preflight` configuration (enabled by default).
  - During Step 1 (`prepare-workspace`), Deployra now verifies that the configured public zero-downtime port is either completely free or owned by the project's own Unitup supervisor via IPC socket handshake. If occupied by an unmanaged foreign process, deployment fails fast with `PreflightError`, preventing systemd service crash loops.
- **Port Environment Variable Linter & Guidance**:
  - Added pre-flight detection for hardcoded `PORT=xxxx` overrides in custom build/start commands, warning the user that zero-downtime applications must dynamically bind to `process.env.PORT` provided by Unitup's supervisor.
- **UnitupAdapter Fast-Fail Circuit Breaker**:
  - Enforced active port collision verification inside `UnitupAdapter.deployZeroDowntime()` before creating or upserting systemd services, stopping unrecoverable collisions before touching systemd.
- **Unitup v0.4.1 Dependency Upgrade**:
  - Upgraded to `unitup` `^0.4.1` with supervisor TCP connectivity health checks, automated generation self-healing to eliminate `502 Bad Gateway (ECONNREFUSED)`, and POSIX code 78 (`RestartPreventExitStatus=78`) systemd rate-limit crash breakers.
- **Test Suite Hardening**:
  - Increased integration test timeouts in `test/release-strategy.test.ts` to prevent flakiness during multi-release test executions.

---

## [0.4.4] - 2026-10-18

### 🚀 Enhancements & Zero-Downtime Reliability
- **Unitup v0.4.0 Integration**:
  - Upgraded `unitup` dependency to `^0.4.0`, bringing concurrent multi-port routing isolation, strict port-scoped traffic dispatching, and zero cross-service collision.
- **Dynamic Service Registration Check**:
  - Enhanced `UnitupAdapter.deployZeroDowntime()` to inspect `readAppMetadata(service)` before skipping service registration.
  - Automatically re-upserts services if the existing systemd unit lacks zero-downtime supervisor configuration or if the configured public port has changed.
- **Release CI/CD Hardening**:
  - Added `.litepacks-release-tools/` to `.gitignore` to ensure clean release runs.

---

## [0.4.3] - 2026-10-16

### 🛡️ Daemon Reliability, Watcher Live-lock & Log Flooding Fixes
- **Watcher In-Flight Protection & Live-lock Prevention**:
  - Replaced `checkingProjects: Set<string>` with `Map<string, InFlightCheck>` tracking execution start time, timeout timer, and `AbortController`.
  - Added in-flight protection to `syncProjects()` so in-flight projects are never marked stalled or rescheduled with a 0ms thundering loop.
  - Implemented 45-second zombie timeout enforcement that aborts child processes, clears locks, and backs off gracefully.
  - Throttled repetitive "already in progress" logs to at most once per 5 minutes per project.
- **Log Level Filtering & Systemd Journal Rate Limiting**:
  - Added strict log level priority (`debug: 0, info: 1, warn: 2, error: 3, silent: 4`) to suppress high-frequency debug output in production.
  - Defaulted log level to `info` in systemd and daemon modes.
  - Added systemd journal rate-limiting directives (`LogLevelMax=info`, `LogRateLimitIntervalSec=10s`, `LogRateLimitBurst=200`, `LOG_LEVEL=info`) to generated service units.
- **Git Timeout Enforcement**:
  - Added default 30s timeout across all Git commands and wired `AbortSignal` into `checkRemoteHead` and `fetchBranch`.

### ⚡ Systemic Resource Leak & Reliability Hardening
1. **Cancelled Deployments Infinite Retry Fix**:
   - Explicitly handled `cancelled` deployments in `SourceWatcher` to prevent automated polling retries.
   - Updated `DeploymentRepository.countRecentFailures` to accurately include `cancelled` alongside failures.
2. **SQLite WAL Checkpointing & Automatic Compaction**:
   - Added `PRAGMA wal_checkpoint(TRUNCATE)` and `VACUUM` into `vacuumDatabase()`.
   - Wired `vacuumDatabase()` into the daemon's periodic auto-retention cycle to prevent SQLite disk bloat.
3. **Orphan Release Directory Cleanup**:
   - Added automatic purge of failed/cancelled `releases/<deploymentId>` directories when `current` symlink does not point to them.
4. **Step Output Truncation (Heap OOM Prevention)**:
   - Added `MAX_STEP_OUTPUT_CHARS = 250_000` (~250 KB) tail-preserving output truncation in `runStep` to prevent huge build outputs from exhausting Node.js heap memory or bloating SQLite.
5. **Fresh Git Lock Preservation**:
   - Added `maxAgeMs` parameter to `repairStaleLocks` and enforced a 15-second age threshold on lock contention to avoid wiping locks belonging to actively running Git processes.
6. **Systemd D-Bus Query Resilience**:
   - Marked transient systemctl/D-Bus errors as `subState: 'query_failed'` and guarded daemon watchdog against false positive service restart loops.
7. **Ghost Timer Prevention on Watcher Stop**:
   - Added `isStopped` lifecycle state guards in `SourceWatcher` to prevent lingering callbacks from reviving timers after `stop()`.

---

## [0.4.1] - 2026-09-21

### 📚 Documentation & Developer Experience
- **Docboot Documentation Site**:
  - Integrated **Docboot v0.4.0** with the `ocean` theme preset, local client search, and GitHub source links.
  - Authored 10 comprehensive documentation guides in `docs/`:
    - `docs/index.md`: Architecture overview, core highlights, and system workflow.
    - `docs/getting-started.md`: Installation, interactive setup (`deployra init`), and systemd daemon service.
    - `docs/architecture.md`: Deep dive into Watcher, Workmatic Queue, Execution Pipeline, SQLite State, and Watchdog subsystems.
    - `docs/configuration.md`: Full `deployra.config.yaml` schema, environment overrides (`DEPLOYRA_ENV`), and variable expansion.
    - `docs/deployment-strategies.md`: Detailed guide to `in-place`, `isolated`, `release`, and `zero-downtime` strategies.
    - `docs/zero-downtime.md`: Unitup generation switching, canary traffic routing, and instant rollback.
    - `docs/cli.md`: Comprehensive reference for all 15 CLI commands with usage examples.
    - `docs/webhooks.md`: Built-in HTTP webhook receiver with GitHub HMAC-SHA256 and GitLab token verification.
    - `docs/self-repair.md`: Autonomous watchdog, stale lock auto-recovery, and process group management.
    - `docs/benchmarks.md`: SoftScope profiling metrics, caching mechanisms, and performance results.
  - Added dedicated documentation scripts to `package.json`: `docs:dev`, `docs:build`, `docs:serve`, and `docs:doctor`.
  - Verified documentation health via `docboot doctor` (10 pages, 65 internal links, 0 broken links).

### 🚀 CI / CD & Automation
- **Litepacks Release Pipeline**:
  - Added `.github/workflows/release.yml` utilizing the centralized `litepacks/.github/.github/workflows/npm-release.yml@main` workflow.
  - Automated tag-driven releases (`v*`) with pre-flight version validation, lint checks, typecheck validation, test suite execution, production bundling (`tsup`), docboot gate (`run-docboot: auto`), dry-run pack validation, NPM trusted publishing with provenance, and GitHub Release generation.
- **GitHub Pages Continuous Deployment**:
  - Added `.github/workflows/docs.yml` to automatically build and deploy the documentation site (`dist-docs`) to GitHub Pages on every push to `main`.
  - Removed deprecated legacy workflows (`npm-publish.yml` and `static.yml`).

### 📦 Package & Metadata
- Added `repository`, `bugs`, and `homepage` metadata fields to `package.json`.
- Added `typecheck` script (`tsc --noEmit`) to `package.json` for CI validation.

---

## [0.4.0] - 2026-09-20

### 🚦 Zero-Downtime & Canary Deployments
- **Unitup v0.3.0 Integration**:
  - Upgraded `unitup` dependency to `^0.3.0` introducing generation-based process supervision and HTTP router traffic shifting.
  - Added `strategy: zero-downtime` with public entry port routing (`deploy.port`) and graceful connection draining (`deploy.drainTimeout`).
  - **Canary Releases**: Added canary traffic weighting support (`deployra deploy --canary --weight 20`) to test new commits with a fraction of live traffic before full cutover.
  - **Canary Promotion**: Added `deployra promote [projectName]` CLI command to promote active canary generations to 100% traffic.
  - **Zero-Downtime Rollback**: Instant generation rollback via Unitup without modifying unaffected services.

### ⚡ Performance & Profiling Optimizations (SoftScope Profiled)
- **Hot Path Prepared Statement Caching**:
  - Migrated state repository (`project_locks`) and deployment repository queries to global `getPreparedStatement` cache.
  - 100 complete lock acquire/release cycles execute in **12.67ms**.
- **Lightweight Step Cancellation & Status Checks**:
  - Replaced heavy `getDeployment` hydration inside `runStep` with `getDeploymentStatus` and `getDeploymentStartedAt`.
  - Completely eliminated 15,000 redundant `stepRows.map` allocations per 100 deployment runs.
- **Watcher Disk I/O & Config Caching**:
  - Added file `mtimeMs` cache to `SourceWatcher` to skip re-reading and parsing `deployra.config.yaml` on every 5s polling cycle (<5µs per check).
  - Replaced full deployment fetches with lightweight `countRecentFailures` and `getActiveDeploymentSummaries` queries.
- **Reactive Git Lock Recovery**:
  - Removed proactive synchronous disk checks before every Git CLI operation; converted to purely reactive self-repair on error contention in `execGit`.
- **Subprocess Environment Optimization**:
  - Optimized `safeExec` to pass `process.env` directly when no custom variables are specified, eliminating redundant shallow-cloning of 100+ environment variables.
- **High-Throughput Secret Redaction**:
  - Optimized `maskSecrets` with a single compiled `COMBINED_SECRET_PATTERN` regular expression, processing 20,000 log lines in **21.08ms** (+54% faster).
- **SQLite Index Optimization**:
  - Added composite index `idx_deployments_proj_status ON deployments(project_name, status, created_at DESC)`.

### 🔄 Dependencies
- Upgraded `workmatic` to `^1.2.0` with SQLite WAL mode and persistent lease-based job claim.

---

## [0.3.0] - 2026-09-19

### 🛡️ Enterprise Features & Self-Repair
- **Autonomous Watchdog Engine**:
  - Added background watchdog cycle to prune abandoned SQLite locks, clean timed-out deployments, and auto-heal crashed services.
  - Added automated failed deployment retries with exponential backoff and cooldown.
- **Clean Subprocess Termination**:
  - Implemented POSIX process group termination (`killProcessTree`) to eliminate orphaned child processes.
- **Symlink Release Strategy**:
  - Added `strategy: release` with timestamped release folders, atomic symlinks, and automatic release pruning (`releasesToKeep`).
- **Webhooks & Multi-Channel Alerting**:
  - Added built-in HTTP webhook receiver with GitHub HMAC-SHA256 and GitLab secret token verification.
  - Added notifications for Slack, Discord, Telegram, and generic HTTP webhooks.
