# Changelog

All notable changes to the SkillFoundry Framework will be documented in this file.

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

---

## [5.17.0] - 2026-06-04

### Codebase Comprehension Pre-Flight (Code Map)

v5.17.0 adds a **codebase comprehension pre-flight** — a tree-sitter-powered Code Map that gives agents a structural model of existing code *before* they write, directly attacking the framework's #1 failure class (Frontend-Backend Contract Mismatch). It complements the environment pre-flight: that one inspects the *environment*, this one inspects the *code*.

#### Added

- **`sf_codemap` MCP tool** (`mcp-server/src/agents/codemap/` + `codemap-agent.ts`) with four modes:
  - `build` — full tree-sitter parse of TS/JS + Python into a node/edge graph (files, functions, methods, classes, exports; `contains` + same-file `calls` edges).
  - `refresh` (default) — incremental rebuild keyed off sha256 content hashes; re-parses only changed files.
  - `query` — look up a symbol/file and return its node + related edges.
  - `diff-impact` — blast-radius of the working-tree diff (reverse BFS over imports/calls, cycle-safe).
- **API contract surface extraction** → `endpoints[]` (method, canonical `:param` path, handler node, FastAPI Pydantic request shapes) for Express/Fastify/Hono/Koa-router, Next.js App Router, NestJS, FastAPI, and Flask.
- **Import graph + `unresolvedImports[]`** — relative + tsconfig-alias + dependency-classification + Python-relative resolution.
- **DB/layer map** — `model` nodes (Prisma block-parser, Drizzle, Mongoose, TypeORM, SQLAlchemy) with fields; deterministic `db`/`backend`/`frontend`/`shared` layer tags on 100% of files.
- **Optional LLM semantic labels** (`semantic:true`) — off by default, `confidence:"llm-hint"`, fact-only prompts, non-authoritative (never satisfies Three-Layer verification).
- **`/preflight` command** (alias `/codemap`) + `agents/_codemap-preflight-protocol.md`, referenced from `CLAUDE.md`.
- **Dashboard Code Map explorer** — loopback-only `/api/codemap` + `/api/codemap/diff-impact` routes and a responsive "Code Map" tab (layer columns, fuzzy search, diff-impact overlay, file detail panel).
- **memory_bank feed** — sanitized, deduped `code-map` facts (API surface, model inventory, unresolved-import hotspots, layer distribution) for cross-project learning.
- New dependencies (pure WASM, no native build — `npm ci` stays portable): `web-tree-sitter@^0.24.7`, `tree-sitter-wasms@^0.1.13`.
- 61 new tests across 12 suites (engine, tool, gate handoff, dashboard).

#### Changed

- **`/forge` & `/go` IGNITE** now run the codebase pre-flight (`sf_codemap refresh`) after the environment pre-flight, handing `endpoints[]` to `sf_contract_check` and `unresolvedImports[]` to `sf_import_validator` as a baseline. Advisory — a code-map failure logs a warning and never blocks a run.
- **`checkContracts(projectPath, baseline?)`** and **`validateImports(projectPath, baseline?)`** accept an optional Code Map baseline; behavior is byte-for-byte unchanged when none is supplied.
- Dashboard server now binds `127.0.0.1` by default (`DASHBOARD_HOST`).
- Tool-agent count 22 → 23 (`sf_codemap`).

#### Security

- Code Map is read-only and never executes/imports the target code (tree-sitter parse only).
- Dashboard routes are loopback-only and path-traversal guarded; memory-feed records are sanitized (no absolute paths/secrets).
- Semantic labels are non-authoritative and excluded from gate/Three-Layer verification.

#### Why

AI agents reasoned about existing code blind, re-discovering structure ad hoc each session and inventing endpoint shapes they never read — the documented #1 vibe-coding failure. The Code Map makes that structure available proactively and feeds it to the gates before code is written.

#### Deferred (tracked follow-ups)

Django `urls.py` routes; zod/TS-type/NestJS-DTO request shapes; ORM field extraction beyond Prisma/Drizzle; diff-impact base-ref param; semantic `domain` label + cost-router/budget routing; cross-platform mirroring of `/preflight`; medium-repo perf benchmark.

---

## [5.16.0] - 2026-05-31

### Grok: 6th Platform + Provider Refresh

v5.16.0 adds **xAI Grok Build** as the sixth install platform (joining Claude Code, Copilot, Cursor, Codex, and Gemini) and refreshes the `xai` LLM provider to the current Grok model lineup. Grok Build reads `AGENTS.md` + Anthropic-format `SKILL.md` skills, so it consumes the same artifacts SkillFoundry already produces for Codex.

#### Added

- **Grok Build platform** in `install.sh` and `update.sh` — interactive menu option `6) Grok Build`, `--platform=grok`, validation, "all platforms" expansion, existing-install detection, overwrite warnings, version stamping, cleanup, manifest, and update/compare paths. Installs `AGENTS.md` to the target root and 95 `SKILL.md` skills into `.grok/skills/`.
  - Skills are sourced from the existing `.agents/skills/` (no duplicate skill files in the repo) and installed into the target's `.grok/skills/`.
- **Current Grok model lineup** in the `xai` provider (`sf_cli`):
  - Default model `grok-3` → **`grok-4.3`**; added `grok-4.20-0309-reasoning`, `grok-4.20-0309-non-reasoning`, `grok-4.20-multi-agent-0309`, and `grok-build-0.1` to the model picker, capability tiers (all Tier 1), token pricing, and context-window table (1M for the 4.x line, 256K for `grok-build-0.1`).
  - Real Grok pricing in `MODEL_PRICING` — previously Grok cost estimates silently fell back to the GPT-4o rate.

#### Changed

- Platform count `5` → `6` across installer banners, README badge/IDE lists, and `AGENTS.md` header (`Penta-Platform` → `Hexa-Platform`).
- README provider table and `docs/USER-GUIDE-CLI.md` now show `grok-4.3` as the xAI default.

#### Why

xAI shipped the Grok Build coding-agent CLI (beta), which loads `AGENTS.md`, Anthropic Skills, and MCP servers out of the box — making it a first-class skill-file consumer like the other five platforms. Separately, xAI retired the `grok-3`/`grok-4`/`grok-4.1`/`grok-code-fast-1` slugs on 2026-05-15 (they redirect to `grok-4.3`), so the provider's defaults and pricing were stale.

#### Note

The Grok skill install target is `.grok/skills/` (matching Grok Build's `.grok/` config namespace). `AGENTS.md` discovery is confirmed; the exact skills directory should be verified with `grok inspect` and is a one-line change if it differs.

---

## [5.15.0] - 2026-05-16

### Coding Discipline Protocol

v5.15.0 adds a framework-wide behavioral guardrail file — `agents/_coding-discipline.md` — referenced from the project `CLAUDE.md` header alongside the existing protocol pointers. The protocol layers on top of the existing *Philosophy*, *Mandatory Production Rules*, and *Three-Layer Enforcement* sections without overriding them. Where the protocol and the project rules differ, the stricter rule wins.

#### Added

- **`agents/_coding-discipline.md`** — Four-section behavioral guardrail applied on every implementation task:
  1. *Think Before Coding* — surface assumptions, ask before silent reinterpretation, present alternatives.
  2. *Simplicity First (scoped)* — minimum code for the request; explicitly does **not** override Three-Layer Enforcement, boundary validation, or the project's mandatory production guards.
  3. *Surgical Changes* — touch only what the request requires; clean up only orphans your changes created.
  4. *Goal-Driven Execution* — define verifiable success criteria, loop until verified.
- **Header reference in `CLAUDE.md`** — new pointer line next to `_env-preflight-protocol.md` so all agents pick up the protocol on session start.
- **Skip list** — trivial edits (typo, single-line config, version bump), read-only investigation, and mechanical housekeeping are exempt from the protocol; matches the existing *Skill Scope Boundaries* / *Complexity-Based Scope* rules.

#### Why

Karpathy-style behavioral guidelines were available as a standalone skill but had no always-on home in the project. Adding them as a referenced protocol file (matching the `_env-preflight-protocol.md` pattern) makes the rules active on every implementation task without bloating `CLAUDE.md` itself and without needing the user to invoke a skill.

#### Not Changed

No code paths, no MCP server logic, no pipeline phases, no agent registry. Documentation/behavior only.

---

## [5.14.0] - 2026-05-13

### MCP Server Security Hardening

v5.14.0 closes every security gap in the MCP server identified by a full BPSBS audit. All 11 BPSBS controls now pass. No functional changes — this is a hardening-only release.

#### Added

- **Bearer token auth** — Auto-generated `sf_*` token on first run (saved to `data/.api-token`, mode `0o600`). Always enforced on `/mcp` and `/api/v1`. Token and ready-to-paste MCP config snippet printed to console on startup. Override with `SKILLFOUNDRY_API_TOKEN` env var.
- **Rate limiting** — `express-rate-limit`: 300 req/min on MCP transports (`/mcp`), 500 req/min on REST API (`/api`).
- **CORS** — Explicit `cors()` middleware. Default origin: `http://localhost:3666`. Override with `SKILLFOUNDRY_CORS_ORIGIN`.
- **`MAX_PAGE_SIZE = 500`** — Enforced on all list queries in `db.ts`. Applies to `queryQuirks`, `getCertifiedSkills`, `listDynamicSkills`, `getFleetHealth`, `querySessionRecordings`, `getSessionTranscripts`, `queryPlatformInsights`, `queryProjectArtifacts`, `getDeviationRules`, `getCorrectionPatterns`.
- **`rowToSessionTranscript()` mapper** — `getSessionTranscripts` previously cast raw DB rows directly (`as SessionTranscriptRecord[]`), leaking `id` and `parsed_at` columns to callers. Now uses an explicit mapper that strips DB-internal columns.
- **Atomic session writes** — `saveSession` now writes to `.tmp` then `renameSync`. Prevents partial-write file corruption on concurrent saves.
- **`handleRouteError()` utility** — Centralises all 8 route catch blocks. Returns generic `"An internal error occurred"` in production; returns the real `err.message` only when `NODE_ENV=development`.
- **Negative auth tests** — 3 new test cases: no token → 401, wrong token → 401, `/health` public → 200. All 64 tests pass.

#### Breaking Change

MCP clients must include an `Authorization` header. On first boot the server prints the ready-to-paste config:

```json
"mcpServers": {
  "skillfoundry": {
    "url": "http://localhost:9877/mcp/sse",
    "headers": { "Authorization": "Bearer <token>" }
  }
}
```

The token is stable across restarts (read from `data/.api-token`). Rotate it by deleting the file or setting `SKILLFOUNDRY_API_TOKEN`.

#### Dependencies Added

- `cors@^2.8.6`
- `express-rate-limit@^8.5.1`
- `@types/cors@^2.8.x` (devDependency)

---

## [5.13.0] - 2026-05-13

### Pipeline Quality — 11 Framework Enhancements

v5.13.0 hardens every layer of the SkillFoundry pipeline: PRD validation before implementation, dependency-ordered execution waves, GuardLoop blocking done/ promotion, token budget forecasting, cross-platform parity detection, skill hot-reload, secret scan in the knowledge harvester, model tier declarations, update.sh rollback capability, and MCP Streamable HTTP transport.

#### Added — PRD Linter (`/prd-lint`)

New skill + script that validates `genesis/*.md` files before `/go` or `/forge` runs on them. 12 structural checks:

- Front matter starts with `---` on line 1
- Required fields: `prd_id`, `title`, `status`, `created`, `author`
- `layers:` not empty
- Required sections: §1–§5, §7–§11
- No `TBD`/`TODO` markers outside HTML comment blocks
- No vague language (`might`/`maybe`/`possibly`/`somehow`)
- Unchecked `[ ]` checkboxes (unverified dependencies)
- §6 Contract Specification: if present, must not be empty
- §8 Regression Surface: must have ≥1 data row
- §11.1 DoD: must include `/guardloop` scan item
- §2 User stories: must have `FR-IDs` column

`/go` now runs `/prd-lint` as **Phase 1.5** (lint gate) before implementation. PRDs with errors are blocked; PRDs with only warnings proceed with caution.

Exit codes: `0`=clean, `1`=warnings, `2`=errors. `--strict` flag treats warnings as errors.

#### Added — PRD Dependency Ordering in `/go`

`/go` gains **Phase 2.5: PRD Dependency Ordering** — topological sort of PRDs by their `dependencies.requires` front matter field into sequential execution waves. Foundation PRDs execute first; independent PRDs in the same wave execute in parallel.

- `scripts/prd-wave-plan.sh` — standalone script (Python3 heredoc) that computes the wave plan. Outputs human-readable table or `--json` for pipeline use.
- Cycle detection with clear error message and the affected PRD IDs.
- Already-`COMPLETED`/`DONE` PRDs are skipped automatically.
- `--ignore-deps` flag bypasses wave ordering when needed.

#### Added — GuardLoop Gate on `done/` Promotion

`scripts/move-story.sh` now runs a GuardLoop pattern check before transitioning any story to `done/`. If any CRITICAL-severity pattern (hardcoded secret, localStorage token, file corruption) has a non-zero count in `guardloop-patterns.json`, the transition is refused with exit code 6 and a clear message listing the offending patterns. Override with `--no-guardloop-gate`.

#### Added — Token Budget Forecasting

`token-tracker.ts` extends `SessionTokenReport` with a `TokenForecast` field (populated after ≥2 minutes of session data):

- `tokensPerMinute` — current burn rate
- `projectedAt60min` / `projectedAt120min` — extrapolated totals at 1h and 2h
- `minutesUntilWarning` / `minutesUntilCritical` — time to 200K/500K thresholds
- `budgetHealthPct` — percentage of the 500K critical budget remaining

#### Added — Cross-Platform Parity Detector (`/parity`)

New `scripts/parity-check.sh` + `.claude/commands/parity.md` skill. Compares `.claude/commands/` (reference) against Copilot, Cursor, Codex (`.agents/skills/`), and Gemini. Reports:

- Presence gaps per platform (missing skills)
- H1 title drift (content divergence between platforms)
- Parity % score per platform

Flags: `--missing`, `--drift`, `--json`, `--skill <name>`.

#### Added — Skill Hot-Reload in MCP Server

The MCP server now watches skill directories (`SKILL_DIRS`) with `fs.watch` and a 400ms debounce. When a `.md` file is saved, added, or deleted, the live `skills` map updates in place — no restart required. `loader.ts` gains `reloadSkill(filePath, skills)` for incremental reload.

#### Added — Secret Scan in Knowledge Harvester

`harvester.ts` now runs a 7-pattern secret scan on all content before inserting it into the SQLite knowledge store. Patterns: AWS access keys, JWTs, Bearer tokens, API key assignments, password assignments, secret/token/credential assignments, private key headers. Matches are redacted to `[REDACTED-BY-HARVESTER]` and logged as warnings. `HarvestResult` gains `secretsRedacted` count.

#### Added — Model Tier Declarations per Skill

Skills can now declare `min_model: haiku | sonnet | opus` in their YAML front matter. The MCP server:
- Surfaces the tier in the tool description: `[min-model: opus]` suffix visible in `ListTools`
- Prepends a model advisory to the skill content when the active tier (from `SKILLFOUNDRY_MODEL_TIER` env var) is below the declared minimum

`forge.md`, `go.md`, and `architect.md` tagged with `min_model: opus`.

#### Added — `update.sh` Checkpoint & Rollback

Three new subcommands for safe framework updates:

- `./update.sh --checkpoint <path> [label]` — snapshots all managed files (skills, agents, rules, CLAUDE.md, etc.) with a `MANIFEST.json` mapping backup filenames to original paths.
- `./update.sh --checkpoints <path>` — lists all available checkpoints with framework version, file count, and manifest status.
- `./update.sh --rollback <path> [checkpoint-id]` — restores from a checkpoint (latest if no ID). Automatically creates a `pre-rollback` safety checkpoint before overwriting anything.

#### Added — MCP Streamable HTTP Transport

The MCP server now exposes **`/mcp/http`** (GET/POST/DELETE) alongside the existing `/mcp/sse`. Uses `StreamableHTTPServerTransport` from `@modelcontextprotocol/sdk` (MCP 2025-03-26 spec). Per-session transport instances keyed by `mcp-session-id` header. New sessions are initialized on the first POST (no header required); subsequent requests include the header returned in the response.

### Changed

- `anvil.sh` gains Phase 4 `sast` subcommand — runs `semgrep --config p/owasp-top-ten --config p/secrets`. HIGH findings block; MEDIUM warn; absent semgrep skips non-fatally.
- `anvil.md` T1 description updated to mention Semgrep SAST; T4 renamed to "Scope + SAST" with `sf_security_scan` tool invocation for deep LLM-assisted scanning.
- `genesis/TEMPLATE.md` gains 10 structural improvements (applied in prior session): required front matter block, §3.3 security constraints table, §4.3 scalability table, §6 skip gate, §8 Regression Surface table, §11.1 three-layer DoD items, FR-IDs column in §2 user stories.
- `SkillDefinition` interface gains `minModel: SkillModelTier | null` field; all inline skill object literals updated.
- `move-story.sh` exit code `6` added: refused transition to `done/` due to CRITICAL GuardLoop patterns.
- MCP server startup log now shows both `/mcp/sse` and `/mcp/http` endpoints.

---

## [5.12.0] - 2026-05-13

### GuardLoop × SkillFoundry — Self-Improving AI Governance

Integration of [GuardLoop](https://github.com/samibs/guardloop.dev) as live Claude Code hooks and a `/guardloop` skill. The framework now tracks its own failure patterns across sessions and promotes them into enforced rules automatically.

#### New Skill: `/guardloop`

Five subcommands for the adaptive governance engine:

- **`/guardloop`** (default) — Pattern frequency report. Reads `guardloop-patterns.json` + recent `memory_bank/` entries. Shows counts, promotion candidates, last harvest time.
- **`/guardloop promote`** — Writes patterns at threshold (3+ hits) as enforced rules to `agents/_guardloop-rules.md`. Marks promoted patterns so they don't re-promote on next run.
- **`/guardloop scan`** — Live scan of the current codebase against all 10 patterns. Reports findings by severity.
- **`/guardloop status`** — Hook health check + pattern summary table.
- **`/guardloop reset`** — Resets pattern counters (preserved promoted rules).

#### New Hooks

- **`failure-scan.sh`** (PostToolUse: Edit|Write) — Scans every written code file for 3 CRITICAL patterns: hardcoded secrets, localStorage token storage, AI file corruption artifacts. Non-blocking. Appends file to `guardloop-files.log` for end-of-session harvest.
- **`guardloop-harvest.sh`** (Stop, runs before `batch-check.sh`) — Full 10-pattern scan of every code file edited during the session. Logs JSON entries to `memory_bank/knowledge/errors-universal.jsonl`. Updates `guardloop-patterns.json` frequency counters.

#### New Scripts

- `scripts/guardloop-analyze.sh` — Reads pattern state and outputs a formatted frequency table. Called by `/guardloop` skill.
- `scripts/guardloop-promote.sh` — Promotes threshold-meeting patterns to `agents/_guardloop-rules.md`. Supports `--dry-run` and `--reset`.

#### New Agent Files

- `agents/_guardloop-rules.md` — Adaptive rules file. Self-populates when patterns hit 3+ occurrences. All code-generating agents enforce rules written here.

#### Pattern Catalog (10 patterns tracked)

| ID | Pattern | Severity |
|----|---------|----------|
| GL-01 | `hardcoded-secret` | critical |
| GL-02 | `localstorage-token` | critical |
| GL-03 | `file-corruption` | critical |
| GL-04 | `empty-catch` | high |
| GL-05 | `placeholder-code` | high |
| GL-06 | `nullable-array-method` | high |
| GL-07 | `ts-ignore-no-comment` | medium |
| GL-08 | `console-log-unguarded` | medium |
| GL-09 | `hardcoded-path` | medium |
| GL-10 | `select-star-query` | medium |

#### The Learning Loop

```
Code edited
  ↓ failure-scan.sh (PostToolUse)     ← CRITICAL patterns + file tracking
Session ends
  ↓ guardloop-harvest.sh (Stop)       ← Full 10-pattern scan + knowledge logging
Pattern hits 3+ occurrences
  ↓ /guardloop promote                ← Writes rule to agents/_guardloop-rules.md
All future sessions enforce the rule  ← Framework self-improves
```
## [5.11.0] - 2026-05-08

### FolderFlow — Deterministic Story State via the Filesystem

Ships the FolderFlow PRD (`genesis/2026-05-08-folder-state-and-checkbox-reconciler.md`)
end-to-end. Story state is now a function of the filesystem, not LLM memory:
checkbox state is reconciled against real artifacts, and stories physically
move between `todo/`, `in-progress/`, `blocked/`, `done/` folders as gates
pass and fail. No daemons, no watchers — synchronous and Git-visible.

### Added — Story Checkbox Reconciler (Phase 1 of FolderFlow PRD)

Phase 1 of `genesis/2026-05-08-folder-state-and-checkbox-reconciler.md`: a deterministic
reconciler that flips `- [ ]` → `- [x]` in story markdown based on artifact pointers, so
checkbox state always matches what the gates have actually verified.

- `scripts/reconcile-story-checkboxes.sh` — main reconciler. Walks story files, finds
  checkboxes tagged with `<!-- artifact: handler:args -->`, dispatches to the named
  handler, and rewrites passing checkboxes in place. Atomic via temp-file + rename.
- `scripts/lib/reconcile-handlers.sh` — handler library. Phase 1 ships the
  `file-exists` and `grep` handlers; reserved Phase-3 names (`test:`, `lint:`,
  `layer-check:`) return a "deferred" code rather than silently misbehaving.
- `tests/scripts/test-reconciler.sh` — 26-case shell test suite covering every
  handler, path-safety rejection (absolute paths, traversal, symlink escape),
  CLI behavior, and strict-mode exit codes.
- Self-test mode: `scripts/reconcile-story-checkboxes.sh --self-test` builds throwaway
  fixtures, asserts FR-005 (untagged boxes never modified), FR-007 (idempotency),
  FR-008 (non-destructive — never un-checks), and `--strict` failure semantics.
- `/layer-check` integration: new `STORY CHECKBOX RECONCILIATION` section and a
  `/layer-check reconcile` invocation. The verdict box gained a `Checkbox Reconcile`
  iteration-gate row.
- `docs/story-checkbox-reconciler.md` — usage, artifact-pointer syntax, exit codes,
  and the FR-008 non-destruction contract.

Properties enforced:
- **Non-destructive**: a previously-checked box is never reverted; if its artifact
  has since vanished, a regression warning is logged but the box stays checked.
- **Idempotent**: a second invocation with no new artifacts produces zero diff.
- **Path-safe**: absolute paths, `..` traversal, and symlinks resolving outside
  the repo root are all rejected before any handler runs.
- **No artifact contents in logs**: only paths and pass/fail booleans are logged,
  so artifact files containing secrets cannot leak through reconciler output.

Phase 3 (rich JSON handlers) is explicitly deferred per the PRD's §9.1 — it ships
when Anvil gates emit standardized JSON artifacts.

### Added — Story Folder State Machine (Phase 2 of FolderFlow PRD)

Phase 2 of `genesis/2026-05-08-folder-state-and-checkbox-reconciler.md`: makes
story state explicit and Git-visible by physically moving story files between
`todo/`, `in-progress/`, `blocked/`, `done/` subfolders under each feature.

- `scripts/lib/story-index.sh` — INDEX.md regeneration library. Deterministic
  output (no timestamps, sorted by ID). Parses `# STORY-XXX — Title` headings
  and YAML `depends_on:` frontmatter (inline + block list). Only re-writes
  INDEX.md when content actually changes (mitigation for noisy diffs, R-003).
- `scripts/move-story.sh` — atomic state transitions. Uses `git mv` so
  `git log --follow` keeps working across renames. Refuses `→ done` (rc=3)
  unless `reconcile-story-checkboxes.sh --strict` passes — gate verdict and
  artifact-backed checkbox state must agree before a story can be marked done.
- `scripts/migrate-stories-to-folders.sh` — one-time, idempotent migration of
  flat `docs/stories/<feature>/STORY-*.md` trees into the new layout.
  Classifies each story by checkbox state: all-checked-tagged → `done/`,
  any-unchecked-tagged → `todo/`, no-tags → `todo/` (ambiguous, printed in a
  manual-review list at the end).
- `tests/scripts/test-folder-state.sh` — 40-case test suite covering INDEX
  regeneration, state-transition validation, BLOCKED sibling lifecycle,
  migrator classification, idempotency, dry-run, and a regression check
  that Phase 1's `--self-test` still passes.
- BLOCKED sibling files: `STORY-XXX.BLOCKED.md` is auto-generated when a
  story enters `blocked/` (failing gate + ISO timestamp + free-text reason)
  and auto-removed when the story leaves.
- `/layer-check` integration: new "STORY STATE FOLDERS (Phase 2)" section
  documenting how an APPROVED verdict drives `→ done/` and a REJECTED
  verdict drives `→ blocked/`.
- `/go` integration: new "STORY STATE FOLDERS (Phase 2)" section instructing
  the orchestrator to call `move-story.sh` at gate transitions and to **skip
  any story already in `done/`** — the explicit fix for the "re-runs
  completed work" failure described in the PRD's §1.1.
- `docs/story-state-folders.md` — full workflow documentation: layout, CLI
  reference, exit codes, manual override, concurrency, and what is still
  out of scope (file watchers, web UI, regression detection).

Sourced libraries (`scripts/lib/*.sh`) deliberately do **not** enable `set -u`
or `set -e` — those leak into the caller's shell. Entry-point scripts set
their own strict modes.

### Added — JSON Artifact Handlers (Phase 3 of FolderFlow PRD)

Phase 3 of `genesis/2026-05-08-folder-state-and-checkbox-reconciler.md`: the
reconciler now parses standardized JSON artifacts, completing the original
schema frozen in PRD §5.2.

- `handler_test` (artifact tag `test:`) — parses `{"passed": <bool>, "failed":
  <number>, "total": <number>}`. Pass when `passed == true && failed == 0`.
- `handler_lint` (artifact tag `lint:`) — parses `{"violations": <number>,
  "files_scanned": <number>}`. Pass when `violations == 0`.
- `handler_layer_check` (artifact tag `layer-check:`) — parses `{"status":
  "pass"|"fail", "database": ..., "backend": ..., "frontend": ...}`. Pass
  when `status == "pass"`.
- Strict schema enforcement: malformed JSON, missing required fields, or
  required fields with the wrong type all produce **invalid** (rc=2). The
  checkbox stays unchecked and a clear error is logged. This is the explicit
  defense against a half-broken gate producing a vacuous pass.
- Dispatch in `reconcile_dispatch_handler` no longer returns the "deferred"
  code (4) for these names — they route to the real handlers. Phase-1
  installs that referenced these names will start working as soon as the
  emitting gate produces JSON.
- Test suite extended from 26 → 43 cases: each new handler has pass / fail-
  by-data / fail-by-missing-file / malformed-JSON / missing-required-field /
  wrong-type cases, plus a dispatch-routing test confirming the names are
  no longer deferred.
- Documentation updated: `docs/story-checkbox-reconciler.md` handler table
  now lists all 5 handlers with usage examples; `.claude/commands/layer-check.md`
  removes the "only file-exists and grep are wired" note.

### Deviation from PRD

PRD §10.1 specified `bats` for unit tests; `bats` is not installed and is not in
the project's existing test toolchain. Substituted plain-shell tests under
`tests/scripts/` matching the project's existing pattern (`tests/run-tests.sh`).
No new system dependency added.

PRD §9.1 stated Phase 2 should ship only "after Phase 1 proves valuable on at
least one feature," and Phase 3 ships only "when Anvil gates emit standardized
JSON artifacts." Both prerequisites were waived at the user's explicit
direction; all three phases ship back-to-back in the same release. Phase 3 is
forward-looking — handlers are wired and tested against synthetic JSON, ready
for the first gate that emits the frozen schema.

---

## [5.10.0] - 2026-05-07

### /test-map Skill — Test Cases Documentation Generator

New `/test-map` skill that reads every test file in a project, classifies tests by business value tier, and produces a deliverable-grade HTML report. Added to all 5 platforms.

#### Classification Engine

- **Tier 1 (HIGH VALUE)** — Tests asserting conditional rendering, state transitions, data transformation rules, business rules, field exposure/hiding, exact payload shapes, multi-step flows. Signal: multiple `expect()` with specific values, `toHaveBeenCalledWith(...)`.
- **Tier 2 (MEDIUM-HIGH VALUE)** — DI wiring with real providers, `HttpTestingController` HTTP contract tests, lifecycle-triggered behavior.
- **Tier 3 (BASELINE VALUE)** — Pure `should create` / `toBeTruthy()` smoke tests with zero behavioral assertions.

One Tier 1 test in a file classifies the entire file as Tier 1.

#### Report Output

- Per-file deep analysis for Tier 1/2: test case table (name + plain-English description), why-it-exists context, added value breakdown, "Is It Useful?" verdict
- Grouped module table for Tier 3 files
- Assessment summary: value distribution + 5-dimension coverage quality score (breadth, depth, business rules, edge cases, API contracts — each scored 1-10)
- Recommendations section: ordered by impact, with specific code examples and exact target files
- Self-contained HTML output (`docs/test-map-YYYY-MM-DD.html`) with inline CSS matching the deliverable format (tier color classes, verdict classes, TOC, score table)

---

### GitHub Copilot + Claude Optimization

Two targeted changes that bring GitHub Copilot with Claude model to full parity with the Claude Code experience.

#### `.github/copilot-instructions.md` — Full Claude System Prompt

Expanded from a 50-line memory-policy stub to a complete Claude-optimized system prompt:
- **Identity block** — SkillFoundry persona, role as cold-blooded senior engineer + agent orchestrator
- **Constitutional rules** — Non-negotiable code quality (no stubs, no nullable array methods), security (no localStorage tokens, HttpOnly cookies), three-layer completeness (DATABASE → BACKEND → FRONTEND), honesty (no vacuous test passes, no inferred verification)
- **Memory policy** — `memory_bank/` usage, schema reference, explicit prohibition on Copilot's `WorkspaceStorage/`
- **Agent invocation table** — All key agents with triggers and purposes
- **Project structure map** — `genesis/`, `docs/stories/`, `memory_bank/`, platform dirs
- **Development workflow** — PRD-first, forge pipeline, verify before done

#### Copilot `forge.md` — Full Parity with Claude Version

Synced to the canonical Claude version (was 222 lines behind). Restores:
- Safeguards 3-6 (Circuit Breaker, Session Issue Tracking, Anomaly Detection, Output Verification Loop)
- Phase 2.5 (Delivery Audit) and Phase 2.75 (Verify)
- Full error handling tables per phase
- Reflection protocol (pre/post execution, self-score)
- Complete OUTPUT FORMAT block with all phase metrics

---

### Fixed

- **Config Protection hook — greenfield false positive.** `.claude/hooks/config-protect.sh` was blocking first-time creation of protected config files (`tsconfig.json`, `.eslintrc.json`, etc.) on greenfield projects, preventing `/go` from scaffolding the first story. The hook now exits 0 when the target path does not yet exist — there are no rules to loosen if no rules exist yet. Subsequent edits still hit the deny branch.

- **Version alignment.** A forge orchestrator job merged a PR that reset version references to 5.7.1 across `sf_cli/package.json`, `mcp-server`, `README.md`, and site files, and injected a spurious `[5.7.1]` entry before the CHANGELOG header. All references corrected to 5.10.0.

---

## [5.9.0] - 2026-05-07

### Self-Validate Skill — Output Verification Loop

New `/self-validate` skill implementing the "agent validates its own work" pattern. Added to all 5 platforms (Claude Code, Copilot, Cursor, Gemini, Codex/Agents).

#### `/self-validate` Skill

- **7 AC types classified**: API endpoint, business logic, database, UI/frontend, CLI command, file output, integration — each mapped to a concrete verification command (`curl`, unit test, DB query, DOM grep, etc.)
- **Core loop**: LOAD story → CLASSIFY ACs → GENERATE commands → EXECUTE → COMPARE actual vs expected → REPORT ✓/✗ → FIX & RETRY (max 3 iterations per AC)
- **Browser validation**: Puppeteer/Playwright MCP for UI stories when available; falls back to `curl + grep` DOM inspection
- **Server startup check**: Verifies dev server is up before API/UI ACs; reports startup failures rather than faking passes
- **Fix routing**: Failed ACs auto-routed to `/fixer` with exact actual-vs-expected delta; re-verified after each fix
- **Strict rules**: Never declare verified without running. Never fake a pass. Actual output wins over code inspection.

#### Forge Pipeline Integration

- **Safeguard 6** added to Phase 2 (Claude Code, Gemini, Codex/Agents): per-story output verification loop runs after Test Existence Gate (Safeguard 2), before DONE is marked
- **Phase 2.75: VERIFY** added to all 5 platforms between Phase 2.5 (Delivery Audit) and Phase 3 (Temper): runs `/self-validate --all` across all DONE stories before layer validation begins
- Both output format blocks updated on all platforms to include Phase 2.75

---

## [5.8.0] - 2026-05-06

### VS Code Extension v1.3.0 — Native IDE Shell

Completes the VS Code extension as a fully standalone product shell. Three blocking gaps closed.

#### Setup Wizard (`SkillFoundry: Setup — Configure API Key`)

- Provider quick-pick (Anthropic Claude / OpenAI) on first activation when no config is detected
- API key stored in VS Code SecretStorage — never written to disk, never in config.toml
- `.skillfoundry/config.toml` created with provider name only
- Reload-window prompt offered immediately after setup
- `onCommand:skillfoundry.setup` activation event added so the command is reachable from the command palette even without a `.skillfoundry/config.toml` present

#### sf CLI Installation Check

- At activation, checks whether `sf` is available on PATH via `execFile('sf', ['--version'])`
- If `sf` not on PATH **and** `sf-runner.mjs` is also missing, shows a warning with "Install via npm" option
- "Install via npm" opens an integrated terminal and runs `npm install -g skillfoundry`

#### Forge Progress Notification

- `vscode.window.withProgress` notification wraps the entire forge terminal lifetime
- Notification is cancellable — cancellation kills the terminal
- ForgeMonitor sidebar continues to update live from `forge-state.json` file watcher
- Forge terminal receives stored API key as env var (via `bridge.getCredentials()`)

#### Credential Injection (`SfBridge`)

- `setCredential(envVar, value)` / `getCredentials()` added to `SfBridge`
- API key loaded from SecretStorage on activation and injected into all `execFile` runner calls
- All terminals (forge, prd, benchmark, hooks) receive credentials via `env:` option
- Keys never touch the filesystem

#### Infrastructure

- Extension version: 1.2.0 → 1.3.0
- All framework version references bumped to 5.8.0

---

## [5.7.0] - 2026-05-06

### Local Vector Memory + Specter Security Engine + Red Team Researcher Skill

Three features that add adversarial intelligence, semantic memory, and a deep security research skill.

#### Local Vector Memory

- `EmbeddingService`: multi-provider embedding with priority chain per `preferredProvider`
  - `preferredProvider: 'ollama'` → [ollama, transformers, openai]
  - `preferredProvider: 'openai'` → [openai, transformers, ollama]
  - `TransformersEmbeddingProvider` (@xenova/transformers, Xenova/all-MiniLM-L6-v2, 384 dims) always-available local fallback
  - Returns `EmbeddingResult { vector, provider, dimensions, cached }`
- `VectorStore`: file-based cosine-similarity store with `initialize()` / `add(MemoryDocument[])` / `search(query)` / `delete(ids[])` API
- `harvestRunMemory` upgraded to async with best-effort semantic indexing on every pipeline run
- Hybrid layered recall: keyword index + semantic vector search with score fusion

#### Specter Security Engine

- `SpecterEngine` agent: adversarial red-team loop; generates attack vectors, runs allowlisted simulations
- Pipeline phase `SPECTER` inserted between `INSPECT` and `DEBRIEF` (9 phases total)
- Simulation allowlist blocks `curl`, `wget`, `rm`, `dd`, `mkfs`, and all network exfil tools
- Agent registered as `specter` (FULL/implementer); circular import resolved by removing static import from registry
- Agent count: 61 → 62

#### Red Team Researcher Skill (`/red-team-researcher`)

- Senior offensive/defensive security researcher persona installed as a slash command
- Structured finding format: SEV / Location / Class / Reachability / Exploit sketch / Fix
- 6 domain reference files: code_review, web_api, cloud_infra, threat_modeling, reporting, blue_team
- Hard guardrails: no weaponized exploits, no C2/ransomware/stalkerware, no credential attacks on named orgs

#### Infrastructure

- `layered-recall.ts`, `memory-search.ts`: async-ified for `await recallIndex()` callers
- Test suite: 2328/2330 pass (2 pre-existing Ollama env failures in health-check.test.ts)
- All version references bumped to 5.7.0

---

## [5.6.0] - 2026-04-19

### Parallel Dispatch Engine + Natural Language Cron

Two execution infrastructure features that reduce pipeline time and simplify scheduling.

#### Parallel Dispatch Engine (`parallel-dispatch.ts`)
- DAG-based dependency graph analysis for multi-story pipelines
- Topological sort generates execution waves of independent tasks
- File conflict detection prevents parallel execution of stories modifying overlapping files
- Migration ordering enforcement serializes stories with database migrations
- Cycle detection with clear error reporting
- Wave execution via `Promise.allSettled` with configurable max concurrency (default: 5)
- Error isolation: failed task dependents are automatically skipped
- Parallel speedup calculation comparing wave vs sequential execution time
- Critical path analysis identifies the longest dependency chain
- New MCP tool `sf_parallel_analyze`: analyze stories and preview wave structure before execution

#### Natural Language Cron Compiler (`nl-cron.ts`)
- 20+ pattern matchers covering common scheduling descriptions
- Time parsing: "9am", "2:30pm", "14:00", "midnight", "noon"
- Day parsing: full names, abbreviations, weekday/weekend groups
- Interval patterns: "every N minutes/hours/days"
- Named patterns: "every morning/evening/night", "daily", "weekly", "monthly"
- Day-specific: "every Monday at 9am", "weekdays at 2:30pm"
- Monthly: "first day of every month", "on the 15th of every month at 3pm"
- Compound: "twice a day at 9am and 5pm"
- Confidence levels: exact/high/medium/low based on pattern match quality
- Cron validator: checks field ranges, step values, lists, and ranges
- Next-run calculator: returns next 5 execution times for any cron expression
- New MCP tool `sf_cron_compile`: compile NL to cron or validate existing expressions

#### Infrastructure
- Both tools wired into handler.ts with optimized JSON responses
- All version references bumped to 5.6.0

---

## [5.5.0] - 2026-04-19

### Hermes-Inspired Intelligence — Context Summarization, Memory Nudges, Session Search

Three features adapted from NousResearch's Hermes Agent framework, closing gaps in context preservation, selective memory, and history search.

#### LLM Context Summarizer (`context-summarizer.ts`)
- Replaces mechanical "[N messages omitted]" with Haiku-generated semantic summaries
- Preserves decisions, tool results, file changes, and error resolutions from pruned messages
- Cost: ~$0.0003 per summarization call (200 input + 200 output tokens on Haiku)
- Graceful fallback to mechanical summary if no API key or LLM call fails
- Input capped at ~2000 tokens to keep summarization fast and cheap
- Only triggers when 4+ messages are pruned (small compactions use mechanical summary)

#### Memory Nudge System (`memory-nudge.ts`)
- Monitors 13 nudge-worthy tools (security scans, builds, tests, linters, contract checks)
- After error results, generates contextual suggestions for patterns worth recording
- Each nudge includes: pattern description, why it matters, suggested entry type, scope, and tags
- Capped at 10 nudges per session to avoid noise
- Nudges appended to tool responses so the LLM can decide whether to record
- Directly references `sf_session_record` with pre-filled parameters for easy recording

#### Full-Text Session Search (`session-search.ts`)
- SQLite FTS5 virtual tables for tool response history and session recordings
- Porter stemming + unicode61 tokenizer for intelligent matching
- FTS5 query syntax: quoted phrases, AND/OR/NOT operators, prefix* matching
- Combined search across tool responses and knowledge base with relevance ranking
- Snippet extraction with highlight markers for context
- New `tool_response_log` table stores truncated (2KB) summaries of all tool responses
- Auto-sync triggers keep FTS indexes updated on every INSERT
- `rebuildSearchIndexes()` for bulk re-indexing after data imports

#### New MCP Tool: `sf_memory_search`
- Full-text search across ALL session history — tool responses and session recordings
- Filter by scope (tools/recordings/all), tool name, or app name
- Returns ranked results with snippets, timestamps, and metadata
- Addresses the "I fixed this before but can't find where" problem

#### Infrastructure
- `server.ts`: FTS5 tables initialized at startup via `ensureSearchTables()`
- `handler.ts`: Every tool response now indexed via `indexToolResponse()` in the `tracked()` wrapper
- `handler.ts`: Memory nudges injected after tool error results
- All version references bumped to 5.5.0 (server, API, MCP protocol, packages)

---

## [5.4.0] - 2026-04-19

### Token Optimization Engine — Response Compression, Concise Mode, Usage Tracking

Addresses the #1 hidden cost in AI-assisted development: tool responses become conversation history and get re-tokenized on every subsequent turn. 98.5% of tokens go to rereading old context — this release cuts the framework's contribution to that cost.

#### Response Optimizer (`response-optimizer.ts`)
- All JSON tool responses now go through smart compaction before returning to the LLM
- Strips null/undefined/empty fields from JSON payloads
- Size-aware formatting: pretty-print for <2KB, single-indent for <8KB, minimal for larger
- Array truncation at 50 items with count summary
- Hard output cap at ~30K chars (~8.5K tokens) with truncation summary header
- Applied to all tool agents (handler.ts) and dispatch agents (tool-dispatch.ts)

#### Concise Mode — Skill Prompt Compression
- Every LLM skill tool now accepts `concise: true` parameter
- Strips code examples, large table rows (keeps header + 3 rows), blockquotes, and verbose sections
- Collapses consecutive blank lines
- Typical reduction: 40-65% fewer tokens per skill invocation
- Use on repeated/familiar skills where full instruction set isn't needed

#### Token Tracker (`token-tracker.ts`) — Persistent Usage Tracking
- SQLite-persisted per-session and daily token usage (survives server restarts)
- Tracks output tokens and character count per tool invocation
- Per-session ID with automatic session management
- Budget warnings at 100K (note), 200K (warning), 500K (critical) token thresholds
- Estimated cost calculation at Sonnet input pricing (tool outputs become input on re-read)
- New `token_usage` table with indexes on session_id, created_at, tool_name

#### `sf_token_report` — New MCP Tool
- Real-time token usage visibility for current session or daily aggregate
- Per-tool breakdown: invocations, total output tokens, average output tokens
- Session duration tracking
- Daily reports via `date` parameter (e.g., `"2026-04-19"`)
- Cost estimates and actionable budget warnings

#### Infrastructure
- `handler.ts`: All 15+ inline JSON responses replaced with `optimizeJsonResponse()` calls
- `tool-dispatch.ts`: `jsonResult()` helper now routes through response optimizer
- `server.ts`: Token tracking table initialized at startup alongside metrics
- `handler.ts`: MCP server version updated from 5.2.0 to 5.4.0
- `routes.ts`: API version corrected from 5.2.0 to 5.4.0
- `server.ts`: Boot log version corrected from 5.2.0 to 5.4.0

---

## [5.3.0] - 2026-04-16

### Hook-Based Workflow Enforcement — GateGuard, Config Protection, Session Quality

Adds a production hook system that enforces coding discipline at the tool level. Inspired by patterns from `everything-claude-code`, adapted and integrated into SkillFoundry's existing settings architecture.

#### GateGuard — Force-Read-Before-Edit
- PreToolUse hook on Edit/Write blocks modifications to files the agent hasn't Read yet
- Prevents "vibe coding" where agents modify files without understanding existing imports, data shapes, or patterns
- Directly enforces the Frontend-Backend Contract Rule from CLAUDE.md at the hook level
- New file creation (Write to non-existent path) is exempt
- State tracked per-session in `.claude/hooks/state/gateguard-reads.log`

#### Config Protection — Linter/Formatter Shield
- PreToolUse hook on Edit/Write blocks changes to 30+ protected config files
- Covers ESLint, Prettier, TypeScript (tsconfig), Biome, Stylelint, EditorConfig, Ruff, Flake8, MyPy, Pylint
- Forces agents to fix code to satisfy rules instead of weakening rules to satisfy code
- User can override by explicit approval when genuine config updates are needed

#### Post-Edit Accumulator — Session Quality Report
- PostToolUse hook on Edit/Write records every edited `.ts/.tsx/.js/.jsx/.py/.css/.json` file
- Stop hook runs batch Prettier check + `tsc --noEmit` + Ruff on all accumulated files
- Reports formatting issues, type errors, and lint violations as a session summary
- Non-blocking: reports issues but doesn't prevent session end

#### Session Lifecycle
- SessionStart hook clears stale state from previous sessions
- All state files ephemeral (`.claude/hooks/state/` added to `.gitignore`)
- Hooks use `$CLAUDE_PROJECT_DIR` for portable paths across environments

#### Infrastructure
- 6 new hook scripts in `.claude/hooks/`
- Updated `.claude/settings.json` with SessionStart, PreToolUse, PostToolUse, and Stop hook configurations
- All hooks have 5-second timeouts (60s for batch-check at Stop)
- Existing `validate-bash.sh` hook preserved and upgraded to use `$CLAUDE_PROJECT_DIR` paths

---

## [5.2.0] - 2026-04-02

### Multi-Tenant Security Enforcement — PRD-to-Code Traceability

Closes the #1 gap in AI-generated multi-tenant apps: PRD says "multi-tenant" but the agent builds flat storage, unprotected downloads, and no tenant scoping. Triggered by the AutoKYC incident (2026-04-02).

#### Story Generator — Security Trait Detection
- Scans PRDs for multi-tenant/multi-user/file-upload/auth trigger words
- Auto-injects mandatory security stories (SEC-001 through SEC-006):
  - SEC-001: Tenant data model with scoped queries (every table, every query)
  - SEC-002: Tenant-scoped file storage (no flat `uploads/{id}/`)
  - SEC-003: Auth on every endpoint (no unprotected downloads)
  - SEC-004: Cross-tenant isolation tests (User A cannot access User B's data)
  - SEC-005: Secure file handling (path traversal prevention, type validation)
  - SEC-006: No hardcoded credentials (no defaults in config)
- Security stories are MUST priority and block all endpoint/model/storage stories

#### Gate Keeper — Multi-Tenant Isolation Gate
- 7 mandatory checks when PRD mentions multi-tenant:
  - Every data model has tenant_id column
  - Every query scoped by tenant
  - File storage paths include tenant directory
  - Every data endpoint has auth middleware
  - Download endpoints verify tenant ownership
  - No hardcoded credentials in config
  - Cross-tenant isolation tests exist
- PRD-to-Code Traceability: cross-references PRD claims against actual implementation
- NON-NEGOTIABLE: BLOCK on any failure

#### Known Deviations — Category 10b: Multi-Tenant Isolation Failures
- 10 new patterns (MT-001 through MT-010):
  - MT-001: Flat file storage without tenant directory
  - MT-002: Download/export endpoint without auth
  - MT-003: Unscoped database queries
  - MT-004: PRD says multi-tenant but code ignores it
  - MT-005: Existing security service bypassed by new code
  - MT-006: Hardcoded default credentials
  - MT-007: Download accepts user-supplied path (traversal)
  - MT-008: No cross-tenant isolation tests
  - MT-009: HTTPBasic auth on data endpoints
  - MT-010: Tenant ID from request body instead of auth token

#### PRD Template
- New §4.2.1 Multi-Tenant Isolation section with tenancy model, scoping strategy, file storage isolation, cross-tenant testing requirements
- Empty section on multi-tenant PRD is a BLOCKING issue during validation

#### Install Flow
- Installer creates `.vscode/mcp.json` for VS Code MCP server auto-discovery
- Installer creates `.github/copilot-instructions.md` for Copilot Chat tool awareness
- Works with any MCP-compatible IDE (VS Code, Cursor, Claude Code extension)

---

## [5.1.0] - 2026-04-02

### Harness Engineering Upgrade — Claude Code Architecture Parity

Architectural patterns extracted from Claude Code's production harness (1,902 TypeScript files, 207 commands, 184 tool entries) applied to SkillFoundry's MCP server.

#### Tool Module System
- Self-contained tool folders: each of 15 tools lives in `mcp-server/src/tools/{ToolName}/` with dedicated execution logic, prompt, constants, and permissions
- Auto-discovery registry scans `src/tools/` at startup — add a folder, get an MCP tool
- 20 MCP tools across 15 modules: BuildAgent, TestRunner, GitAgent, DependencyAgent, PortAgent, TypecheckAgent, LintAgent, MigrationAgent, EnvAgent, LighthouseAgent, DockerAgent, NginxAgent, PlaywrightAgent, SemgrepAgent, VerificationAgent

#### Permission Engine
- `ToolPermissionContext` with deny-list (by name), prefix-blocking, simple-mode (core tools only), and workspace trust gates
- Trust-required tools (sf_verify_auth, sf_security_scan, sf_harvest_knowledge, sf_create_skill, sf_memory_gate) blocked in untrusted workspaces
- Simple mode restricts to sf_build, sf_run_tests, sf_git_status only
- All denials logged with tool name, reason, and timestamp

#### Streaming Event Protocol
- SSE event types: `message_start`, `tool_match`, `message_delta`, `message_stop`, `permission_denial`
- `StreamEmitter` class manages connected SSE clients
- Fire-and-forget — no overhead if no clients are listening

#### Session Intelligence
- `SessionConfig` with configurable max turns, token budget, compaction threshold
- `UsageSummary` with functional (immutable) updates — `addTurn()` returns new object
- `TranscriptStore` with automatic compaction when turn threshold exceeded
- File-based session persistence (`.sf_sessions/{id}.json`) with load/save/list
- `SessionEngine` orchestrates budget enforcement + auto-compaction
- REST API: `GET /api/v1/sessions`, `GET /api/v1/sessions/:id`

#### Bootstrap Pipeline
- 7-stage startup: prefetch -> guards -> tool-registry -> skill-load -> deferred-init -> permissions -> transport
- Stage 2 (guards): fail-fast on Node < 20, missing git/npm
- Stage 5 (deferred-init): trust-gated — checks Playwright/Semgrep binaries, skips in untrusted workspaces
- Non-required stages log warnings and continue instead of crashing

#### Verification Agent
- New `sf_verify` MCP tool validates other agents' output with tool evidence
- Strategies: build, test, typecheck, lint — each runs the real tool and compares against claimed output
- Returns structured `VerificationReport` with per-check evidence
- Optional auto-verify hook after any tool execution (`SKILLFOUNDRY_AUTO_VERIFY=true`)

#### Command Graph & Enhanced Health
- Tools categorized as builtin/plugin/skill/dynamic via `CommandGraph`
- `GET /api/v1/agents?category=builtin` for filtered listing
- `/health` reports bootstrap stage, completion progress, duration, session metrics, and permission state
- `/ready` returns 503 until all 7 bootstrap stages complete

#### Environment Variables (New)
- `SKILLFOUNDRY_DENY_TOOLS` — comma-separated tool deny list
- `SKILLFOUNDRY_DENY_PREFIXES` — comma-separated prefix deny list
- `SKILLFOUNDRY_SIMPLE_MODE` — restrict to core tools
- `SKILLFOUNDRY_TRUST` — workspace trust level (default: true)
- `SKILLFOUNDRY_MAX_TURNS` — session turn limit (default: 50)
- `SKILLFOUNDRY_MAX_BUDGET_TOKENS` — session token budget (default: 100000)
- `SKILLFOUNDRY_COMPACT_AFTER` — compaction threshold (default: 30)
- `SKILLFOUNDRY_SESSION_DIR` — session persistence directory (default: .sf_sessions)
- `SKILLFOUNDRY_AUTO_VERIFY` — auto-verify after tool execution (default: false)

---

## [5.0.0] - 2026-03-29

### BREAKING — SkillFoundry v5: Learning-Driven Intelligence

**Data-driven upgrade**: Every feature in v5 was derived from analysis of 2,792 harvested artifacts, 115 AI session transcripts, 267 extracted insights, and security/contract assessments across 49 projects. This is the first release where the MCP server's own knowledge loop drove the feature set.

#### Secret Guard Agent (`sf_secret_guard`)
- 11 detection rules: hardcoded passwords, API keys, secrets, tokens, database URLs, JWT secrets, private keys, AWS keys, Stripe keys, SendGrid keys, basic auth URLs
- False-positive filtering: validation messages, setup scripts, localhost URLs, comments, .env.example files, documentation, process.env references
- `.env.example` completeness validation: cross-references `process.env.*` references against defined vars
- Redacted output in MCP responses to prevent secret exfiltration

#### Import Resolution Validator (`sf_import_validator`)
- Validates JS/TS `import`/`require` and Python `import`/`from...import` statements
- Cross-references against `package.json` dependencies, `node_modules`, `requirements.txt`, `pyproject.toml`
- Detects native modules requiring build tools (better-sqlite3, sharp, bcrypt, etc.)
- Node.js builtin module skip list (60+ modules)
- Local import resolution with extension and index file fallbacks

#### Deviation Enforcement Engine (`sf_deviation_enforcer`)
- Parses 161 known LLM deviation patterns from the knowledge store catalog
- 16 categories: Frontend, Backend, Database, TypeScript, Security, Authorization, Error Handling, LLM-Specific, and more
- Regex-based detection rules derived from pattern descriptions
- Rules stored in SQLite `deviation_rules` table — queryable, extensible, per-project allowlists
- `loadDeviationCatalog()` loads from knowledge store; `enforceDeviations()` scans projects

#### Enhanced Contract Resolution (`sf_contract_check` upgrade)
- **NestJS support**: `@Controller('/api/users')` + `@Get('/:id')` = `/api/users/:id` full path resolution
- **FastAPI support**: `APIRouter(prefix="/api/v1")` + `@router.get("/users")` = `/api/v1/users`
- **Centralized API client tracing**: `axios.create({ baseURL: '/api/v1' })` -> `api.get('/users')` = `/api/v1/users`
- Contract match rate improved from 17.5% to 70.8% on tested projects

#### Correction Feedback Loop
- Extracts correction events from AI session transcripts
- Groups corrections by semantic similarity using keyword-based phrase extraction
- SHA-256 hashing for stable pattern identification
- Auto-generates deviation rules when threshold met: 3+ occurrences across 2+ projects
- Generated rules stored with `source: "auto_correction"` in `deviation_rules`
- Per-project correction history queryable via `sf_query_corrections`

#### Project Health Scores
- Per-project A-F grades with 0-100 scoring
- Formula: 100 base, -15/critical, -8/high, -3/medium, -1/low security, -2/contract mismatch, -5/import error, -10/secret finding
- Stored in `project_health_scores` table with run-by-run history
- Fleet-wide health summary with grade distribution
- Trend tracking for week-over-week regression detection

#### Nightly Harvest Pipeline v2
- All 5 new agents integrated into the nightly pipeline
- New stages: Secret Guard, Import Validator, Deviation Enforcer, Correction Analyzer, Health Scorer
- Enhanced report with fleet health table, deviation violations, correction patterns
- Version bumped to v5.0.0 in report footer

#### Security Hardening
- `validateProjectPath()` on all MCP tool endpoints — resolves path, checks allowlist, verifies directory
- Secret content redacted in MCP responses (first 20 chars + `****[REDACTED]`)
- Regex construction from DB wrapped in try/catch with 500-char length cap
- `maxViolations` input capped at 500

#### New Database Tables
- `deviation_rules` — 161 LLM failure patterns with regex detection, file globs, severity
- `correction_patterns` — semantic groups of user corrections with threshold tracking
- `project_health_scores` — per-project per-run health metrics and grades

#### New MCP Tools (5)
- `sf_secret_guard` — scan project for hardcoded secrets
- `sf_import_validator` — validate all imports resolve
- `sf_deviation_enforcer` — enforce 161 deviation rules
- `sf_contract_check` — enhanced frontend-backend contract validation
- `sf_query_corrections` — query correction patterns and trends

---

## [4.0.0] - 2026-03-29

### BREAKING — SkillFoundry v4: Tier 4 Tool Agents, Fleet Intelligence, Multi-Platform Detection

**Architecture expansion**: SkillFoundry gains 5 new Tier 4 tool agents, fleet-wide health monitoring, multi-platform AI artifact detection, knowledge scoping, and BPSBS production rules recovery.

#### Tier 4 Tool Agents (5 new MCP tools)
- **Contract Check** (`sf_contract_check`) — Validates frontend API calls (fetch/axios) match actual backend endpoints. Detects path mismatches, HTTP method conflicts, and orphaned calls. Supports Next.js App Router, Express, Fastify, and FastAPI.
- **Project Context** (`sf_project_context`) — Auto-generates project-specific context by scanning package.json, requirements.txt, .env files, and directory structure. Detects framework, DB, auth provider, ORM, test framework, linter, CSS framework, UI library, and API style.
- **Security Scan Lite** (`sf_security_scan_lite`) — Fast 14-rule regex-based security scanner for pre-commit checks. Catches hardcoded secrets, CORS misconfig, eval/exec, SQL injection, data leaks, insecure cookies, and type evasion. Runs in <500ms vs Semgrep's 30s+.
- **Version Check** (`sf_version_check`) — Compares PRD version specifications against actual installed packages. Catches major/minor drift before implementation begins (PRD says Prisma 5, npm has Prisma 7).
- **Session Recorder** (`sf_session_record`) — Records decisions, corrections, errors, facts, and patterns during development sessions. Auto-detects scope (project vs universal) and extracts framework/category tags.

#### Fleet Health Dashboard
- `GET /api/v1/fleet/health` — Real-time fleet overview: total apps, assessment coverage %, stale apps (below framework v2.0.70), platform distribution, framework version distribution, memory bank presence.
- `GET /api/v1/knowledge/recordings` — Query session recordings by app, type, scope, with pagination.
- Fleet health auto-populated during harvest runs via `upsertFleetHealth()`.

#### Multi-Platform AI Detection
- Scanner now detects artifacts from all 5 AI coding platforms: Claude Code (`.claude/`), Cursor (`.cursor/`), GitHub Copilot (`.copilot/`, `.github/copilot/`), Google Gemini (`.gemini/`), OpenAI Codex (`.codex/`, `.agents/`).
- Root instruction files detected: `CLAUDE.md`, `.cursorrules`, `.cursorrc`, `copilot-instructions.md`, `.gemini.md`, `AGENTS.md`, `codex.md`.
- Per-platform artifact scanning: commands, agents, rules, skills, prompts, memory banks.

#### Knowledge System Enhancements
- **Scope tagging**: `"project"` (local) vs `"universal"` (eligible for cross-project promotion) on every knowledge entry.
- **Multi-root harvest**: `appsRoots: string[]` — scan multiple directories in one harvest (`~/apps` + `~/wapplications`).
- **Session recordings table**: Captures non-forge development knowledge (decisions, corrections, errors, facts, patterns) with auto-scope and auto-tags.
- **`appHasData()` rewrite**: Detects real platform artifacts instead of only forge logs — harvest now correctly identifies apps with AI development data.

#### BPSBS Production Rules Recovery
- 7 critical rules recovered from cross-project analysis of 37 apps and encoded in `agents/_bpsbs-production-rules.md`:
  1. Authentication & Token Security (HttpOnly cookies, RS256/ES256, refresh rotation)
  2. Centralized Logger (replace console.log, sensitive field sanitization)
  3. .gitignore Security Template (secrets, tokens, IDE files, build artifacts)
  4. Database Migration Strategy (dangerous ops matrix, linear chain rules)
  5. Incident Response Protocol (P0-P4 severity, 8-step response, post-incident template)
  6. PM2 Production Scripts (ecosystem.config.cjs template)
  7. Observability Stack (RED method, structured log format)

#### Hook Templates
- `hooks/pre-commit-security-scan.sh` — Pre-commit hook checking staged files for secrets, credentials, and API keys.
- `hooks/post-edit-contract-check.sh` — Post-edit hook for API files triggering contract validation.
- `hooks/post-tool-session-recorder.sh` — Auto-records tool failures to session recordings.

#### Tier 1-3 Tool Agents (12 — from v3.0.0-rc)
- Build (`sf_build`), Test (`sf_test`), Deps (`sf_deps`), Port (`sf_port`), Git (`sf_git`), TypeCheck (`sf_typecheck`), Lint (`sf_lint`), Migration (`sf_migration`), Env (`sf_env`), Lighthouse (`sf_lighthouse`), Docker (`sf_docker`), Nginx (`sf_nginx`).

---

## [3.0.0] - 2026-03-29

### BREAKING — SkillFoundry v3: MCP Agent Server + iznir Skill Factory

**Architecture shift**: SkillFoundry transforms from installed prompt files to a centralized MCP server with real tool agents and an on-the-fly skill factory.

#### Phase 1: MCP Server Shell
- Node.js/TypeScript server with SSE transport for MCP protocol
- Loads 124 `.md` skill files as MCP tools on startup
- REST API: `/health`, `/ready`, `/api/v1/agents` (list + detail)
- PM2 ecosystem config for production deployment
- Any IDE connects via: `"mcpServers": { "skillfoundry": { "url": "http://localhost:9877/mcp/sse" } }`
- No more `install.sh` per app. Zero version drift. Single source of truth.

#### Phase 2: Real Tool Agents
- **Playwright Agent** (`sf_verify_auth`) — 8 browser-level auth checks: page load, form elements, login redirect, session cookie, cookie flags, expected destination, protected route, unauthenticated redirect. Screenshot evidence at each step.
- **Semgrep Agent** (`sf_security_scan`) — Real SAST with OWASP rule packs. Returns findings with severity, file:line. Replaces regex-based banned pattern matching.
- **Memory Gate** (`sf_memory_gate`) — Tool evidence (Playwright, Semgrep, build) = `verified`. LLM reasoning alone = `observed`. curl for auth flows = `observed`. Prevents saving wrong "definitive" patterns. Includes warning about 3 corrections in one session.

#### Phase 3: Knowledge Loop
- **Session Log Scanner** — Walks `~/apps/`, detects AI platforms (`.claude/`, `.cursor/`, `.copilot/`, `.gemini/`), parses forge logs and session monitor data.
- **Knowledge Aggregator** — Extracts failure patterns across all apps. Promotes recurring patterns (2+ apps or 3+ occurrences) to quirk candidates.
- **SQLite Knowledge Store** — `known_quirks`, `harvest_runs`, `session_logs` tables. Query by framework. Deduplication on insert.
- **Harvester** (`sf_harvest_knowledge`, `sf_query_quirks`) — Full pipeline: scan → aggregate → deduplicate → persist. Live tested: 42 forge logs → 2 quirks extracted.

#### Phase 4: Optimization
- **Cost Router** — Routes tasks to Haiku ($0.25/M) for search/grep, Sonnet ($3/M) for code gen, Opus ($15/M) for architecture. Per-agent overrides. Daily budget cap. Token spend tracking.
- **Metrics Collector** — Per-agent invocation tracking: count, success/fail rate, duration, tokens, model tier. REST: `/api/v1/metrics`.
- **iznir Integration** — REST client for dynamic skill generation via iznir.hexalab.dev.

#### iznir Engine Merge
- **Skill Factory** (`sf_create_skill`) — Ported from iznir.hexalab.dev core engine. Creates certified AI skills on the fly:
  - `analyzeIntent()` — Claude analyzes description into structured SkillProposal
  - `generateGuardrails()` — 6 domain/risk-aware guardrails (hallucination, unknown handling, source grounding, scope enforcement, audit trail, version contract)
  - `runSkillTest()` — 10-case automated test suite (80% pass required for certification)
  - `exportAsClaudeSkill()` — Exports as `.md` compatible with SkillFoundry's skill loader
  - Auto-registers certified skills as live MCP tools without server restart
  - Persists to SQLite, reloads on startup
- **Flow**: user needs capability → no existing skill → `sf_create_skill("description")` → Claude analyzes → guardrails → tests → if 80%+ → certified → registered → available immediately

#### PRD Template Hardening (v2.0.79–v2.0.86)
- §5.0 Technology Maturity Assessment (Beta deps → Playwright mandatory)
- §5.3 Dependencies (verified versions + peer conflicts)
- §5.4 Compatibility Notes
- §5.5 Directory Structure
- §5.7 Environment Variables
- §5.8 Deployment Environment + Known Deployment Quirks
- Browser-level auth verification in TEMPER phase and layer-check (all 5 platforms)
- Playwright-verified NextAuth v5 credentials login pattern
- 8 new checklist gates

**Files**: `mcp-server/` (20 source files, 7 test files, ~6,500 lines TypeScript)
**Tests**: 53 passing across 7 test files
**MCP Tools**: 124 LLM skills + 7 tool agents + 2 knowledge tools = 133 total

---

## [2.0.86] - 2026-03-27

### Added — §5.0 Technology Maturity Assessment

**Problem**: The agent confidently built with NextAuth v5 beta (unstable API, 0 known quirks in the knowledge base) and only discovered it was uncharted territory after 6 login rewrites. The PRD had no mechanism to flag "this dependency is beta, you're the first to hit the problems, test harder."

**§5.0 Technology Maturity Assessment** (new, first section in Technical Specifications):
- **Maturity Classification Table**: Stable / Recent Major / RC / Beta / Alpha — each with a defined verification level
- **Stack Assessment**: Every dependency classified with version, maturity, breaking changes from prior, known quirks in KB, and required verification level
- **Risk Decision Table**: Beta/Alpha deps must justify why the beta is used over a stable alternative, state the blast radius (auth = critical), and acknowledge who owns debugging
- **Key rule**: Any dep marked Beta/Alpha → **Playwright verification mandatory in TEMPER**. Agent cannot declare TEMPER PASS with only curl.

**Forge TEMPER updated** (all 5 platforms): Playwright mandatory for Beta/Alpha deps per §5.0.
**PRD checklist updated** (both templates): New gate — "Technology maturity assessed in §5.0."
**Platform PRD skills updated** (all 5): Compact maturity assessment table.

**How this prevents the LuxComplianceSuite failure**:
- NextAuth v5 beta.30 would be flagged as Beta + 0 known quirks = uncharted territory
- Blast radius = Critical (auth) → Playwright mandatory, not optional
- Agent would know before writing the first line that curl-only verification is insufficient

---

## [2.0.85] - 2026-03-27

### Fixed — Playwright-Verified NextAuth v5 Patterns (3rd Correction)

**Context**: The Known Deployment Quirks for NextAuth v5 credentials login were corrected **3 times** in this session. Each correction was based on pattern-matching ("this looks right") rather than browser-level verification. Only after running Playwright did the actual working pattern emerge.

**Playwright-verified patterns** (replaces all previous entries):

| Component | Works | Doesn't Work |
|-----------|-------|-------------|
| **Login** | `signIn("credentials", { redirect: false })` + manual `window.location.href` + `SessionProvider` | Default redirect, fetch(), native form POST, getCsrfToken() |
| **Middleware** | Cookie existence check (`__Secure-authjs.session-token`) | `getToken()` (JWE), `auth()` wrapper (Prisma not edge-compatible) |
| **Build** | `rm -rf .next` + clean rebuild | Incremental (stale server chunks → InvariantError) |

**New quirks added**: middleware edge runtime incompatibility, stale standalone builds.

**Lesson**: Never document a "definitive pattern" based on code inspection. Only Playwright/browser verification counts for auth flows.

---

## [2.0.84] - 2026-03-27

### Added — Browser-Level Auth Verification in TEMPER Phase & Layer Check

**Problem**: `/forge` declared "Phase 3 TEMPER: PASS" on LuxComplianceSuite because all `curl` tests passed. But the login was completely broken in a real browser — `set-cookie` dropped on 302 redirects, CSRF token/cookie context mismatches, form fields not reaching the authorize function. `curl` is blind to browser-specific auth failures.

**Root cause**: The three-layer validation (layer-check) had no browser-level verification for auth flows. It accepted `curl` + screenshots as "evidence" for frontend validation, but cookie handling, CSRF pairing, and redirect behavior are invisible to `curl`.

**Changes**:

**Layer Check — Frontend Validation** (all 5 platforms):
- New "BROWSER-LEVEL VERIFICATION" section in the frontend checklist
- Login sets session cookie and redirects to dashboard
- Logout clears session and redirects to login
- Protected routes redirect unauthenticated users
- Cookie flags verified (Secure, HttpOnly, SameSite)
- CSRF token pairing works in browser context
- Redirects preserve `set-cookie` headers
- Explicit note: "curl tests backend logic. Browser tests verify the full contract."
- New evidence requirement: "Auth flow verified in browser (not just curl/httpie)"

**Forge — Phase 3 TEMPER** (all 5 platforms):
- Added browser-level auth as a mandatory TEMPER check alongside DB, Backend, Frontend

**PRD Template — §10.1 Definition of Done** (both templates):
- New gate: "Browser-level auth flow verified (login/logout/protected routes — curl is NOT sufficient)"

**Files updated** (15):
- 5 layer-check skills (Claude Code, Copilot, Cursor, Gemini, Codex)
- 5 forge skills
- 2 PRD templates (genesis + docs)
- Version, README, CHANGELOG, site

---

## [2.0.83] - 2026-03-27

### Added — NextAuth v5 Credentials Login Pattern in Known Deployment Quirks

**Problem**: `/forge` rewrote the LuxComplianceSuite login form **4 times** before finding the one working pattern for NextAuth v5 beta + credentials provider. Each failure was silent — no error, just a redirect loop.

**What doesn't work** (3 of 4 approaches fail silently):
1. `signIn("credentials", { redirect: false })` — session cookie never set
2. `fetch()` + `redirect: "follow"` — `set-cookie` dropped on 302 (browser security)
3. Native `<form>` + raw `fetch("/api/auth/csrf")` — CSRF token/cookie context mismatch → `MissingCSRF`

**What works** (only 1 pattern):
4. Native `<form method="POST" action="/api/auth/callback/credentials">` + `getCsrfToken()` from `next-auth/react` + `SessionProvider` wrapper on auth layout

**Quirks table updated** in `genesis/TEMPLATE.md`, `docs/prd/TEMPLATE.md`, `templates/prd-web-app.md` with the definitive pattern. This prevents future `/forge` runs from repeating the 4-rewrite cycle.

---

## [2.0.82] - 2026-03-27

### Changed — PRD Template: Consolidated v2.0.79–v2.0.82

Consolidates 4 rapid-fire PRD template improvements driven by a real `/forge` session on LuxComplianceSuite. Each section was added after observing a specific failure class.

**New PRD Sections (§5.3–§5.8)**:

| Section | Prevents | Failure Observed |
|---------|----------|-----------------|
| **§5.3** Dependencies (enhanced) | Unverified package versions | `next-auth@5` doesn't exist, 3 wasted install cycles |
| **§5.4** Compatibility Notes | Undocumented peer conflicts | `--legacy-peer-deps` bailout, masked real conflicts |
| **§5.5** Directory Structure | Agent improvising file-system routes | Bash escaping errors on `(auth)` and `[tenantSlug]` dirs |
| **§5.7** Environment Variables | No `.env.example`, no secrets | Project deployed with zero env config, `/generate auto` had nothing to read |
| **§5.8** Deployment Environment | Port conflicts, MIME errors, proxy auth failures | Port 3000 crashed another app, static assets served as `text/plain` (3 times), NextAuth 500 behind nginx |
| **§5.8** Known Deployment Quirks | Framework-specific production gotchas | `trustHost`, standalone static copy, `fetch()` dropping `set-cookie` on 302 redirects (3 login rewrites) |

**Quirks captured**: Next.js standalone static copy, NextAuth `trustHost` behind proxy, NextAuth `signIn()` silent failure, Prisma 7 adapter everywhere, `fetch()` dropping `set-cookie` on 302 redirects.

**Checklist gates added**: dependency versions verified, peer conflicts documented, directory structure specified, env vars listed, deployment environment specified.

**Files updated**: `genesis/TEMPLATE.md`, `docs/prd/TEMPLATE.md`, 5 platform PRD skills, 3 project-type templates (API, Web App, CLI), README, site.

---

## [2.0.81] - 2026-03-27

### Added — PRD Template: Deployment Environment (§5.8)

**Problem**: `/forge` on LuxComplianceSuite improvised the entire deployment: used port 3000 (crashed another app), missed Next.js standalone static asset copy (MIME type errors hit 3 times), missed NextAuth `trustHost` behind nginx (500 on all auth), and `signIn()` silently failed. None of this was in the PRD.

**§5.8 Deployment Environment** (new) — Specifies target infrastructure before implementation begins:
- **Infrastructure table**: port allocation (portman/manual), process manager (PM2/systemd/Docker), reverse proxy, SSL, domain, CDN
- **Build & Deploy Commands**: exact sequence from code to production — no improvisation
- **Known Deployment Quirks**: framework-specific gotchas that break production (Next.js standalone static copy, NextAuth trustHost, Prisma adapter everywhere). Saves hours of runtime debugging.

**Files updated** (14 total):
- `genesis/TEMPLATE.md`, `docs/prd/TEMPLATE.md` — Full section with infrastructure table, deploy commands, quirks table
- 5 platform PRD skills — Compact deployment section
- `templates/prd-web-app.md` — Pre-filled with Next.js + PM2 + nginx patterns
- `templates/prd-api.md` — Pre-filled with API deployment patterns
- Both checklist gates updated

---

## [2.0.80] - 2026-03-27

### Added — PRD Template: Environment Variables Specification (§5.7)

**Problem**: `/forge` generated all code for LuxComplianceSuite but never created `.env.example` and never ran `/generate auto`. The project deployed with zero environment configuration — no secrets, no database URL, no SMTP credentials. The PRD had no section telling the agent what env vars were needed or how to generate them.

**§5.7 Environment Variables** (new) — Table listing every env var the project needs, with columns for format, generation method (`/generate ...` for auto-generated secrets, `Manual` for user-provided credentials, `Derived` for computed values), and notes. This is the source of truth for `.env.example` generation. `/generate auto` reads this table during `/forge` to auto-fill secrets.

**Files updated** (13 total):
- `genesis/TEMPLATE.md`, `docs/prd/TEMPLATE.md` — Full section with examples
- 5 platform PRD skills (Claude Code, Copilot, Cursor, Gemini, Codex)
- 3 project-type templates (API, Web App, CLI) — Pre-filled with stack-appropriate examples
- Both checklist gates updated

---

## [2.0.79] - 2026-03-27

### Changed — PRD Template: Dependency Verification & Directory Structure

**Problem**: `/forge` wasted 3 install cycles on a LuxComplianceSuite PRD because `next-auth@5` doesn't exist (only beta.30), peer conflicts weren't documented, and the agent improvised the entire Next.js directory structure.

**§5.3 Dependencies** — Enhanced with `Verified` checkbox and `Peer Conflicts` columns. Comments now require running `npm view <pkg> versions` before freezing a PRD. No more "version doesn't exist" surprises at install time.

**§5.4 Compatibility Notes** (new) — Table for documenting known peer dependency conflicts between packages before implementation begins. Prevents `--legacy-peer-deps` bailouts.

**§5.5 Directory Structure** (new) — Required for file-system-routed frameworks (Next.js App Router, Nuxt, SvelteKit, Remix). The directory structure IS the routing — it's an architectural decision that must be specified in the PRD, not improvised by the agent.

**§5.6 Integration Points** — Renumbered from old §5.4 (no content change).

**Files updated** (13 total):
- `genesis/TEMPLATE.md` — Primary template with full sections
- `docs/prd/TEMPLATE.md` — Documentation copy with full sections
- `.claude/commands/prd.md` — Claude Code PRD skill
- `.copilot/custom-agents/prd.md` — GitHub Copilot PRD skill
- `.cursor/rules/prd.md` — Cursor PRD skill
- `.gemini/skills/prd.md` — Google Gemini PRD skill
- `.agents/skills/prd/SKILL.md` — OpenAI Codex PRD skill
- `templates/prd-api.md` — API project template
- `templates/prd-web-app.md` — Web app project template
- `templates/prd-cli.md` — CLI project template

**Checklist gates added** (both templates):
- All dependency versions verified (npm view / pip index)
- Peer dependency conflicts documented in §5.4 (or confirmed "None")
- Directory structure specified in §5.5 (required for file-system-routed frameworks)

---

## [2.0.78] - 2026-03-27

### Added — Framework Hardening (Phases 1-5)

**Context-Aware Loading (Phase 1)**:
- `CLAUDE-LITE.md` (~380 tokens) — lightweight context for everyday work. Full `CLAUDE.md` loaded on-demand by `/forge`, `/certify`, `/go`.
- 13 per-category deviation files in `agents/deviations/` — agents load only their relevant categories instead of the full 171-pattern catalog.
- Master `_known-deviations.md` updated with per-category file index.

**Executable Deviation Checks (Phase 2)** — 4 new certification categories (15 total, was 11):
- **Contracts** (`auditContracts`) — Detects frontend-backend mismatches: unverified endpoints (CONTRACT-002), unguarded `.map()` on response fields (CONTRACT-005), timestamp format mismatches (CONTRACT-009), mixed error formats (CONTRACT-010). Weight: 10%.
- **Authorization** (`auditAuthorization`) — Detects missing auth: user-scoped queries without ownership checks (AUTH-001), admin routes without role checks (AUTH-003), state-changing endpoints without CSRF (AUTH-007). Weight: 5%.
- **Error Handling** (`auditErrorHandling`) — Detects gaps: empty catch blocks (ERR-001), network calls without try/catch (ERR-003), HTTP 200 with error bodies (ERR-005), missing global error handlers (ERR-007). Weight: 4%.
- **Supply Chain** (`auditSupplyChain`) — Detects risks: wildcard versions (SUPPLY-005), missing lockfiles (SUPPLY-004), dev deps in production (SUPPLY-006), unpinned Python deps. Weight: 2%.
- Category weights rebalanced to accommodate new categories (total: 100%).

**Integration Test Suite (Phase 3)**:
- `examples/test-project/` — Sample project with intentional violations across all 15 certification categories. Grades D or F when certified.
- `certification-roundtrip.test.ts` — End-to-end test: certify (assert fail) → apply fixes → re-certify (assert pass). Proves the certification→remediation pipeline works.

**Domain Pack Staleness Alerting (Phase 4)**:
- `computeStaleness()` — Classifies rules as current (<6mo), stale (6-12mo), or outdated (>12mo) based on `last_verified` date.
- `/domain list` now shows staleness warnings per pack (STALE/OUTDATED counts).
- `/domain explain` shows staleness tag on each rule's verification date.
- `formatStalenessSummary()` — Detailed staleness report per pack.
- `scripts/verify-packs.sh` — Shell script that lists all rules by `last_verified` date, grouped by staleness, with markdown output for review.

**Smart Router Instrumentation (Phase 5)**:
- `startAgentDispatch()` — Records routing decision when forge/go dispatches to an agent. Returns decision ID.
- `completeAgentDispatch()` — Records outcome (success/failure/partial), score, duration, cost. Updates both `routing_decisions` and `agent_performance` tables.
- `hasLearningData()` — Returns true when 10+ decisions have outcomes (router can make data-driven recommendations).
- `getLearningStatus()` — Summary: total decisions, completed, unique agents, is-learning flag.

### Changed

- Certification engine: 11 → 15 categories with rebalanced weights.
- Test count: 2,277 → 2,307 (30 new tests across 4 suites).

---

## [2.0.77] - 2026-03-26

### Added — Mandatory Production Rules

**5 new mandatory rules** enforced across CLAUDE.md, global settings, agents, and `/certify`:

- **Consistent page width** — All pages MUST use the same `max-width` container regardless of content
- **Responsive + mobile-friendly** — Every page MUST work at 320px, 768px, and 1200px+. Viewport meta tag required. No horizontal scrolling.
- **README = user-friendly** — README is for users (install, usage, screenshots). Technical details go in CHANGELOG and `docs/`.
- **Rebuild protocol** — `git pull → rm -rf .next → npm ci → npm run build → pm2 restart → verify health → hard refresh`. Never skip cache cleanup.
- **Deployment notifications** — Commit and deploy events must send notifications (webhook, email, or CI/CD).

Updated agents: `/ux-ui` (layout rules), `/docs` (README vs CHANGELOG separation), `/sre` (rebuild protocol + notifications).
Updated `/certify`: viewport meta check added to accessibility audit.

---

## [2.0.76] - 2026-03-26

### Added — Local Secret & Artifact Generator

**Generator Engine** (`/generate`):
- JWT tokens: HS256/RS256/ES256 with auto-generated key pairs, decode existing tokens
- API keys with configurable prefix (`sk_`, `pk_`, etc.)
- UUIDs (v4, batch generation with `--count`)
- Secure passwords with complexity enforcement (upper, lower, digit, special)
- Cryptographic secrets (hex, base64, base64url, configurable length)
- SHA256/SHA512/scrypt hashes, HMAC-SHA256/SHA512 signatures
- RSA/EC key pairs saved to `.keys/` directory
- Webhook signing secrets (`whsec_` prefix)
- TOTP secrets (RFC 6238 compatible for 2FA)
- `.env` templates (api, fullstack, minimal) with auto-filled secrets

**Forge Pipeline Auto-Integration**:
- `/generate auto` scans `.env` for empty `SECRET`, `KEY`, `TOKEN`, `PASS` variables
- Auto-fills with cryptographically secure random values (64-char hex for JWT, prefixed for API keys)
- Creates `.env` from `.env.example` if `.env` doesn't exist
- Generates RS256 key pair when `package.json` references JWT libraries
- Called automatically by `/forge`, `/go`, `/goma` during project setup

Zero external dependencies — all Node.js `crypto` module. No secrets leave your machine.
45 tests covering all generators, auto-fill, file I/O, and formatting.

---

## [2.0.75] - 2026-03-26

### Fixed — Simple-First Debugging Discipline

- **Debugger agent** (`/debugger`) — Added Simple-First Debugging Protocol: verify data → verify binding → verify flow → only then investigate timing/race conditions. Prevents the "15 steps before checking the obvious" anti-pattern.
- **Fixer agent** (`/fixer`) — Added Hard Rules: diagnose simple→difficult→complex before routing to specialist agents.
- **Memory recorded** — `feedback_simple_first_debugging.md` ensures this discipline persists across sessions.
- Root cause: RUE-2026 incident where LLM investigated token refresh, React state sync, and memory lifecycle before checking if the API returns the correct field name. The fix was 3 steps away.
- Synced to all 5 platforms (240 files).

---

## [2.0.74] - 2026-03-25

### Added — Industry Knowledge Engine with 3 Domain Packs

**Industry Knowledge Engine** (`/domain`):
- `/domain explain <topic>` — query rules with source citations and disclaimers
- `/domain search <keywords>` — weighted keyword search across all installed packs
- `/domain validate <file> --pack <name>` — check code against domain-specific rules
- `/domain matrix <name>` — structured data tables (VAT rates, CDD levels, lawful bases)
- `/domain prd <description>` — generate PRDs pre-populated with regulatory requirements
- `/domain cite <rule-id>` — full citation for any rule by ID
- `/domain list` / `/domain info <pack>` — pack management
- 37 tests covering pack loading, search, scoring, validation, PRD generation

**EU VAT Pack** (`packs/eu-vat/`, 24 rules, 1 matrix):
- VAT Directive 2006/112/EC: standard rates, reduced rates, exemptions
- Place of supply (B2B/B2C), reverse charge, OSS, EUR 10K threshold
- 12 country-specific rates (LU, DE, FR, BE, NL, IT, ES, PT, AT, IE, PL, SE)
- 27-country standard rates matrix with all EU member states
- Invoice requirements, VAT calculation formulas

**GDPR Pack** (`packs/gdpr/`, 20 rules, 1 matrix):
- Lawful bases (Article 6), consent conditions (Articles 7-8)
- Data subject rights: access (DSAR), erasure, portability, profiling objection
- Breach notification (72-hour rule), DPIA, privacy by design
- Cookie consent (ePrivacy), storage limitation, international transfers
- Fines (4%/EUR 20M upper tier), DPO requirements, transparency
- Lawful bases matrix with use cases and requirements

**AML/KYC Pack** (`packs/aml-kyc/`, 20 rules, 1 matrix):
- CDD/SDD/EDD levels with triggers and required measures
- PEP screening, beneficial ownership (25% threshold)
- SAR filing, tipping-off prohibition, record retention (5 years)
- EUR 15,000 occasional transaction threshold
- Crypto VASP obligations, travel rule (TFR 2023/1113)
- Sanctions screening, high-risk third countries
- Risk-based approach, customer risk rating, FATF 40 Recommendations
- CDD levels matrix

All 64 rules cite specific legislation articles with EUR-Lex URLs.

---

## [2.0.73] - 2026-03-25

### Added — RegForge Certification Pipeline & Remediation

**RegForge Certification** (`/certify`):
- 11-category static analysis audit: security, documentation, testing, dependencies, license, accessibility, privacy, architecture, seo, performance, ci-cd
- Weighted scoring (0-100) with grade (A-F): A=90+, B=75-89, C=60-74, D=40-59, F=<40
- Context-aware security scanner: excludes test fixtures, pattern-definition files, scripts, and generated content; reduced severity for innerHTML in server-rendered HTML
- Auto-generates 4 deliverables: HTML report (dark-mode), Markdown report (with code diffs), Word-compatible HTML (print-ready), remediation PRD (ready for `/go`)
- DB persistence: `certification_runs` + `certification_findings` tables
- 44 tests covering all categories, grading, DB, HTML generation, XSS escaping

**4 New Agents** (60 → 64 total, synced to all 5 platforms):
- `/pentest` — White-hat OWASP Top 10 penetration testing
- `/a11y` — WCAG 2.1 AA accessibility auditor
- `/license-audit` — OSS license compliance and SBOM
- `/privacy` — GDPR / data protection auditor

**Certification Remediation** (Grade B → A):
- Improved scanner to eliminate false positives (pattern-definition files, test fixtures)
- Added meta descriptions to internal HTML files (SEO: 50 → 90)
- Added root package-lock.json (dependencies: 90 → 100)
- Added .prettierrc (architecture: code style config)
- SkillFoundry self-certification: Grade A (95.5/100), 0 critical, 0 high

---

## [2.0.72] - 2026-03-23

### Added — Code Booster, Smart Router, Token Optimizer

Three new features inspired by Ruflo's architecture patterns:

**Code Booster** (`/boost`):
- 6 fast mechanical transforms without LLM calls: `var-to-const`, `add-types`, `wrap-async`, `add-export`, `require-to-import`, `add-jsdoc`
- Zero token cost, ~2,000 tokens saved per transform vs LLM approach
- CLI: `/boost <file>` with `--dry-run`, `--transforms`, `--all` flags

**Smart Router** (`/route`):
- Learning-based task routing that tracks agent performance per task type
- Jaccard keyword overlap for similar-task matching from history
- Falls back to keyword-based classification when no historical data
- DB tables: `routing_decisions`, `agent_performance`
- CLI: `/route <description>`, `/route stats`, `/route history`

**Token Optimizer** (`/tokens`):
- 6 compression strategies: `strip-markdown`, `collapse-repeats`, `strip-comments`, `truncate-files`, `dedup-instructions`, `compact-tables`
- Token analysis with per-section breakdown and cost estimates
- CLI: `/tokens analyze <file>`, `/tokens compress <file>`

110 new tests (37 + 37 + 36) across 3 test files, all passing.

---

## [2.0.71] - 2026-03-19

### Added — Skill Optimizer & Cursor Platform Fix

**Skill Optimizer** (autoresearch-inspired prompt mutation engine):
- 8 deterministic mutation strategies: `reorder_sections`, `toggle_emphasis`, `list_type_swap`, `sharpen_instructions`, `toggle_optional_section`, `consolidate_constraints`, `format_swap`, `prune_redundancy`
- 6 structural quality gates: structure, clarity, completeness, conciseness, specificity, actionability
- Composite scoring: gate quality (70%) + duration efficiency (15%) + token efficiency (15%)
- CLI command: `/optimize <skill>` with `--iterations`, `--apply`, `--strategies` flags
- DB persistence: `optimization_experiments` + `optimization_iterations` tables
- Batch mode: ran 100 iterations × 42 agents, identified 8 low-scoring prompts
- 50 tests covering strategies, scoring, DB, and experiment runner

**Agent Prompt Remediation** (optimizer-driven):
- Remediated 9 agents with +3.4% fleet average improvement (0.855 → 0.884)
- Zero agents below 0.80 (was 8)
- Top gains: `ai-workflows-and-learning-guide` +30.6%, `social-media-specialist` +23.2%, `mathematical-ground-checker` +23.1%
- Root cause: missing directive verbs (DO, REJECT, VALIDATE, CHECK, ENSURE, NEVER, ALWAYS)
- Added domain-specific "Hard Rules" sections to all deficient agents

**Cursor Platform Fix**:
- Rewrote `generate_cursor_content()` in `sync-platforms.sh` for Cursor-native rules
- All 86 `.cursor/rules/*.md` files now include YAML frontmatter, activation preamble, and usage footer
- Users say "use go rule" instead of `/go` — matching Cursor's rule-based model
- Previously: Cursor rules were identical to Claude commands with unusable `/slash` syntax

---

## [2.0.70] - 2026-03-18

### Fixed — Dashboard Launcher Portability

- **ESM compatibility** — `dashboard-serve.sh` now uses `--input-type=module` with `await import()` instead of `require()`. Fixes `ERR_MODULE_NOT_FOUND` on fresh clones where sf_cli is ESM (`"type": "module"`).
- **Auto-install dependencies** — Script detects missing `better-sqlite3` and runs `npm ci`/`npm install` automatically before starting.
- **Auto-build** — If compiled `dist/` files are missing, runs `npx tsc` to build before launching.
- **Real error reporting** — Shows actual Node.js error output instead of generic "non-JSON, continuing..." messages.

---

## [2.0.69] - 2026-03-18

### Added — One-Command Dashboard Launcher

- **`scripts/dashboard-serve.sh`** — Standalone bash launcher that auto-syncs all projects, captures KPI snapshots, seeds remediation playbooks, scans for remediations, then starts the web dashboard. Flags: `--port`, `--sync-only`, `--skip-sync`, `--open`.
- **`sf dashboard serve` auto-prepare** — The CLI `serve` subcommand now runs sync, snapshot capture, playbook seeding, and remediation scanning automatically before launching the web server. No manual prep steps needed.
- Updated in-app help (`bin/skillfoundry.js`) with standalone launcher commands.

---

## [2.0.68] - 2026-03-18

### Added — Centralized Multi-Project Dashboard (6-Phase)

A complete centralized dashboard aggregating telemetry, sessions, failures, KPIs, trends, and remediations across all 60+ registered projects. Built in 6 phases:

**Phase 1 — Foundation:**
- Persistent UUIDv4 project identifiers (`project-id.ts`)
- Central SQLite database (`data/dashboard.db`) with 10 tables: projects, telemetry_events, perf_entries, knowledge_entries, failure_patterns, kpi_snapshots, session_reports, session_issues, remediations, playbooks
- Incremental sync engine — reads per-project telemetry, perf, knowledge, and session data
- Auto-harvest cron integration — dashboard sync runs after every harvest sweep

**Phase 2 — CLI Commands (15 subcommands):**
- `sf dashboard` — project overview table
- `sf dashboard sync` — force-sync all projects into central DB
- `sf dashboard status <project>` — detailed single-project drill-down
- `sf dashboard failures` — cross-project failure report (--severity, --project filters)
- `sf dashboard top` — project rankings by events, failures, cost, or performance
- `sf dashboard kpi` — computed KPI metrics (success rate, gate pass rate, security findings)
- `sf dashboard health` — health assessment with letter grades (A-F)
- `sf dashboard import` — session report and forge log import
- `sf dashboard patterns` — failure pattern analysis (cross-project, recurring, escalating, category clusters)
- `sf dashboard trend` — KPI trend report with change detection
- `sf dashboard snapshot` — capture daily KPI snapshots
- `sf dashboard forecast <project>` — metric forecasting (linear regression)
- `sf dashboard remediate` — remediation report, scan, list, apply, playbooks
- `sf dashboard serve` — start web dashboard (http://127.0.0.1:9400)
- All subcommands support `--json` for machine-readable output

**Phase 3 — Session Import & Failure Detection:**
- Session report import from `.skillfoundry/runs/*-issues.json`
- Forge log parsing for failure pattern extraction
- Inbox pipeline: `data/inbox/` → import → move to `imported/`
- 4 detection rules: cross-project correlation, high-frequency (5+), category clusters (3+), escalating failures (>1/day)
- Failure pattern report with severity sorting and actionable recommendations

**Phase 4 — Web Dashboard:**
- Single-page dark-mode HTML dashboard (Chart.js 4.4.7, zero build step)
- 8 KPI cards: Projects, Forge Runs, Success Rate, Gate Pass Rate, Security Findings, Open Failures, Avg Duration, Knowledge
- 4 chart types: Health Distribution (doughnut), Top Projects (bar), Failure Severity (doughnut), Top by Failures (bar)
- 6 tabbed sections: Projects, Failures, Patterns, Health, Trends, Remediations
- HTTP server using Node.js built-in `http.createServer` (zero new dependencies)
- 13 API endpoints + CORS support, binds to 127.0.0.1 only
- Sync button, auto-refresh every 60 seconds

**Phase 5 — KPI Trend Engine:**
- Daily per-project KPI snapshot capture
- Trend detection: improving / declining / stable (comparing recent vs prior windows)
- Alert system: detects critical drops in success rate, gate pass rate, cost spikes, new security findings
- Simple moving-average forecasting with linear regression
- Trend charts in web dashboard (success rate bar, trend direction doughnut, cost trend)
- 4 new API endpoints: trends, snapshot capture, latest snapshots, forecast

**Phase 6 — Auto-Remediation Engine:**
- 10 built-in playbooks: TypeScript Build, Dependency Resolution, Test Timeout, Test Coverage, Security Vulnerability, Lint Gate, Type Check Gate, Circuit Breaker Recovery, Story Failure, Outdated Dependencies
- Pattern-to-playbook matching via signature and category heuristics
- Auto-apply for safe playbooks (dependency fixes, lint fixes, security audit)
- Remediation lifecycle: pending → in_progress → completed / failed
- Playbook effectiveness tracking (success/failure rates)
- Web UI with action buttons (Start, Complete, Fail) and playbook effectiveness table
- Cron integration: remediation scan runs after KPI snapshots in auto-harvest

**New files (11):**
- `sf_cli/src/core/project-id.ts` — project ID management
- `sf_cli/src/core/dashboard-db.ts` — SQLite database wrapper (10 tables, 30+ query functions)
- `sf_cli/src/core/dashboard-sync.ts` — sync orchestrator
- `sf_cli/src/core/session-import.ts` — session import pipeline
- `sf_cli/src/core/failure-detector.ts` — 4-rule failure pattern detection
- `sf_cli/src/core/dashboard-server.ts` — HTTP server with 19 API routes
- `sf_cli/src/core/kpi-engine.ts` — KPI snapshot capture, trends, forecasting
- `sf_cli/src/core/remediation-engine.ts` — auto-remediation with 10 playbooks
- `sf_cli/src/web/dashboard.html` — single-page dark-mode web dashboard
- `sf_cli/src/commands/dashboard.ts` — 15 CLI subcommands

**Tests: 206 new tests across 8 test files, 1,991 total (86 files), zero regressions.**

---

## [2.0.67] - 2026-03-18

### Changed — Documentation & Help Sync for Session Monitor (v2.0.66)

Full documentation sync across all surfaces for session monitor feature:

- **docs/HOW-TO.md**: New section 21 "Session Monitor" — 5 detectors, installation, how it works, state/log files
- **docs/QUICK-REFERENCE.md**: Added Session Monitor section with detector table, updated version
- **docs/AGENTS.md**: Added session monitor to Developer Experience commands and Quick Reference Card
- **docs/DOCUMENTATION-INDEX.md**: Added session monitor and env-preflight to Audit & Logging section, new Session & Environment Safety subsection
- **docs/USER-GUIDE-CLI.md**: Updated version and feature list to include session monitoring
- **sf_cli status command**: Now shows session monitor detections (total count + top patterns) from `logs/session-monitor.jsonl`
- **site/pages/**: Updated all 19 HTML pages from stale v2.0.52 to v2.0.67 (52 occurrences)
- **site/index.html**: Version bump to v2.0.67
- **README.md**: Updated What's New heading and version badge

---

## [2.0.66] - 2026-03-18

### Added — Real-Time Session Monitor

**Problem**: LLM agents exhibit erratic behavior patterns that waste tokens and break deployments — retry loops on identical errors, restarting services without reading logs, `source .env` on bash-unsafe files, and dismissing self-inflicted regressions as "pre-existing." Real-world cases: CircularWatch agent retried `source .env` 6 times; SmartExchange agent restarted a service 3 times debugging its own regressions one-at-a-time.

**Session Monitor (`scripts/session-monitor.sh`):**
- PostToolUse hook on Bash commands — runs after every shell command the agent executes
- **5 pattern detectors**:
  - **Source .env blocker**: Immediately blocks `source .env` / `. .env` with safe alternative (exit 2)
  - **2-Failure Rule**: After 2 consecutive similar errors, injects diagnostic nudge; at 3+, injects hard stop
  - **Service restart loops**: Tracks pm2/docker/systemctl restarts per service; nudges at 2, blocks at 3+
  - **Self-inflicted regression**: Cross-references `git diff --name-only` with error output to flag agent-modified files
  - **Restart without logs**: Detects `pm2 restart` without preceding `pm2 logs` read
- State persisted per-project in `.claude/session-monitor-state.json`
- Structured logging to `logs/session-monitor.jsonl` (harvestable by auto-harvest)
- Alert throttling: max 1 feedback injection per 30 seconds
- Session rotation: archives old state when session_id changes

**Hook Integration:**
- Added `PostToolUse` hook entry in `~/.claude/settings.json` (matcher: `Bash`)
- Updated `scripts/setup-auto-harvest.sh` to install/uninstall/status the session monitor hook
- Exit code 2 injects stderr content back into agent context as diagnostic feedback

---

## [2.0.65] - 2026-03-18

### Changed — Documentation & Help Sync for v2.0.62-v2.0.64 Features

Full documentation sync across all surfaces for environment pre-flight, auto-harvest, and .env safety features:

- **site-docs/architecture.md**: Added "Environment Pre-Flight" section (5-phase protocol, 2-Failure Rule, .env safety, fact pinning), added "Automatic Session Harvesting" section (cron, hooks, promotion pipeline), updated IGNITE phase to include env-preflight, fixed stale "7-tier" → "8-tier" reference
- **site-docs/getting-started.md**: IGNITE phase table now mentions environment pre-flight audit
- **site-docs/configuration.md**: New "Auto-Harvest Configuration" section (quick setup, customization options, env vars), new "Environment Pre-Flight" section with manual usage examples, added `KNOWLEDGE_SYNC_INTERVAL` env var
- **site/index.html**: Fixed "7 Quality Tiers" → "8 Quality Tiers" stat, updated Anvil feature card to "8-tier (T0-T7)", updated Knowledge Sync feature card to "Auto-Harvest & Knowledge Sync", fixed terminal demo "T1-T6" → "T0-T7 (8/8)"
- **README.md**: Added `env-preflight.sh`, `auto-harvest-cron.sh`, `setup-auto-harvest.sh` to scripts architecture tree
- **CLAUDE.md**: Added pointer to `agents/_env-preflight-protocol.md` in header references
- **sf_cli status command**: Now shows auto-harvest state (last run, lifetime runs/entries, projects harvested) when harvest state file exists

---

## [2.0.64] - 2026-03-18

### Added — .env File Safety Protocol

**Problem**: LLM agents routinely use `source .env` to load environment variables before running database commands. `.env` files are NOT bash scripts — they contain unquoted values with `<`, `>`, `|`, `&`, `()` characters that bash interprets as operators. Real-world case: `SMTP_FROM=CircularWatch <noreply@circularwatch.lu>` caused 6 consecutive `source .env` failures with `syntax error near unexpected token 'newline'` — agent never read the error message.

**Protocol Update (`agents/_env-preflight-protocol.md`):**
- New **Phase 5: .env File Safety** — documents why `source .env` is unsafe with safe alternatives
- Safe access patterns: `grep '^KEY=' .env | cut -d= -f2-` for single values, `sed` for complex values
- Database connection pattern: extract `DATABASE_URL` with grep, never source the whole file
- Pin rule: `.env format = NEVER source` added to session fact pinning
- Error→Diagnosis Map: added `syntax error near unexpected token` and `psql fails after .env load` entries
- Anti-patterns table: `source .env` / `. .env` added as first entry with correct alternative

**Script Update (`scripts/env-preflight.sh`):**
- New `dotenv` section in JSON output: detects `.env` and `backend/.env` files
- Unsafe character detection: scans for unquoted `<>|&()` in .env values
- `DATABASE_URL` extraction (safe grep, never source): reports presence and prefix
- CRITICAL warning when .env contains bash-unsafe characters
- WARNING when .env exists but no `DATABASE_URL` found

---

## [2.0.63] - 2026-03-17

### Added — Automatic Session Harvesting

**Problem**: Knowledge harvesting (`/gohm`, `session-close.sh`) required manual invocation. Across 60+ registered projects, session knowledge was only captured when the developer remembered to harvest — which means most sessions went unharvested.

**`scripts/auto-harvest-cron.sh` — Cron-based Cross-Project Sweep:**
- Scans all projects in `.project-registry` for new knowledge since last harvest
- Change detection: only harvests projects with modified `memory_bank/` or `.claude/scratchpad.md` files (skip unchanged)
- Runs `harvest.sh` per-project, then `promote-knowledge.sh` for pattern promotion, then `knowledge-sync.sh` for global repo sync
- Sanitizes central knowledge after each sweep (strips secrets, normalizes paths)
- Lock file prevents concurrent runs; stale locks auto-cleaned
- Persistent state tracking (`.claude/auto-harvest-state.json`): total runs, lifetime entries harvested, last duration
- Log rotation (2000-line cap) to `logs/auto-harvest.log`
- Modes: `--dry-run` (preview), `--harvest` (skip promote/sync), `--status` (stats), `--verbose`

**Claude Code Hooks — Automatic Session Lifecycle:**
- `SessionStart` hook: auto-runs `session-init.sh` (pulls global knowledge, starts sync daemon) when opening any SkillFoundry project
- `SessionEnd` hook: auto-runs `session-close.sh` (records session end, final sync, promotion check) then triggers cross-project harvest sweep in background
- Hook scripts only activate for projects with a `memory_bank/` directory (non-SkillFoundry projects unaffected)
- Hooks installed in `~/.claude/settings.json` with 30s/60s timeouts

**`scripts/setup-auto-harvest.sh` — One-Command Installer:**
- Installs cron job (default: every 30 minutes, configurable via `--interval=N`)
- Installs Claude Code hooks into `~/.claude/settings.json` (preserves existing settings)
- `--cron-only` / `--hooks-only` for selective install
- `--uninstall` cleanly removes cron entry and hook config
- `--status` shows full installation state, last harvest stats, registered project count

---

## [2.0.62] - 2026-03-17

### Added — Environment Pre-Flight Protocol

**Problem**: LLM agents fail at "obvious" operational tasks not because they lack syntax knowledge, but because they lack disciplined environmental reasoning. Real-world sessions showed agents doing guided trial-and-error (wrong interpreter, permission denied on `tsc`, missing `@types/node`) instead of systematic diagnosis — wasting tokens on retry loops that never converge.

**`scripts/env-preflight.sh` — Environment Audit Script:**
- JSON-output environment scanner that runs before any code execution in a new project/session
- Detects: OS, Python (system + venv), Node.js, TypeScript (tsc executable, tsconfig, @types/node), Git state, database tools (Alembic, Prisma), Docker, PM2, disk space
- Generates actionable warnings: missing `node_modules`, non-executable `tsc`, missing `@types/node`, missing system python with venv present
- Supports workdir argument for cross-project scanning

**`agents/_env-preflight-protocol.md` — Agent Protocol:**
- **Phase 1: Environment Audit** — Run `env-preflight.sh` or manual equivalents
- **Phase 2: Pin Environment Facts** — Lock interpreter paths, package state, binary locations for the session
- **Phase 3: Diagnostic Discipline** — The "2-Failure Rule": after 2 consecutive failures of the same operation, STOP executing and switch to diagnostic mode
- **Phase 4: Parallel Execution Rules** — Never parallelize commands that modify the same environment
- Error→Diagnosis Map: maps common error signals to correct diagnostic actions (not retry variations)
- Hypothesis Ranking: environment mismatch → config error → code bug → platform issue
- Anti-pattern table: documents the most common LLM agent failure modes with correct alternatives
- Forge pipeline integration: env-preflight runs in Phase 1 (IGNITE) before any story execution

---

## [2.0.61] - 2026-03-17

### Changed — Documentation & Help Sync for 8-Gate Pipeline

- Updated all references from "T0-T6" / "7 tiers" to "T0-T7" / "8 tiers" across:
  - README.md (badge, What's New, command reference, ASCII mockup)
  - VS Code extension: gate-timeline.ts (T7 in reference list + "8 tiers" label), gate.ts (T7 in tier picker)
  - VS Code extension changelog (v1.2.0) and package.json version bump
  - site-docs: architecture.md (gate table, pipeline phase, micro-gates intro)
  - site-docs: getting-started.md (pipeline output, phase table, gate count)
  - site/index.html version references
- `/gate` command help text now shows `t7` as a valid tier

---

## [2.0.60] - 2026-03-17

### Added — T7: Deployment Pre-Flight Gate

**Problem**: The existing T0-T6 gate pipeline validates code quality but not deployment readiness. A real-world session revealed 4+ rounds of trial-and-error debugging in production caused by DB schema mismatches, CORS misconfiguration, and API contract violations — all detectable before deployment.

**DB Migration State (Sub-check 1):**
- Detects Alembic, Prisma, EF Core, Rails migration systems
- Compares current DB revision vs head revision
- Reports pending migrations with actionable `alembic upgrade head` / `prisma migrate deploy` commands
- Supports `backend/` subdirectory detection

**Environment Consistency (Sub-check 2):**
- Validates `CORS_ORIGINS` includes `www.` variant when apex domain is listed
- Checks `DATABASE_URL` is present in backend `.env`
- Warns when frontend `VITE_API_URL` is hardcoded to a specific domain (should be relative)

**Endpoint Smoke Test (Sub-check 3):**
- Probes common backend ports (8000, 8005, 8080, 3000, 5000) for running servers
- Checks for 500 errors on health/API endpoints
- Skips gracefully when no server is running (never blocks non-deployed projects)

**API Contract Validation (Sub-check 4):**
- Scans frontend source for `page_size`/`pageSize`/`limit` values exceeding 100
- Warns on constraint violations between frontend requests and typical backend limits

**Pipeline Integration:**
- T7 runs as the final gate in both sequential and parallel modes
- Available via `/gate t7` in sf_cli, `sf-runner.mjs --gate T7`, and VS Code extension
- Graceful degradation: skips entirely for projects without deployable backends

### Tests
- 6 new tests: skip (no backend), pass (clean project), warn (hardcoded URL), warn (CORS www), fail (missing DATABASE_URL), warn (page_size contract)
- Total: 1,788 tests passing across 77 files

---

## [2.0.59] - 2026-03-16

### Added — CLI Support for Jurisdiction & Quality Routing

**Config Command:**
- `data_jurisdiction` and `quality_fallback` added to editable config keys
- Users can now set jurisdiction mode via `/config data_jurisdiction eu` or `/config data_jurisdiction strict`
- Quality fallback toggled via `/config quality_fallback true`

**Status Command:**
- Shows active jurisdiction mode when not `"none"` (e.g., `Jurisdiction: eu`)
- Shows quality fallback state when enabled

**Documentation:**
- Updated README "What's New" section for v2.0.59
- Site version bumped to 2.0.59

---

## [2.0.58] - 2026-03-16

### Added — Jurisdiction-Aware Model Routing

**Jurisdiction Guards (FR-001, FR-002):**
- `data_jurisdiction` config field: `"none"` (default), `"eu"`, `"strict"`
- `"eu"` mode: simple tasks always local, complex tasks allowed to cloud with logged warning. Throws `JurisdictionError` if local is unhealthy for simple tasks.
- `"strict"` mode: ALL tasks forced local. Cloud is never selected. Overrides even explicit routing rules.
- Works with `route_local_first` enabled or disabled — jurisdiction takes precedence.

**Quality-Gate Fallback (FR-003, FR-004):**
- `quality_fallback` config field (boolean, default false)
- `checkOutputQuality()` heuristic: empty response, refusal patterns, length proportionality, alphanumeric ratio
- Zero LLM calls — purely regex/heuristic based, <1ms execution

**Declarative Routing Rules (FR-005):**
- `[routing.rules]` TOML section with per-task-type overrides: `security = "cloud"`, `documentation = "local"`, `default = "auto"`
- Task type detection via keyword matching: security, orchestration, code_generation, documentation, testing
- Rules evaluated before the keyword classifier, after jurisdiction guards

**Routing Decision Logging (FR-006):**
- Every `RoutingDecision` now includes `jurisdictionBlocked` flag
- `JurisdictionError` thrown with actionable message when jurisdiction blocks required cloud routing

### Tests
- 24 new tests: 3 task type detection, 6 jurisdiction guards, 7 routing rules, 8 quality checks
- Total: 1,782 tests passing across 77 files

---

## [2.0.57] - 2026-03-16

### Added — VS Code Extension: Live Gate Execution

**sf-runner.mjs — ESM/CJS Bridge:**
- **Runner Script** (`sf_cli/bin/sf-runner.mjs`): ESM wrapper that loads sf_cli core modules and executes operations via JSON stdout. Solves the ESM/CJS incompatibility between sf_cli (ESM) and VS Code extensions (CJS/esbuild).
- Supports `--gate-all`, `--gate T1`, `--scan-deps`, `--report`, `--metrics` with `--workdir` and `--target` options
- Sets `SF_FRAMEWORK_ROOT` automatically so `anvil.sh` discovery works from any location

**VS Code Extension — Real Operations:**
- **Bridge Rewrite** (`bridge.ts`): Active operations (gates, dep scan, reports) now call `sf-runner.mjs` via `child_process.execFile`. Passive data (telemetry, audit, perf) still read JSONL directly.
- **Run All Gates** — executes real T0-T6 quality gates and displays results in Gate Timeline
- **Run Single Gate** — executes individual gate tiers with real output
- **Scan Dependencies** — runs actual npm/pip/dotnet vulnerability analysis
- **View Quality Report** — generates live quality report from telemetry data
- **Show Metrics** — aggregates real telemetry with industry baselines

**npm Package:**
- Added `sf_cli/bin/` and `sf_cli/dist/` to npm `files` array so the extension works after global install

### Changed
- Updated gate command error messages to reference sf-runner availability
- Extension bridge now uses subprocess execution instead of returning null for active operations

---

## [2.0.56] - 2026-03-16

### Added — Phase 3: Make It the Standard

**Team & Cloud Mode (Epic 7):**
- **Team Config** (`team-config.ts`): Load and validate `skillfoundry.team.json` with org-wide gate thresholds, banned patterns, approved models, memory sync, and skill version pins
- **Audit Log** (`audit-log.ts`): Append-only JSONL gate decision log with UUID, actor detection (GitHub/GitLab/Azure/CircleCI), streaming reader, rotation at 10K entries
- **Policy Engine** (`policy-engine.ts`): Policy-as-code enforcement checking approved models, memory sync status, and skill version pins against team config

**Pipeline Performance (Epic 8):**
- **Parallel Gates** (`gates.ts`): Wave-based parallel execution — T0+T1+T2 concurrent → T3 sequential → T4+T5 concurrent → T6 sequential
- **Gate Cache** (`gate-cache.ts`): SHA256 file-hash caching with composite key (`gate:hash:version`), 24h TTL, auto-invalidation on gate logic version bump
- **P95 Tracker** (`perf-tracker.ts`): Gate latency recording to `perf.jsonl`, percentile computation, P95 threshold enforcement (T3 excluded)

**Automated Distribution (Epic 9):**
- **sf publish** (`publish.ts`): Discover skills from `agents/`, transform to 5 platform formats (Claude, Cursor, Copilot, Codex, Gemini), skip unchanged files, dry-run mode
- **sf upgrade** (`upgrade.ts`): Check npm registry for latest version, semver comparison, `--check` flag for CI
- **sf audit** (`audit.ts`): Query audit log with `--recent N`, `--gate T1`, `--verdict fail`, `--json`, `--rotate`

**Benchmark & Mutation Testing (Epic 10):**
- **Quality Benchmark** (`quality-benchmark.ts`): 50 static scenarios (25 bad + 25 good) with deterministic regex classifier, >90% accuracy, per-category breakdown

### Security
- Path traversal hardening: `resolve()` normalization applied to `audit-log.ts`, `gate-cache.ts`, `perf-tracker.ts`, `publish.ts` (matching `team-config.ts` pattern)
- 0 critical, 0 high, 0 medium vulnerabilities (4 MEDIUM findings remediated)

### Tests
- 179 new tests across 8 test files (team-config, audit-log, gate-cache, policy-engine, publish, upgrade, quality-benchmark, perf-tracker)
- Total: 1,758 tests passing across 77 files

---

## [2.0.55] - 2026-03-16

### Added — Phase 2: Make It Excellent

**Runtime Intelligence (Epic 5):**
- **Message Bus** (`message-bus.ts`): Pub/sub event system with typed channels, wildcard subscriptions, and backpressure control
- **Agent Pool** (`agent-pool.ts`): Managed pool of reusable agent instances with lifecycle management, concurrency limits, and health monitoring
- **Embedding Service** (`embedding-service.ts`): Text-to-vector embedding with provider abstraction (Anthropic, OpenAI, local), batching, and caching
- **Vector Store** (`vector-store.ts`): In-memory vector similarity search over project source files with configurable chunking and path confinement
- **Weight Learner** (`weight-learner.ts`): Adaptive quality gate weight adjustment based on historical pass/fail patterns and project-specific calibration
- **Dependency Scanner** (`dependency-scanner.ts`): npm audit integration with CVE severity mapping, fix recommendations, and JSONL output
- **Report Generator** (`report-generator.ts`): Structured pipeline run reports in JSON and Markdown with gate breakdowns, cost summaries, and trend data

**Security Scanners (Epic 6):**
- **Gitleaks Scanner** (`gitleaks-scanner.ts`): Secret detection via Gitleaks binary with SHA-256 hashed findings (raw secrets never stored), redacted output, and configurable rulesets
- **Checkov Scanner** (`checkov-scanner.ts`): Infrastructure-as-code scanning with framework selection, skip-check support, and whitelist-validated CLI arguments
- **Semantic Search** (`semantic-search.ts`): Natural language code search combining vector similarity with keyword fallback

**CLI Commands (3 new, total: 23):**
- **`sf runtime`**: Show runtime intelligence status — message bus stats, agent pool health, embedding cache, vector store index
- **`sf prd review <path>`**: Score a PRD on 4 dimensions (completeness, specificity, consistency, scope) with color-coded output, progress bars, and `--json` mode
- **`sf lessons`**: Query and manage knowledge bank entries from the terminal

### Fixed

- **Secret exposure in Gitleaks findings**: Raw secret values were stored in `GitleaksFinding.secret` field — replaced with SHA-256 hash (`secretHash`) for deduplication only. Raw secrets are never persisted in any data structure.
- **Command injection via `execSync`**: Gitleaks and Checkov binary detection used `execSync('which ...')` which allows shell injection — replaced with `execFileSync` array-arg invocation across all scanners.
- **Path traversal in PRD review**: `sf prd review ../../etc/passwd` could read files outside the project — added `resolve()` + `startsWith(workDir)` confinement check.
- **Path traversal in Vector Store**: Source directories could escape the work directory via `../` — constructor now validates all `sourceDirs` are confined within `workDir`.
- **Unsafe CLI argument injection in Checkov**: Framework and skip-check values were passed unsanitized to the CLI — added whitelist regex validation (`/^[a-zA-Z0-9_.-]+$/`).

### Security

- 5 security findings from Phase 4 audit (1 CRITICAL, 4 HIGH), all fixed before release
- SHA-256 hashing for secret deduplication — zero raw secret storage
- `execFileSync` with array args for all external tool invocation (shell injection prevention)
- Path confinement enforced in vector-store and prd-review commands
- Whitelist validation for all user-supplied CLI arguments passed to external tools

### Tests

- 697 new tests across 17 test files: message-bus (48), agent-pool (52), embedding-service (44), vector-store (56), weight-learner (38), dependency-scanner (42), report-generator (46), gitleaks-scanner (63), checkov-scanner (58), semantic-search (34), prd-review (28), prd-scorer (36), runtime command (22), lessons command (18), consent (12), baseline-collector (8), telemetry (92)
- Total: 1,579 tests across 69 files, all passing

---

## [2.0.52] - 2026-03-16

### Added — Phase 1: Make It Reachable

**Distribution (Epic 1):**
- **GitHub Actions release workflow** (`.github/workflows/release.yml`): Automated npm publish with provenance + GitHub Releases on semver tag push. Includes tag-version validation with semver regex.
- **Homebrew formula** (`homebrew/skillfoundry.rb`): `brew install samibs/tap/skillfoundry` for macOS
- **curl|bash installer** (`scripts/install-global.sh`): One-liner install with Node.js version check, root detection, EACCES handling, explicit npm registry URL
- **npm downloads badge** added to README

**Documentation Site (Epic 2):**
- **Docusaurus 3 site** (`site-docs/`): Full docs site with dark mode, offline search, GitHub Pages deploy
- **Getting Started guide**: 5-step walkthrough (install → init → PRD → forge → metrics) with time estimates
- **Architecture deep-dive**: Pipeline flow, agent state machine, T0-T6 gate tiers, memory system — 3 Mermaid diagrams
- **Configuration reference**: All config.toml options, VS Code extension settings, env vars, CLI flags
- **3 Recipes**: Next.js integration, TypeScript monorepo, Azure DevOps pipeline
- **Search documentation**: Local search + Algolia migration path

**Telemetry MVP (Epic 3):**
- **`sf metrics baseline`**: Captures code quality snapshot (LOC, test count, lint errors, type errors, language detection)
- **`sf report --html`**: Self-contained HTML dashboard with Chart.js trends, gate breakdown, baseline comparison, dark theme
- **Telemetry consent** (`consent.ts`): Opt-in mechanism with TOML persistence, non-TTY defaults to opted_out (GDPR), in-memory caching
- **Privacy policy** (`docs/PRIVACY.md`): Complete data handling documentation

**VS Code Extension (Epic 4):**
- **Version 1.0.0**: Marketplace-ready with icon, gallery banner, badges
- **"Open Last Report" command**: Opens `.skillfoundry/report.html` in browser from command palette
- **Publish workflow** (`.github/workflows/publish-vscode.yml`): Manual + tag-triggered Marketplace publish

### Fixed

- **npm package missing platform directories**: Added `.agents/`, `.claude/`, `.copilot/`, `.cursor/`, `.gemini/` to `files` field — fixes `skillfoundry init` failing on npm-installed package when platform files not found
- **Command injection in baseline collector**: Replaced `execSync` with `execFileSync` for eslint/tsc invocation (prevents shell injection via binary paths)
- **Tag version injection**: Added semver regex validation in release workflow
- **Consent runtime validation**: Added explicit type guard before TOML write
- **VS Code publish permissions**: Added explicit `permissions: contents: read` block

### Security

- 6 security findings from Phase 4 audit, all fixed before release
- `execFileSync` used for all external tool invocation in baseline-collector.ts
- HTML report escapes all dynamic values (XSS prevention verified by 16 tests)

### Tests

- 46 new tests: baseline-collector (12), report-html (16), consent (18)
- Total: 882 tests across 52 files, all passing

---

## [2.0.51] - 2026-03-15

### Fixed — Installer Non-Interactive Mode & npm Link

- **TTY auto-detection in `install.sh`**: Installer now auto-enables `YES_MODE` when stdin is not a TTY (e.g., invoked via `npx skillfoundry init` or `execSync`). Previously, interactive `read` prompts would fail silently when existing platform directories were detected, causing the installer to abort.
- **`npm link` setup**: Configured user-owned npm prefix (`~/.npm-global`) so `skillfoundry` CLI can be linked globally without `sudo`. Running `npm link` from the framework root makes `skillfoundry init` available from any directory.
- **Extension activation messages**: Updated VS Code extension messages to reference the install script as primary method alongside `npx skillfoundry init`.
- **Root `package.json` version sync**: Aligned root package version with framework version (was stuck at 2.0.42).

---

## [2.0.50] - 2026-03-15

### Added — VS Code Extension (`skillfoundry-vscode`)

Native VS Code extension that brings quality gates, telemetry dashboards, and forge pipeline monitoring directly into the editor. A UI layer over the existing sf_cli engine — not a rewrite.

**New Package: `skillfoundry-vscode/`**

*Sidebar Providers (7):*
- **Quality Dashboard** (`dashboard.ts`): TreeDataProvider showing gate pass rate, total runs, trend, security findings, cost, duration, tests, and window — color-coded by status
- **Gate Timeline** (`gate-timeline.ts`): T0-T6 gate results with pass/fail/warn icons, duration, and expandable detail per tier
- **Dependency CVE Tree** (`dependency.ts`): Vulnerable dependencies grouped by severity (critical→high→moderate→low), clickable advisory links
- **Forge Monitor** (`forge-monitor.ts`): Real-time forge pipeline progress — watches `forge-state.json` for phase transitions, story count, elapsed time
- **Inline Diagnostics** (`diagnostics.ts`): Maps gate findings to VS Code DiagnosticCollection — squiggly underlines on banned patterns (T1) and security issues (T4)
- **CodeLens** (`codelens.ts`): "Run T3 (Tests)" above test files, "Run T1 (Patterns)" + "Run T4 (Security)" above source files
- **Status Bar** (`statusbar.ts`): Gate pass rate with color coding (green ≥90%, yellow ≥70%, red <70%), click to open metrics

*Commands (12):*
- `skillfoundry.gateAll` — Run all quality gates (T0-T6) with progress notification
- `skillfoundry.gate` — Run single gate tier via QuickPick selection
- `skillfoundry.gateFile` — Run gate on current file (T1, T4, or T1+T4)
- `skillfoundry.forge` — Start forge pipeline in integrated terminal (Full/Blitz/Dry Run)
- `skillfoundry.metrics` — View quality metrics in output channel
- `skillfoundry.report` — Quality report in webview panel with CSP headers
- `skillfoundry.memory` — Memory recall QuickPick with fuzzy search
- `skillfoundry.prd` — Create PRD via sf CLI (input validated against shell injection)
- `skillfoundry.scanDeps` — Run dependency vulnerability scan
- `skillfoundry.benchmark` — Run quality benchmark in terminal
- `skillfoundry.hook` — Git hook management (install/uninstall/status)
- `skillfoundry.refresh` — Refresh all sidebar providers

*Architecture:*
- Bridge pattern: `SfBridge` class wraps sf_cli core modules via `require()` — no subprocess spawning, no HTTP server
- esbuild bundling: 41.6kb CJS bundle targeting Node 20 (< 5MB marketplace limit)
- File watcher: `FileSystemWatcher` on `telemetry.jsonl` with 2-second debounced auto-refresh
- Graceful degradation: placeholder commands when `.skillfoundry/config.toml` not found

**Security Hardening (8 findings remediated):**
- CRITICAL: Command injection — shell metacharacter rejection + env var passthrough for PRD input
- HIGH: Path traversal — `__dirname`-relative sf_cli path resolution, removed workspace-parent traversal
- HIGH: Unsafe `require()` — pinned to resolved absolute paths only
- HIGH: Missing CSP — added `Content-Security-Policy` meta tag to webview panels
- MEDIUM: Incomplete HTML escaping — added `"` and `'` to `escapeHtml()`
- MEDIUM: Unvalidated URL — scheme check (`https://`/`http://` only) for advisory links
- MEDIUM: Path traversal in diagnostics — workspace boundary validation on parsed file paths
- MEDIUM: No schema validation — runtime type checking on all parsed JSON entries from workspace

**Tests:**
- 28 tests across 2 test files (bridge: 13, providers: 15)
- Full vscode module mock for provider testing
- 0 TypeScript errors, clean esbuild bundle

---

## [2.0.49] - 2026-03-15

### Added — Quality Intelligence & Developer Integration Layer

Closes the measurability gap: SkillFoundry can now prove its quality gates work with hard numbers. Adds telemetry, dependency scanning, git hooks, quality reports, benchmarks, and memory weight learning.

**Quality Telemetry Engine (`telemetry.ts`):**
- Append-only JSONL event tracking (`.skillfoundry/telemetry.jsonl`) for forge runs, gate executions, security scans, dependency scans, hook executions, and benchmarks
- Auto-rotation at 5MB with 2 archives. Non-blocking writes — never breaks the pipeline
- Rolling window aggregation with trend detection (improving/declining/stable)
- Industry baseline comparison: Veracode 45% vuln rate, CodeRabbit 1.7x issue ratio, GitClear 5.7% churn, Stack Overflow 29% AI trust

**Dependency Vulnerability Scanner (`dependency-scanner.ts`):**
- Auto-detects project type: Node.js (npm audit), Python (pip-audit), .NET (dotnet list), Rust (cargo-audit), Go
- Integrated into T4 security gate alongside Semgrep SAST — combined verdict
- Findings merged into SecurityReport with severity levels (critical/high/moderate/low)
- Command allowlist prevents shell injection (security hardened)

**Git Hook Integration (`hook.ts`):**
- `sf hook install` — installs pre-commit (T0+T1) and pre-push (T2+T4) quality gates as standard git hooks
- `sf hook uninstall` — removes SF hooks, restores backups
- `sf hook status` — shows current hook state
- Configurable via `.skillfoundry/hooks.toml` (which gates, fail action, timeouts)
- Backs up existing hooks to `.bak` files before overwriting

**Memory Weight Learning (`weight-learner.ts`):**
- Retrieval boost (+0.05/retrieval), validation pass boost (+0.03), validation fail penalty (-0.1)
- Time-based decay (-0.01/week for unretrieved entries), floor 0.1, ceiling 1.0
- Path traversal protection on reality_anchor.test_file checks

**Quality Report Generator (`report-generator.ts`):**
- Markdown and JSON export with executive summary, security posture, gate performance, trends
- Industry baseline comparison tables with delta and percentile
- Actionable recommendations based on data

**5 New CLI Commands:**
- `/gate <t0-t6|all> [target]` — Run single or all quality gates with telemetry recording
- `/metrics [--window N] [--baseline] [--json]` — Quality metrics dashboard with trends
- `/report [--format md|json] [--output path]` — Generate exportable quality reports
- `/benchmark` — Compare quality against industry baselines
- `/hook install|uninstall|status` — Manage git hook integration

**Security Hardening (6 findings remediated):**
- HIGH: Command injection — allowlist in dependency-scanner.ts `isCommandAvailable()`
- MEDIUM: Path traversal — `resolve()` + `startsWith()` guard in report.ts `--output`
- MEDIUM: Shell injection — gate name regex `/^t[0-6]$/` + timeout sanitization in hook.ts
- MEDIUM: Shell metachar rejection in gate.ts target parameter
- MEDIUM: Path traversal guard in weight-learner.ts reality_anchor
- MEDIUM: fail_action enum restriction in hook.ts

**Infrastructure:**
- 3 new LogCategory values: `telemetry`, `weight-learner`, `dep-scanner`
- 101 new tests across 6 test files (telemetry: 21, dependency-scanner: 20, weight-learner: 19, report-generator: 13, hook: 11, commands-new: 19)
- Total: 836 tests, 49 test files, 0 TypeScript errors
- CLI commands: 15 → 20

---

## [2.0.48] - 2026-03-15

### Added — Passive Memory Engine (inspired by claude-mem)

Integrated 3 memory intelligence patterns from claude-mem research into the SkillFoundry pipeline. These address manual harvest dependency, blind session starts, and flat recall inefficiency.

**Phase 1 — Auto-Harvest Hooks:**
- **Rule-based extraction engine** (`auto-harvest.ts`): Passively captures knowledge from pipeline events — story completions, gate failures, fixer interventions, and session summaries. Zero secondary LLM calls. Produces canonical JSONL entries via `MemoryBuffer`.
- **4 extraction rules**: FILE_CREATED → fact, DEPENDENCY_ADDED → decision, GATE_FAILURE → error, FIXER_SUCCESS → error. Tags auto-extracted from file paths.
- **Pipeline integration**: Hooks into story completion, Anvil gate failures, and fixer runs. Entries auto-flush every 3 stories via existing `MemoryBuffer`.

**Phase 2 — Context Primer:**
- **Primer generator** (`context-primer.ts`): Generates a compact (~400-800 token) markdown index from all `memory_bank/knowledge/*.jsonl` files. Shows entry counts by type, top-5 by weight, 5 most recent, estimated token costs.
- **Staleness detection**: Warns if newest entry is >7 days old.
- **Session integration**: `session-init.sh` now generates primer at session start (Step 5). `session-close.sh` regenerates primer for next session (Step 2.5).
- **Shell script** (`generate-primer.sh`): Standalone primer generation with jq-based JSON parsing.

**Phase 3 — Layered Recall:**
- **Progressive disclosure** (`layered-recall.ts`): Three search modes — index (compact table, ~400 tokens), preview (200-char summaries, ~600 tokens), full (complete canonical entries). 3-5x token savings over flat dump.
- **TF-IDF scoring**: Matches `semantic-search.sh` algorithm — exact phrase (+100), word match (+10), type bonus (+20), weight bonus (+10*w), tag bonus (+5).
- **Filter support**: `--type`, `--min-weight`, `--since` (relative: 7d/30d/4w, or ISO date), `--tags`, `--limit`.
- **New `/recall` command**: Progressive recall with index → preview → full workflow. Synced to all 5 platforms.

**Infrastructure:**
- 3 new log categories: `harvest`, `recall`, `primer`
- 54 new tests across 3 test files (13 + 22 + 19)
- Total: 643 tests, 40 test files
- `/recall` command synced to all 5 platforms (Claude Code, Copilot, Cursor, Codex, Gemini)

---

## [2.0.47] - 2026-03-15

### Added — Swarm Intelligence Patterns (inspired by MiroFish)

Integrated 5 resilience and quality patterns from multi-agent swarm intelligence research into the SkillFoundry pipeline. These address truncated LLM output recovery, research-before-acting enforcement, progressive artifact persistence, batched memory writes, and agent introspection.

**Phase 1 — Output Resilience:**
- **LLM output repair** (`output-repair.ts`): Structural auto-repair for truncated LLM responses — closes unclosed JSON brackets/braces (nesting-aware stack), removes trailing commas, strips markdown fences, closes unclosed code blocks. Never modifies content between delimiters.
- **Temperature decay retry** (`withTemperatureDecay()`): When output is malformed, retries with progressively lower temperatures (0.7 → 0.4 → 0.1). Attempts structural repair before retrying. Returns best available repair if all attempts fail.
- **JSON validation** (`isValidJSON()`): Quick validation utility for repair pipeline.

**Phase 2 — Research Enforcement:**
- **ReACT gate** (`react-gate.ts`): Blocks file writes (Edit/Write) until the agent has performed at least 2 read operations (Read/Grep/Glob/Bash). Enforced for coder, secure-coder, data-architect, and refactor agents. Exempt: tester, docs, ops. Tracks per-agent compliance stats.
- **ReACT enforcement protocol** (`agents/_react-enforcement.md`): Shared protocol document included by 4 code-generating agents. Requires verification summary before each write.
- **Agent protocol updates**: ruthless-coder, secure-coder, data-architect, and refactoring-strategist now include ReACT enforcement.

**Phase 3 — Progressive Persistence:**
- **Story deliverable persistence** (`progressive-persist.ts`): After each story completes, writes a delivery manifest to `delivery/{prd-id}/STORY-{N}.md` with file lists, test files, commit stubs, and decisions. Survives context exhaustion.
- **Forge state snapshots** (`saveForgeState()/loadForgeState()`): Persists pipeline state to `.skillfoundry/forge-state.json` after each batch. Enables resume after interruption.

**Phase 4 — Knowledge Buffering:**
- **Memory write buffer** (`memory-buffer.ts`): Queues knowledge entries during forge execution and flushes to `memory_bank/knowledge/*.jsonl` every 3 completed stories. Auto-flushes on pipeline exit. Deduplicates against existing content. Canonical schema compliant.

**Phase 5 — Agent Introspection:**
- **Decision trail** (`decision-trail.ts`): Ring buffer (max 50 entries) capturing agent decisions — what was considered, what was chosen, and why. Per-agent filtering, markdown formatting for `/explain last`, session singleton.

**Infrastructure:**
- 5 new log categories added to logger: `repair`, `react`, `persist`, `memory`, `decision`
- 87 new tests across 5 test files (total: 589 tests, 37 files)
- All 5 platforms synced (220 files)

---

## [2.0.46] - 2026-03-15

### Added — Industry Prompt Patterns Integration

Integrated 11 high-impact patterns distilled from an analysis of 12 leading AI coding tools (Cursor, Devin, Lovable, Manus, Bolt, Cline, Codex CLI, RooCode, Replit, Same.dev, v0, Windsurf) into SkillFoundry's skill library. These patterns represent techniques that multiple tools independently converged on — making them de facto industry standards.

**Phase 1 — Agent Behavior Hardening:**
- **Think-before-act reasoning gate** (FR-001): 8 skills (architect, coder, debugger, fixer, review, refactor, tester, secure-coder) now require a mandatory reasoning block before every file edit or tool call. Agents must state what they'll do, why, risk level, and alternatives considered.
- **Post-edit verification** (FR-002): The coder skill now runs the project's type-checker/linter after every file edit, not just at the end of the pipeline.
- **3-attempt escalation protocol** (FR-003): 7 skills now stop and escalate after 3 failed attempts with a structured failure report, instead of looping indefinitely.
- **Never-modify-tests rule** (FR-004): The tester skill is restricted to test files only — it cannot edit application code to make tests pass.
- **Safe/unsafe command classification** (FR-005): The secure-coder classifies all shell commands as SAFE, UNSAFE, or BLOCKED before execution.
- **Pre-commit secret scanning** (FR-006): Ship and release skills scan staged files for API keys, tokens, passwords, private keys, and `.env` files before every commit.

**Phase 2 — Specialized Skill Enhancements:**
- **Architect file restriction** (FR-007): Architect can only create/modify `.md`, `.mmd`, `.puml`, `.drawio` — must delegate code to coder.
- **Auto-capture decisions to memory** (FR-008): Memory curator automatically captures architectural decisions during agent execution.
- **Bulk refactor mode** (FR-009): Refactor skill supports regex+LLM bulk operations for 10+ location changes.
- **Migration-file-required** (FR-010): Data-architect rejects schema changes without migration files.
- **Accessibility checklist** (FR-011): UX/UI skill includes mandatory a11y checklist (semantic HTML, ARIA, keyboard, contrast, forms, media).

All changes applied to agent sources (`agents/`) and synced across 5 platforms (220 files). PRD: `genesis/2026-03-15-prompt-analysis-integration.md`.

---

## [2.0.45] - 2026-03-14

### Changed — Auto-Init Git for New Projects

- **`forge.md`**, **`go.md`**, **`goma.md`**, **`prd.md`**: Git repository check no longer halts the pipeline and asks for user confirmation. When no `.git/` directory is detected, the framework now automatically runs `git init && git add -A && git commit -m "initial commit"` and continues. Git is a prerequisite for rollback, state tracking, and story completion — there is no valid reason to skip it, so the confirmation prompt was unnecessary friction on new projects.

---

## [2.0.44] - 2026-03-14

### Added — Slash-Command Safeguard Parity

All pipeline safeguards from the CLI (`sf forge`) are now enforced in slash-command mode (`/forge`, `/go`) when running inside Claude Code, Copilot, Cursor, Codex, or Gemini. Previously, the TypeScript enforcement (test gates, circuit breaker, session recorder, anomaly detection) only ran through the CLI — slash commands followed markdown instructions that lacked these protections.

**forge.md — 5 Mandatory Safeguards:**
- **Build Health Baseline**: Verify the project builds (type check + build) before starting any story execution. Pre-existing errors are tracked separately from story-induced failures.
- **Test Existence Gate**: After each story, verify test files were created. Triggers tester remediation if missing. Rejects vacuous passes (test runner exits 0 with zero test files).
- **Circuit Breaker**: Track error signatures across stories. If 2+ consecutive stories fail with the same error pattern (e.g., `Can't resolve 'tailwindcss'`), halt the pipeline immediately with root cause guidance instead of burning tokens on a systemic blocker.
- **Session Issue Tracking**: Maintain a running issue log (severity, category, story, detail, remediation) for every gate failure, test gap, build warning, and circuit breaker activation.
- **Anomaly Detection**: Post-pipeline checklist catches contradictions — zero tests with completions, PASS verdict with failures, recurring errors that weren't halted, high cost with zero delivery.

**go.md — Story Execution Hardening:**
- Build baseline check inserted as step 1.5 before first story.
- Circuit breaker state (`consecutiveFailures`, `lastErrorSignature`) maintained across all stories with check at the top of each story loop.
- Test existence gate added after implementation, before marking story DONE.
- Error signature extraction and tracking on story failure; reset on success.
- Anomaly detection and issue report compilation in feature completion phase (step 3a) — blocks COMPLETE status if anomalies detected.

### Changed

- **`forge.md`**: Phase 2 now includes "MANDATORY SAFEGUARDS" section with 5 numbered safeguards and pseudocode decision logic.
- **`go.md`**: Story execution flow restructured with circuit breaker check, test existence gate, error tracking on failure/success, and anomaly detection before completion.

---

## [2.0.43] - 2026-03-14

### Added — Test Enforcement & Circuit Breaker

**Test Enforcement Pipeline Gates:**
- **Test existence gate** in FORGE phase (`pipeline.ts`): After each story completes T2/T5, the pipeline now checks if test files were created/modified via `git diff` and `git ls-files`. If no test files are found, a tester remediation agent is triggered to write tests. Stories that still lack tests after remediation are flagged with `testsMissing: true`.
- **Tester remediation prompt** (`TESTER_REMEDIATION_PROMPT`): Dedicated prompt for the tester agent that creates test files for implementations that shipped without tests. Runs with `maxTurns: 15` and is given the story content for context.
- **T3 gate enhancement** (`gates.ts`): T3 now fails on vacuous passes — when the test runner exits 0 but zero test files exist in the project. Also warns when completed stories have no matching test files via `checkStoriesHaveTests()`.
- **`countTestFiles()` and `checkStoriesHaveTests()`** helpers in `gates.ts`: Count test files across 9 naming conventions (`.test.ts`, `.spec.ts`, `.test.js`, `.spec.js`, `.test.tsx`, `.spec.tsx`, `test_*.py`, `*_test.go`, `*Tests.cs`) and cross-reference completed stories' "Files Affected" sections.
- **`testsMissing` field** on `StoryExecution` type: Tracks stories that completed implementation but failed to produce test files even after remediation.

**Circuit Breaker (Goal-Completion Bias Prevention):**
- **Pre-FORGE build health baseline** (`checkBuildHealth()`): Before starting any stories, the pipeline runs T2+T5 to establish whether the project builds cleanly. Emits `BUILD_BASELINE` warning if pre-existing build failures exist, so the pipeline can distinguish "story broke the build" from "build was already broken."
- **Repeated error detection** (`extractErrorSignature()`, `errorSimilarity()`): After each story failure, the pipeline extracts a normalized error fingerprint (stripping file paths, line numbers, and variable parts) and compares it to the previous story's failure. If similarity exceeds 60%, the failures are counted as consecutive.
- **Consecutive failure halt** (threshold: 2): When 2+ consecutive stories fail with the same error pattern, the pipeline halts with a `CIRCUIT_BREAKER` failure. Remaining stories are skipped instead of wasting tokens on a systemic blocker. FORGE phase status is set to `failed` with a detailed halt reason.
- **Blocker detection in `STORY_EXECUTION_PROMPT`**: New "BLOCKER DETECTION (CRITICAL)" section instructs the agent to stop and diagnose root causes when encountering the same error twice, instead of working around it. Specific guidance for dependency resolution failures (`Can't resolve`, `Module not found`) including workspace root verification.

### Changed

- **`STORY_EXECUTION_PROMPT`** (`pipeline.ts`): Now explicitly mandates writing test files (TEST REQUIREMENTS section) and includes blocker detection instructions (BLOCKER DETECTION section) that tell the agent to stop, diagnose, and report rather than loop.
- **`STORY_GENERATION_PROMPT`** (`pipeline.ts`): Stories now require a "Test Requirements" section and test files in "Files Affected". Includes enforcement warning that stories without test deliverables will be rejected.
- **`forge.md`** skill: Added TEST ENFORCEMENT documentation explaining the three-layer test gate (existence check → tester remediation → T3 TEMPER gate).
- **`stories.md`** skill: "Expected Changes (Anvil T4)" section now documents the mandatory test file requirement.

### Fixed

- **T3 vacuous pass bug**: Previously, `vitest run` or `npm test` exiting 0 with zero test files reported "All tests passed" — now correctly returns FAIL with "vacuous pass" explanation.
- **Zero-test forge runs**: The pipeline could previously complete 21 stories with zero test files and report PASS. Now impossible — test existence is enforced at story level (FORGE) and project level (TEMPER T3).

**Session Recorder (Issue Tracking & Anomaly Detection):**
- **`SessionRecorder` class** (`session-recorder.ts`): Real-time issue tracker that hooks into pipeline callbacks to capture gate failures, build errors, test gaps, security findings, and anomalies. Categorizes issues by severity (CRITICAL/HIGH/MEDIUM/LOW/INFO) and category (BLOCKER/TEST_GAP/BUILD_FAILURE/SECURITY/QUALITY/ANOMALY/CIRCUIT_BREAKER/DEPENDENCY/GATE_FAILURE).
- **Anomaly detection engine** (`detectAnomalies()`): Post-pipeline analysis that detects contradictions between reported status and actual evidence — zero tests with completions, PASS verdict with failures, all stories passed but TEMPER failed, high cost with zero completion, all micro-gates skipped.
- **Error pattern correlation** (`trackErrorPattern()`): Tracks normalized error signatures across stories and flags recurring patterns (2+ occurrences) as systemic blockers with likely root cause.
- **Dual-format reports**: Each pipeline run now produces `{runId}-issues.json` (machine-readable) and `{runId}-issues.md` (human-readable) alongside the run bundle. Markdown report includes: summary table, top remediations, blockers section, other issues table, anomalies, and recurring error patterns.
- **Pipeline integration**: Recorder is automatically instantiated at pipeline start and merged into callbacks. All existing user callbacks continue to work — the recorder is transparent. Report is written during DEBRIEF phase. `PipelineResult.sessionReport` field added with issue/blocker/anomaly counts and report path.
- **20 new tests** in `session-recorder.test.ts` covering issue recording, blocker counting, anomaly detection (5 anomaly types), callback integration (gate failures, circuit breaker, build baseline, test gaps, micro-gates, provider errors), report generation, file persistence, and error pattern tracking.

---

## [2.0.42] - 2026-03-13

### Added — Developer Experience & Adoption Improvements

- **Lightweight npm installation** (`package.json` + `bin/skillfoundry.js`): Three-tier installation path — `npx skillfoundry init` (quickest), `npm install -g skillfoundry` (persistent CLI), or `git clone` (contributors). Delegates to existing `install.sh`/`install.ps1` with platform flags and non-interactive mode support. Resolves [#7](https://github.com/samibs/skillfoundry/issues/7).
- **Model compatibility matrix** (`docs/model-compatibility.md`): Four-tier classification of AI models — Tier 1 (Full Pipeline: Claude Sonnet/Opus, GPT-4o, Grok-3), Tier 2 (Capable: Haiku, Gemini Flash, GPT-4o-mini), Tier 3 (Limited: large local models), Tier 4 (Basic: small local models). Documents feature requirements per tier, gate strictness configuration, and cost-optimized setups. Resolves [#8](https://github.com/samibs/skillfoundry/issues/8).
- **Model tier awareness in CLI** (`provider.ts`): `getModelTier()`, `getModelTierLabel()`, and `checkModelTierWarning()` functions detect configured model capabilities and emit warnings when using below-recommended tiers for pipeline features. Tier mappings for 18 known models with prefix-match fallback.
- **Example project** (`examples/todo-api/`): Complete Todo REST API example with a production-quality PRD (`genesis/todo-api.md`) — 6 user stories with Gherkin acceptance criteria, technical requirements (Express, SQLite, Zod, Vitest), security section, and data model. Demonstrates the full SkillFoundry workflow from PRD to `/forge`. Resolves [#9](https://github.com/samibs/skillfoundry/issues/9).

### Changed

- **README.md** — Quick Start section rewritten with three installation tiers (npx, npm global, git clone). Added Windows equivalents for all options. Added references to model compatibility docs and example project. Documentation table expanded with new entries.

---

## [2.0.41] - 2026-03-13

### Added — Smart Output Compression

- **Output compressor** (`output-compressor.ts`): Command-aware output compression that reduces tool output tokens by 60-90% before they reach the LLM context. Detects command type via regex pattern matching (<1ms overhead) and applies type-specific compression. Ten compressor strategies:
  - `git status` — strips hint lines and section headers, keeps file paths (~80% reduction)
  - `git push/pull/add/commit/fetch/checkout/merge/stash` — reduces verbose output to one-liners (~90%)
  - `git log` — one line per commit: `abc1234 message` (~80%)
  - `git diff` — strips index/mode metadata, collapses unchanged regions (~60%)
  - Test runners (vitest, jest, pytest, cargo test, go test) — all-pass → summary only, failures → failure blocks only (~90%)
  - Build/lint (tsc, eslint, biome, ruff, clippy) — groups errors by file, deduplicates identical messages (~80%)
  - Package install (npm, pnpm, pip, cargo build) — strips progress bars and warnings, keeps summary (~85%)
  - Docker/kubectl — compact tables, deduplicated logs (~75%)
  - Log deduplication — heuristic fallback that collapses consecutive repeated lines with counts (~60%)
  - Default — passthrough to existing 30KB truncation (unchanged behavior)
- **35 new tests** in `output-compressor.test.ts` covering all compressor strategies, command detection ordering, error-aware behavior, and edge cases.

### Changed

- `executor.ts` — `executeBash()` now calls `compressOutput()` before `truncate()`. Compression runs first, truncation acts as safety net.
- **458 total tests passing** (35 new, 0 regressions).

---

## [2.0.40] - 2026-03-13

### Added — Pipeline Resilience

- **Early git pre-flight check**: `/go`, `/forge`, `/goma`, and `/gosm` now verify the project is a git repository before starting any work. `/goma` also blocks on dirty working trees. `/prd` advises git init after PRD creation. Prevents late-stage failures when git is needed for rollback and state tracking.
- **Batch-aware story execution**: Stories are now executed in batches of 3-5 (respecting dependency order). After each batch, state is persisted to `.claude/state.json` and context is compacted. If context budget exceeds 60%, the pipeline stops gracefully with explicit resume instructions (`/go --resume`, `/goma --resume`, `/gosm --resume`). Prevents context exhaustion from silently killing long-running pipelines.
- **Delivery audit gate**: Mandatory post-execution audit that compares planned deliverables (from story index) against actually created files. Reports the delta with specific missing files listed. Runs automatically in `/go` (Phase 3.5), `/forge` (Phase 2.5), `/goma` (Phase 3.0), and `/gosm` (Phase 4). Prevents the scenario where stories are listed as complete but their files were never created.

### Changed

- `/go` story execution flow restructured from per-story to batched execution with state persistence between batches.
- `/forge` output format updated to include Phase 2.5 (Delivery Audit) in pipeline summary.
- `/goma` section numbering updated (2.3-2.5) to accommodate new batch execution section.
- `/gosm` gains new Phase 4 (Delivery Audit) and section 2.3 (Batch Execution).
- `/version` in-app help updated with current framework stats (56 agents, 63 skills, 5 platforms, 6 providers) and recent milestone history.

---

## [2.0.39] - 2026-03-12

### Added — Native Debugger Integration

- **Chrome DevTools Protocol (CDP) adapter** (`debugger-cdp.ts`): Full CDP client with MinimalWebSocket for Node 20 compatibility. Handles Debugger and Runtime domains — breakpoints, stepping, scope inspection, expression evaluation, call stack retrieval.
- **Debug session manager** (`debugger.ts`): Singleton session lifecycle with `node --inspect-brk=0 --enable-source-maps` process spawning. Auto-detects runtime from project files (tsconfig.json → node, requirements.txt → python, Cargo.toml → lldb). Configurable timeout (default 60s, max 5min) with SIGTERM → SIGKILL escalation.
- **6 debug tools** for AI agents: `debug_start`, `debug_breakpoint`, `debug_inspect`, `debug_evaluate`, `debug_step`, `debug_stop`. All return structured JSON responses — no raw terminal output.
- **Async tool execution**: `executeTool()` now returns `ToolResult | Promise<ToolResult>`. The agentic loop in `ai-runner.ts` handles both sync and async tools via `await Promise.resolve()`.
- **DEBUG tool category**: New agent tool category giving agents the full 5-tool set plus all 6 debug tools. The `debugger` agent reassigned from OPS to DEBUG.
- **`/debug` skill**: Interactive debugger skill for IDE use — `/debug <file>`, `/debug <file>:<line>`, `/debug test <test-file>`.
- **18 new tests** covering CDP adapter state, runtime detection, session lifecycle, tool definitions, executor routing, and integration.

### Security

- **Localhost-only WebSocket**: `CDPAdapter.connect()` rejects connections to non-localhost hosts (127.0.0.1, localhost, ::1 only).
- **Test runner whitelist**: `ALLOWED_TEST_RUNNERS` prevents command injection via `testCommand` parameter.
- **Stderr buffer limit**: 1 MB cap prevents memory exhaustion from malicious child process output.
- **Signal handler cleanup**: Process event handlers removed in `stop()` to prevent accumulation across sessions.

### Changed

- `LogCategory` type extended with `'debugger'`.
- Agent registry `VALID_CATEGORIES` updated to include `'DEBUG'`.
- **423 total tests passing** (18 new, 0 regressions).

---

## [2.0.38] - 2026-03-08

### Added — Correctness Contracts

- **MG0 — Pre-generation AC validation gate**: Validates `done_when` / acceptance criteria are objectively verifiable before the coder fires. Returns WARN for legacy stories without `done_when` (backward compatible). Checks for subjective language like "works correctly", "looks good", "handles edge cases properly".
- **T0 — Correctness Contract gate**: Zero-cost static check added as the first Anvil tier (T0, before T1). Fuzzy-matches `done_when` items against test file content using keyword extraction. No AI calls, no build required — runs in milliseconds.
- **MG1.5 — Test documentation gate**: AI review checking `@test-suite` headers, `@story`/`@rationale` metadata, GIVEN/WHEN/THEN structure comments, and WHY comments explaining what contract each test enforces. On FAIL, re-triggers the tester agent (not fixer) to add intent documentation.
- **Story format: `done_when` / `fail_when` blocks**: Story generation prompt now includes correctness contract sections with objectivity guidance. Every `done_when` item must be testable without human judgment.
- **Pipeline integration**: MG0 wired before coder in FORGE phase, MG1.5 wired in POLISH phase (between MG1/MG2), T0 wired in TEMPER phase (before T1). MG1.5 failures trigger tester re-run capped at 1 retry.
- **`/ac` skill**: Acceptance criteria validator — checks `done_when` items for subjective language across all stories.
- **`/doc-tests` skill**: Test documentation checker — validates `@test-suite` headers, GWT+WHY comments across test files.
- **Anvil upgraded to 7-tier** (T0-T6): `_anvil-protocol.md` updated with T0 Correctness Contract tier.
- **Tester agent Phase 3.5**: `ruthless-tester.md` updated with test intent documentation requirements and escalation rule.
- **7 new tests** for MG0, MG1.5, and safety overrides in `micro-gates.test.ts`. Pipeline and gate test counts updated. **405 total tests passing.**

---

## [2.0.37] - 2026-03-05

### Added — Platform Memory Migration

- **One-time migration script** (`scripts/migrate-platform-memory.ts`) normalizes all legacy JSONL entries, extracts knowledge from `.claude/scratchpad.md`, updates stale bootstrap facts, and writes canonical JSONL.
- **16 legacy entries normalized** across `decisions.jsonl`, `decisions-universal.jsonl`, `patterns-universal.jsonl`, `errors-universal.jsonl` — converted from flat key-value schema to canonical schema with `id`, `weight`, `lineage`, `reality_anchor`.
- **27 entries extracted** from scratchpad session history (Feb 15 – Feb 27): 13 facts (session summaries, architecture, version progression), 5 decisions, 4 errors (security fixes), 3 preferences.
- **2 stale bootstrap entries superseded**: `bootstrap-fact-003` ("3 platforms" → "5 platforms") and `bootstrap-fact-004` ("41 agents" → "56 agents, 63 skills") with proper `lineage.supersedes` linkage.
- **Idempotent**: running the script again reports 0 new entries. Deduplication checks content against existing entries before writing.
- **`facts.jsonl`** populated (was empty): 15 entries covering session summaries, version history, architecture facts, and superseding bootstrap facts.
- **`errors.jsonl`** populated (was empty): 4 entries covering critical security fixes (eval injection, mktemp, sed injection, clearTimeout).
- **`preferences.jsonl`** populated (was empty): 3 entries (backend-first workflow, dark mode default, cold-blooded logic philosophy).

---

## [2.0.36] - 2026-03-05

### Added — Automatic Memory Harvesting in Pipeline

- **New `memory-harvest.ts` module** — `harvestRunMemory()` automatically writes knowledge entries to `memory_bank/knowledge/*.jsonl` after every forge run. No AI prompt dependency — works identically on every platform.
- **Harvested entry types**: run summary facts, failed story errors, MG FAIL finding errors, and gate verdict facts. All entries follow the full JSONL schema documented in `memory_bank/knowledge/README.md`.
- **Deduplication**: reads last 50 lines of target file before appending, skips entries with identical content.
- **Pipeline integration**: called during DEBRIEF phase after persisting the run bundle. DEBRIEF detail now includes harvest count.
- **14 new tests** (13 in `memory-harvest.test.ts`, 1 in `pipeline.test.ts`) covering schema compliance, deduplication, zero-story runs, MG findings, gate verdicts, and pipeline integration.

---

## [2.0.35] - 2026-03-05

### Changed — Two-Pass Pipeline (FORGE + POLISH)

- **FORGE phase** now runs only T2 (type check) and T5 (build) smoke tests per story, replacing the previous per-story micro-gate (MG1/MG2) checks. Stories fail only on compilation errors, not quality gate findings.
- **New POLISH phase** inserted between FORGE and TEMPER. Runs MG1 (security) and MG2 (standards) reviews on all completed stories in aggregate. If failures are found, a holistic fixer runs once across the entire codebase, then re-checks.
- POLISH failures do not block the pipeline — TEMPER remains the strict enforcement gate (T1-T6).
- Pipeline phases now: IGNITE → PLAN → FORGE → POLISH → TEMPER → INSPECT → DEBRIEF → FINISH.
- Reduced story failures caused by micro-gate rejections during active development.
- Updated pipeline tests for new two-pass behavior.

---

## [2.0.34] - 2026-03-05

### Changed — Documentation & Version Update

- Updated README with structured logging section, pipeline resume documentation, and cross-platform (Git Bash / WSL) support notes
- Updated test count to 382 (from 380) reflecting new pipeline resume tests
- Updated USER-GUIDE-CLI.md with structured logging configuration reference
- Updated TEST-SUITE-REFERENCE.md with current test counts

---

## [2.0.33] - 2026-03-05

### Fixed — Git Bash / WSL Anvil Script Discovery

**Anvil script now found correctly in Git Bash and WSL environments**
- In Git Bash / WSL, `process.platform` reports `'linux'` but paths use Windows drive letters (`C:/...`). The previous fix (v2.0.31) excluded `.sh` scripts entirely on Windows-like paths, but this was too aggressive — Git Bash's `bash` can handle `C:/` paths natively.
- `findAnvilScript()` now tries all extensions in priority order: `.ps1/.cmd` first on Windows-like environments, then `.sh` as fallback. This ensures the framework's `anvil.sh` is found even when no `.ps1/.cmd` variant exists.
- `getAnvilScript()` in `framework.ts` gets the same drive-letter detection and extension fallback logic.
- `anvilCommand()` now converts backslashes to forward slashes for bash when drive-letter paths are detected (not just on native `win32`).

---

## [2.0.32] - 2026-03-05

### Added — Structured Logging

**JSONL structured logging for pipeline and interactive sessions**
- New `SfLogger` class in `src/utils/logger.ts` with `DEBUG`, `INFO`, `WARN`, `ERROR` levels
- JSONL format: one JSON object per line with `ts`, `level`, `category`, `event`, `data` fields
- Per-run log files in `.skillfoundry/logs/{runId}.log` matching the run bundle naming
- Rolling `session.log` (capped at 1000 lines) for interactive mode
- Auto-cleanup keeps the last 20 run logs, removes oldest on pipeline start
- Configurable via `log_level` in `.skillfoundry/config.toml` (default: `info`)

**Logger wired into all pipeline modules:**
- `pipeline.ts` — phase start/complete, story start/complete/failed, run complete
- `ai-runner.ts` — loop start/end, per-turn token stats (DEBUG), provider stream errors
- `retry.ts` — retry attempts with delay/error, fallback attempts, retries exhausted
- `micro-gates.ts` — gate start/complete, provider errors
- `gates.ts` — T1-T6 gate results and failures
- `budget.ts` — threshold warnings when >80% of monthly budget consumed
- `executor.ts` — tool call start/complete at DEBUG level with duration

### Fixed — Pipeline Resume

**Pipeline marks stories DONE after successful completion**
- Previously, completed stories were never marked in their `.md` files, so re-running `/forge` would re-implement all stories from scratch. Now `status: PENDING` is updated to `status: DONE` in the story file after successful completion.
- Re-running `/forge` skips stories already marked DONE, implementing only remaining pending stories.
- Two new tests added: story-mark-done validation and pipeline resume behavior (382 total).

---

## [2.0.31] - 2026-03-05

### Fixed — Windows T1 Gate + Micro-Gate Provider Error Handling

**T1 gate no longer tries bash scripts on Windows**
- On Windows, `findAnvilScript` was finding `scripts/anvil.sh` and trying to run it with `bash "C:/apps/.../scripts/anvil.sh"`, which fails because bash can't resolve Windows drive-letter paths. The script search now only looks for `.ps1` and `.cmd` on Windows, falling back to the inline grep-based T1 check which works cross-platform.

**Micro-gates detect provider connection errors**
- When the AI provider is unreachable, micro-gates (MG1/MG2) received error content like "Provider error: Connection error" and parsed it as WARN verdict (no VERDICT keyword found). Now provider errors are detected before parsing and marked with `skippedDueToError: true`. These don't trigger the fixer loop and display with a `~` icon instead of `!` so the user can tell the difference between a real warning and a connection failure.

---

## [2.0.30] - 2026-03-05

### Fixed — Pipeline Reliability Overhaul (First Real-Use Fixes)

Four fundamental issues discovered during the first real `/forge` pipeline run where all 20 stories failed:

**Post-story T1 gate is now advisory (does not block story completion)**
- Previously, the post-story T1 scan checked the entire project directory and found pre-existing TODOs in documentation, genesis files, and framework code — causing every single story to fail. T1 is now advisory after each story; only micro-gate FAILs (MG1 security, MG2 standards) trigger the fixer loop. The full T1-T6 TEMPER phase remains the real quality gate.

**T1 gate excludes framework and documentation directories**
- T1 banned-pattern scan now excludes `genesis/`, `docs/`, `memory_bank/`, `.claude/`, `scratchpads/`, `coverage/`, and other non-application directories. Also excludes `CHANGELOG.md` and test files where TODO/FIXME patterns are legitimate.

**Windows path fix in INSPECT phase**
- The security audit phase passed a Windows-style path (`C:\apps\...`) to `/bin/bash`, causing the script to fail. Backslashes are now converted to forward slashes on Windows.

**Resilient micro-gate response parser**
- The parser expected AI output in an exact format (`VERDICT: PASS`, `FINDINGS:` with `- [SEVERITY]`). Real AI output uses markdown formatting (`**VERDICT:** WARN`), numbered lists, bullet variants (`*`, `•`), and sometimes omits the SUMMARY line. The parser now handles all these variations with fallback summary generation.

**Pipeline tests updated** to reflect new T1-advisory behavior (380/380 passing).

---

## [2.0.29] - 2026-03-05

### Fixed — Pipeline Cost Tracking + Story Execution Quality

Two issues fixed in the `/forge` pipeline:

**Header cost display now updates during pipeline execution**
- The status bar showed `$0.0000` throughout `/forge` runs because pipeline costs were tracked internally but never attached to message metadata. The forge result is now added as a message with `metadata.costUsd`, so the header's cost counter updates.

**Story execution prompt now enforces quality standards**
- Previously the AI wrote code with TODOs, missing input validation, hardcoded values, and empty error handlers — then the quality gates correctly flagged all of it. The story execution prompt now explicitly lists the same standards the gates check: banned patterns (TODO/FIXME/STUB), security requirements (input validation, parameterized queries, no hardcoded secrets), error handling, documentation, and code quality rules. The AI knows what it will be checked against before writing code.

---

## [2.0.28] - 2026-03-05

### Fixed — Gate and Micro-Gate Output Now Shows Actionable Details

Quality gates (T1-T6) and micro-gates (MG1/MG2/MG3) previously displayed bare icons with no explanation (e.g., `T1 [x]` or `MG1 [!] security: WARN`). Now they show the actual failure details and findings.

- **Gate results (T1-T6)**: Non-passing gates show up to 3 lines of detail with file paths and matched patterns
- **Micro-gate results (MG1/MG2/MG3)**: Non-passing gates list up to 5 individual findings with severity, description, and file location
- **Dry-run mode**: Also improved — shows up to 5 detail lines per gate instead of a single truncated line
- **`/model` command**: Removed confusing "not in known models" warning — any model string is accepted without caveats
- **OpenAI models**: Added `gpt-5.1-codex-max` to known models list and pricing table

---

## [2.0.27] - 2026-03-05

### Fixed — Forge Pipeline Skips Already-Completed Stories

- **PLAN phase**: Now checks for existing stories before generating new ones. Reports per-PRD: `Found 5 existing stories for auth-system (3 done, 2 pending)` — only calls the AI when stories don't exist yet.
- **FORGE phase**: Skips stories already marked `status: DONE/COMPLETED/IMPLEMENTED`. Previously re-implemented every story on each `/forge` run, wasting API calls and time.
- Progress output now shows: `Implementing 2 stories (3 already done, skipped)` so users know exactly what's happening.

### Added

- **`/model` command**: List known models for the active provider and switch models instantly (`/model gpt-4.1-mini`). More discoverable than `/config model`.

### Fixed — Graceful Error Handling for Model Access Errors

- CLI no longer crashes when the configured AI model is inaccessible. Errors are classified (model access, auth, billing, SSL, network) with actionable fix instructions.
- `NON_RETRYABLE` regex expanded to fail fast on model access and billing errors instead of retrying 3 times.

---

## [2.0.26] - 2026-03-05

### Fixed — Graceful Error Handling for Model Access Errors

The sf CLI crashed and exited when the configured AI model was not accessible (e.g., "you don't have access to gpt-4o"). Now errors are classified and displayed with actionable fix instructions.

- **Model access errors**: Friendly message suggesting `/model` or `/config model <name>` instead of a stack trace crash
- **Auth errors**: Suggests `/setup` for API key configuration
- **Billing/quota errors**: Suggests checking provider dashboard or switching models
- **SSL/certificate errors**: Suggests `NODE_TLS_REJECT_UNAUTHORIZED=0` for corporate proxies
- **Network errors**: Suggests checking connectivity and local provider status
- **`ai-runner.ts`**: Added try/catch around `streamWithRetry()` — pipeline mode no longer crashes on provider errors
- **`useStream.ts`**: Unified error classification using shared `classifyProviderError()` helper
- **`retry.ts`**: Expanded `NON_RETRYABLE` regex to include model access, billing, and 404 errors (fail fast instead of retrying 3 times)

### Added

- **`/model` command**: List known models for the active provider and switch models instantly. More discoverable than `/config model <name>`.

---

## [2.0.25] - 2026-03-05

### Added — Demo GIF and CONTRIBUTING.md

- **Animated demo GIF**: 20-frame terminal animation of the `/forge` pipeline embedded in the README hero section — shows typing, all 6 phases running (with Anvil gate recovery), and final "FORGED" status. 123KB.
- **CONTRIBUTING.md**: Setup instructions, development workflow, code standards, commit conventions, and guides for adding new agents and CLI commands.
- **README hero polish**: Bold tagline, "Why SkillFoundry?" bullets, compact quick start, pipeline overview diagram. Windows instructions collapsed in `<details>`.

### Fixed

- **Install performance test**: Threshold increased from 5s to 30s to account for `npm install` + TypeScript build on CI runners.

---

## [2.0.24] - 2026-03-04

### Fixed — CLI Wrapper Auto-Added to PATH on Install & Update

The `sf` command was not recognized on Windows (and sometimes Linux/macOS) after installation because `~/.local/bin` was not on the user's PATH. The installer only printed a yellow warning with manual instructions — users missed it and thought the install had failed.

- **install.ps1**: Now auto-adds `%USERPROFILE%\.local\bin` to the user's persistent PATH via `[Environment]::SetEnvironmentVariable()` and updates the current session so `sf` works immediately without restarting the terminal
- **install.sh**: Now auto-appends `export PATH="~/.local/bin:$PATH"` to the user's shell profile (`.bashrc`, `.zshrc`, or `config.fish`), with duplicate detection to stay idempotent
- **update.ps1 / update.sh**: Also check and fix PATH on update, so users who installed before this fix get the PATH entry on their next update
- **Dry-run output**: Both installers now show `PATH — Auto-add ~/.local/bin if missing` in the dry-run preview

### Changed — README Hero Section Rewritten

The README hero section was redesigned for GitHub visitors who spend 5 seconds on a repo page:

- Added bold tagline: "Turn requirements into tested, production-ready code — with quality gates your AI can't skip."
- Added "Why SkillFoundry?" section with 5 sharp differentiator bullets
- Moved Quick Start to the hero (3 steps, Windows collapsed in `<details>`)
- Added compact "How It Works" pipeline overview before the detailed sections
- Renamed the duplicate detailed pipeline section to "Pipeline Details"
- Removed redundant duplicate Quick Start section

---

## [2.0.23] - 2026-03-03

### Fixed — CLI Exits Silently on Windows (Non-Claude Platforms)

When SkillFoundry was installed with a non-Claude platform (e.g., Copilot only), running `sf` on Windows would silently exit with no output. The CLI appeared to do nothing.

- **Root cause**: `render()` from Ink was not awaited — the async action handler completed immediately, allowing Node.js to exit before the React/Ink terminal UI had time to render. On Linux the event loop often stayed alive long enough by coincidence; on Windows it exited reliably.
- **Secondary issue**: `program.parse()` (synchronous) was used instead of `program.parseAsync()`, causing any startup errors in the async action handler to be silently swallowed as unhandled promise rejections.
- **Fix**: `render()` now returns `{ waitUntilExit }` which is properly awaited, keeping the process alive for the lifetime of the Ink UI. `program.parseAsync()` with a `.catch()` handler ensures startup errors are logged.
- **Entry point hardened**: `bin/sf.js` dynamic import now has a `.catch()` to surface fatal module load errors.

---

## [2.0.22] - 2026-03-02

### Added — Auto-merge .gitignore on Install & Update

Both `install.sh` / `install.ps1` and `update.sh` / `update.ps1` now automatically create or update the project's `.gitignore` with a managed block of SkillFoundry entries. This prevents framework operational state (memory bank, scratchpads, metrics, Claude runtime artifacts, etc.) from being committed to the user's repository.

- **Managed block**: Entries wrapped in `# >>> SkillFoundry Framework` / `# <<< SkillFoundry Framework` markers for safe, idempotent updates
- **Three cases handled**: creates `.gitignore` if missing, appends block if no marker exists, replaces block if already present
- **Read-only safety**: skips with a warning if `.gitignore` is read-only
- **Ignored paths**: `memory_bank/`, `scratchpads/`, `metrics/`, `knowledge/staging/`, `.skillfoundry/`, `.claude/*.jsonl`, `.claude/*.json`, `.claude/attribution/`, `.claude/heartbeat*`, `.claude/backups/`, `.claude/scratchpad.md`, `.arena/`, `compliance/evidence/*`, `observability/*.log`, `.*/.framework-version`, `.*/.framework-updated`, `.*/.framework-platform`, `.skillfoundry-diagnostics.log`
- **Explicitly tracked** (un-ignored): `.claude/settings.json`, `.claude/settings.local.json`, `.claude/commands/`, `.copilot/custom-agents/`, `.cursor/rules/`, `.agents/skills/`, `.gemini/skills/`
- **Dry-run support**: `.gitignore` merge shown in `install.sh --dry-run` and `install.ps1 -DryRun` previews
- **Summary output**: `.gitignore` status included in post-install summary

---

## [2.0.21] - 2026-03-01

### Changed — UX/UI Specialist Agent Rewrite

Complete rewrite of the UX/UI Specialist agent (`agents/ux-ui-specialist.md`) merging the existing structure with production-quality reference material. The agent grows from ~513 lines to ~800 lines with concrete, actionable content replacing generic placeholders.

- **Design tokens**: Generic `--color-primary: [...]` placeholders replaced with full 178-line CSS custom properties with real hex values, plus Tailwind config, Angular Material theme, and React theme object templates
- **Audit system**: Checkbox-based pass/fail audit replaced with 12-point scored system (0-3 per item, 36-point max) organized into 4 categories (Layout & Spacing, Color & Visual Hierarchy, Typography, Components & Patterns, Responsive & Polish)
- **Priority matrix**: New P0-P3 categorization for audit findings (P0 = blocks professional use, P3 = delight layer)
- **Component specs**: Concrete specifications table with pixel heights, padding, font sizes for 9 components (Button sm/md/lg, Input, Card, Table header/row, Badge, Modal)
- **Component patterns**: Full empty state pattern with 9 context examples, status badge color mapping with 6 statuses, table standards with 9 rules and CSS, page header standard with structure diagram, card standards with KPI rules
- **Remediation workflow**: New 4-phase systematic workflow (Discovery → Foundation → Remediation → QA)
- **Execution order**: New 9-step ordered sequence (tokens → globals → layout → components → pages → empty states → interactive → responsive → polish) to avoid rework
- **QA checklist**: 26-item visual regression checklist + 10 cross-page consistency checks + multi-width testing (1920, 1440, 1280, 1024, 768)
- **Enterprise anti-patterns**: 10 new enterprise-specific anti-patterns (ghost town pages, Frankenstein styling, label salad, table wilderness, button roulette, padding chaos, status color anarchy, orphan pages, missing states, visual hierarchy collapse)
- **Reflection protocol**: Blocking threshold lowered from 7 to 5 for hard blocks
- **Preserved**: Operating modes, migration protocol, rewrite protocol, existing 18 anti-patterns, button/form/loading patterns, dark mode requirements, responsive breakpoints, security considerations, integration section, closing format

---

## [2.0.20] - 2026-03-01

### Added — Skill Scope Boundaries in CLAUDE.md

Added explicit scope isolation rules to prevent instruction creep — where heavyweight skill rules (e.g., `/security` STRIDE modeling, `/tester` 14 test categories, `/forge` 6-phase pipeline) get misapplied to trivial tasks like README edits, config changes, or one-line fixes.

- **Rule 1 — Activation/Deactivation**: Skill rules are active only between invocation and output delivery
- **Rule 2 — Global vs Skill-Local**: Classifies which rules always apply (no hardcoded secrets) vs skill-scoped (OWASP checklist only during `/security`)
- **Rule 3 — Complexity-Based Scope**: Trivial (1 file) = direct edit; Large (10+ files) = full pipeline
- **Rule 4 — Exempt Contexts**: Documentation, housekeeping, questions, config files exempt from heavyweight rules
- **Rule 5 — No Retroactive Expansion**: Running `/security audit` doesn't re-evaluate prior unrelated work

Thanks to joozio from Reddit for the suggestion.

---

## [2.0.19] - 2026-02-28

### Added — Social Media Publishing Script

New shell script `scripts/social-publish.sh` for publishing posts directly to X (Twitter) and LinkedIn via their REST APIs.

- **Single posts**: `social-publish.sh publish x "content"` / `social-publish.sh publish linkedin "content"`
- **Threads**: `social-publish.sh thread x thread-file.txt` (sections split by `---`)
- **Dry-run mode**: Preview without posting (`--dry-run`)
- **History tracking**: All posts logged to `.claude/social-media-posts.jsonl`
- **Status check**: Verify API connectivity and token validity
- **Setup wizard**: Interactive token configuration
- **Sourceable**: Other scripts can `source` it and call `social_publish()` directly
- Config via env vars (`CLAUDE_AS_X_BEARER_TOKEN`, `CLAUDE_AS_LINKEDIN_ACCESS_TOKEN`) or `.claude/social-media.json`
- Updated `/social-media` agent with Publishing section referencing the script

---

## [2.0.18] - 2026-02-28

### Added — 3 New Specialist Agents (56 agents, 63 skills)

Three new agents added to the framework, synced across all 5 platforms (Claude Code, Copilot, Cursor, Codex, Gemini):

- **SEO Specialist** (`/seo`) — Google Search Console analysis, technical SEO audits, Core Web Vitals, structured data/Schema.org validation, sitemap/robots.txt generation, crawl budget optimization, URL migration planning
- **Social Media Specialist** (`/social-media`) — Platform-specific content creation for X (Twitter), Medium, Reddit, XDA-Developers, and LinkedIn. Includes formatting rules, character limits, tone guidelines, content calendars, and engagement strategies per platform
- **Production Cleaner** (`/clean`) — Strips AI/LLM framework artifacts before production deployment. Generates production `.gitignore`/`.dockerignore`, removes AI modification markers from code, audits for leaked framework files, CI/CD integration for automated clean checks

Agent count: 53 → 56 | Skill count: 60 → 63

---

## [2.0.17] - 2026-02-27

### Fixed — Git Executable Permissions

31 scripts (`.sh`, `.ps1`, `bin/sf.js`, `sf` wrapper) were stored as `100644` (non-executable) in the git index. Every fresh `git clone` required a manual `chmod -R 755 *` before `install.sh` or `update.sh` would run. All 31 files now stored as `100755` — fresh clones have correct permissions out of the box.

---

## [2.0.16] - 2026-02-27

### Fixed — Update Script Self-Copy Bug

When running `update.ps1 .` or `update.sh .` from inside the framework directory, `$ScriptDir` and `$ProjectDir` resolve to the same path. Unguarded `Copy-Item`/`cp` calls for copilot helper files (helper.sh, WORKFLOW-GUIDE.md, SECURITY-INTEGRATION.md) crashed because the OS prevents overwriting a file with itself.

- **update.ps1**: Added `$isSameDir` guard; wrapped 2 unguarded `Copy-Item` calls
- **update.sh**: Added `is_same_dir` guard; wrapped 5 unguarded `cp` calls across 2 code paths

Hash-checked copy loops already handled this gracefully (identical hashes = skip), so only the direct copies needed the guard.

---

## [2.0.15] - 2026-02-27

### Added — Pipeline Finisher (Automated Post-Pipeline Housekeeping)

Deterministic 7th pipeline phase that eliminates the "forgot to bump version / update test counts / update docs" gap. Zero AI cost — fully mechanical checks that auto-fix what's safe and report what needs human judgment.

#### New: Finisher Module (`src/core/finisher.ts`)
- **Version sync**: Bumps patch version (when stories completed > 0) and syncs across `.version`, `package.json`, `README.md`, `USER-GUIDE-CLI.md`, `TEST-SUITE-REFERENCE.md`
- **Test count sync**: Runs vitest, compares actual count vs docs, auto-fixes stale references
- **Architecture listing**: Scans `src/core/*.ts` on disk, compares with tree diagram in docs, reports drift (no auto-fix — descriptions need human judgment)
- **Changelog**: Verifies `[current-version]` entry exists in CHANGELOG.md, inserts placeholder if missing
- **Git clean**: Detects uncommitted changes (report-only, never auto-commits)
- Two modes: `check` (read-only for dry-run) and `fix` (auto-correct what's mechanical)
- Execution order: version → test-count → architecture → changelog → git-clean

#### Updated: Pipeline Integration
- FINISH phase runs after DEBRIEF (7th of 7 phases)
- Non-blocking: drift or errors don't fail the pipeline
- `onFinisherCheck` callback fires per check for real-time progress
- Results attached to `PipelineResult.finisherSummary`
- Run bundle JSON updated with finisher data

#### Updated: Forge Command (`/forge`)
- Full pipeline shows finisher summary: `Finisher: X ok, Y fixed, Z drift`
- Dry-run mode (`--dry-run`) shows finisher checks in read-only mode
- Real-time progress shows each check with status icon

#### Tests
- 50 new unit tests (`finisher.test.ts`) covering all 5 checkers + integration
- 2 new pipeline integration tests (FINISH phase + callbacks)
- Total: 380 tests across 27 files (was 328/26)

---

## [2.0.14] - 2026-02-27

### Added — Post-Handoff Micro-Gates

Lightweight AI-powered quality reviews at pipeline handoff points. Agents now enforce quality on each other — security blocks insecure code, standards blocks non-compliant code — at ~15% cost increase vs ~400% for full cross-agent enforcement.

#### New: Micro-Gates Module (`src/core/micro-gates.ts`)
- **MG1 (Security)**: Post-coder per-story security review — checks OWASP Top 10, injection, hardcoded secrets, auth issues
- **MG2 (Standards)**: Post-coder per-story standards review — checks missing docs, magic numbers, naming, conventions
- **MG3 (Review)**: Pre-TEMPER cross-story consistency review — checks cross-story inconsistencies, arch issues (advisory only)
- Structured response parser: `VERDICT: PASS|FAIL|WARN` / `FINDINGS:` / `SUMMARY:` format
- Safety override: PASS verdict with CRITICAL/HIGH findings automatically escalated to FAIL
- Conservative defaults: unparseable AI responses default to WARN
- Read-only tool set (read, glob, grep) — micro-gates inspect but never modify code
- Each gate limited to 3 turns max for cost control

#### Updated: Pipeline Integration (`src/core/pipeline.ts`)
- MG1 + MG2 run after each story implementation, before T1 gate
- Micro-gate FAIL triggers fixer even when T1 passes
- Fixer prompt merges T1 violations + micro-gate findings into single remediation prompt
- MG3 runs once between FORGE and TEMPER phases (advisory only, does not block)
- Micro-gate costs tracked and included in pipeline totals
- Run bundle JSON includes `microGates` section with per-gate results

#### Updated: Forge Command (`src/commands/forge.ts`)
- Real-time `onMicroGateResult` callback shows gate progress during execution
- Final output includes micro-gate summary: `Micro-gates: 3P 0F 0W ($0.0150)`
- MG3 advisory warning displayed when verdict is not PASS

#### Updated: Types (`src/types.ts`)
- `MicroGateVerdict`, `MicroGateFinding`, `MicroGateResult` types
- `StoryExecution.microGateResults` for per-story results
- `PipelineCallbacks.onMicroGateResult` callback
- `PipelineResult.microGateSummary` with totals and advisory

#### Tests
- `micro-gates.test.ts`: 16 test cases (8 parser, 5 runner, 3 formatter)
- `pipeline.test.ts`: +4 integration tests (micro-gate wiring, fixer trigger, callbacks, advisory)
- All tests passing, 0 regressions

---

## [2.0.13] - 2026-02-27

### Updated — Documentation, CLI Help & Consistency

#### CLI Help & Setup
- Setup wizard now lists LM Studio as a separate option (option 6) alongside Ollama
- `/setup list` correctly shows lmstudio as "always available (local)"
- `/provider set lmstudio` no longer requires an API key
- `/config` now supports editing `route_local_first`, `local_provider`, `local_model`, `context_window`
- `/status` shows active local-first routing info when enabled

#### Documentation
- README.md: Updated version badge to 2.0.13, added providers badge, added Local-First Development section
- USER-GUIDE-CLI.md: Added Section 12 (Local-First Development) with routing, compaction, health checks, and cost savings docs
- USER-GUIDE-CLI.md: Updated architecture section with compaction.ts, health-check.ts, task-classifier.ts
- USER-GUIDE-CLI.md: Updated test suite count from 154 to 308 across 25 test files
- USER-GUIDE-CLI.md: Updated config reference with routing settings

---

## [2.0.12] - 2026-02-27

### Added — Local-First Development

Three new modules that enable effective use of local AI models (Ollama, LM Studio) for cost optimization and offline development.

#### New: Context Compaction Engine (`src/core/compaction.ts`)
- Token estimation using conservative 3.5 chars-per-token ratio
- Context window defaults for 20+ models (cloud and local)
- System prompt compression: strips code blocks, examples, tables when over budget
- Message sliding window: keeps first user message + last N turns that fit
- Summary injection: prepends "[N earlier messages omitted...]" when pruning
- Automatically applied for local providers (Ollama, LM Studio) in the agentic loop

#### New: Provider Health Checks (`src/core/health-check.ts`)
- `pingProvider()` — HTTP ping to local endpoint with 500ms timeout
- Cached results with 60-second TTL (avoids per-turn latency)
- `resolveProvider()` — graceful fallback to cloud with user-visible warning
- `listLocalModels()` — queries /v1/models endpoint for available models
- `isLocalProvider()` / `getLocalBaseUrl()` helpers

#### New: Task Complexity Classifier (`src/core/task-classifier.ts`)
- Keyword-based simple/complex task classification (no LLM call needed)
- Simple keywords: docstring, format, explain, readme, changelog, etc.
- Complex keywords: architect, security, refactor, implement, test, etc.
- Default to complex (safer — cloud handles ambiguous tasks)
- `selectProvider()` — combines classification + health check for routing decisions

#### Updated: Config & Types
- New `SfConfig` fields: `route_local_first`, `local_provider`, `local_model`, `context_window`
- Default: routing disabled (opt-in via `route_local_first = true` in config.toml)

#### Updated: Cost Command
- Shows local vs cloud token breakdown when both providers have been used
- Estimates savings from local routing: "Saved: ~$X.XX by routing locally"

#### Updated: AI Runner
- Applies context compaction before each turn when using local providers
- Uses model-specific context windows for sliding-window pruning

#### Tests
- `compaction.test.ts`: 20 test cases (token estimation, sliding window, summary injection, compression)
- `health-check.test.ts`: 11 test cases (ping, caching, fallback, local detection)
- `task-classifier.test.ts`: 17 test cases (classification, routing, provider selection)
- All 308 tests passing, 0 regressions

---

## [2.0.11] - 2026-02-27

### Added — LM Studio Provider & Local-First PRD

#### New: LM Studio Provider
- Added LM Studio as the 6th supported provider (OpenAI-compatible at `localhost:1234/v1`)
- Factory function `createLMStudioProvider()` in `providers/openai.ts`
- Registered in `AVAILABLE_PROVIDERS` with default model `qwen2.5-coder-7b`
- Auto-detected as always available (same as Ollama — no API key needed)
- Credential mapping via `LMSTUDIO_BASE_URL` environment variable
- Deprioritized in auto-selection (local providers don't override cloud)

#### New: Local-First Development PRD
- Created `genesis/2026-02-27-local-first-development.md` PRD covering:
  - Context compaction engine for small-context local models (4K-32K)
  - Local-first cost routing (simple tasks → local, complex → cloud)
  - Provider health checks with graceful fallback
  - Task complexity classification (keyword-based, no LLM call)
- Based on analysis of XDA article "How I built a Claude Code workflow with LM Studio"

#### Updated
- Provider tests updated: 260 tests passing (2 new: lmstudio detection + creation)
- README.md: LM Studio added to provider table
- USER-GUIDE-CLI.md: LM Studio added to setup wizard, capabilities table, env var docs

---

## [2.0.10] - 2026-02-26

### Added — The Forge Pipeline Engine

The `/forge` command is now a real executable pipeline. Previously it was a read-only scanner that reported PRD/story status and gate results. Now it drives the full development lifecycle: discover PRDs, generate stories via AI, implement each story with tools, run quality gates, and produce working code.

#### New: Standalone Agentic Loop (`src/core/ai-runner.ts`)
- Extracted the multi-turn tool-use loop from `useStream.ts` into a standalone module
- Zero React dependencies — can be called from both interactive mode and batch pipelines
- Supports callbacks for streaming, tool execution, permissions, and turn progress
- Budget enforcement per-turn, abort signal support, retry with fallback provider

#### New: Pipeline Execution Engine (`src/core/pipeline.ts`)
- 6-phase pipeline: IGNITE → PLAN → FORGE → TEMPER → INSPECT → DEBRIEF
- **IGNITE**: Discovers and validates PRDs from `genesis/`
- **PLAN**: Generates stories from PRDs via AI (or reuses existing stories)
- **FORGE**: Implements each story sequentially via the agentic loop (25 turns max per story)
- **TEMPER**: Runs T1-T6 quality gates
- **INSPECT**: Isolates T4 security results
- **DEBRIEF**: Persists run metadata to `.skillfoundry/runs/{runId}.json`
- Auto-fixer: if T1 gate fails after story implementation, routes to fixer agent (max 2 retries)
- Real-time progress callbacks for UI integration

#### Refactored: useStream.ts
- The inline while-loop replaced with a call to `runAgentLoop()`
- All interactive behavior preserved — same tools, budget, permissions, streaming
- React state updates via callbacks (onStreamChunk, onToolStart, onToolComplete, etc.)

#### Updated: `/forge` Command
- `/forge` — Executes the full pipeline (AI-powered)
- `/forge --dry-run` — Read-only scan (backward compatible with pre-2.0.10 behavior)
- `/forge <prd-file>` — Filter to a specific PRD
- Real-time progress messages during pipeline execution

#### New Types
- `RunnerCallbacks`, `RunnerOptions`, `RunnerResult` — Agentic loop interfaces
- `PipelineCallbacks`, `PipelineOptions`, `PipelineResult` — Pipeline interfaces
- `StoryExecution`, `PipelinePhase`, `PipelinePhaseStatus` — Execution tracking

#### Tests
- `ai-runner.test.ts`: 8 test cases (single-turn, multi-turn, budget, permissions, abort, callbacks)
- `pipeline.test.ts`: 12 test cases (PRD scan, story generation, execution, fixer retry, persistence, callbacks)
- Total: 258 tests passing (20 new, 0 regressions)

---

## [2.0.9] - 2026-02-26

### Added — Reflection Protocols for 5 Key Orchestrators

Completed the reflection coverage gap from v2.0.8. The 5 most-used orchestrator agents now have full reflection protocols with pre/post execution self-assessment and scoring thresholds.

#### Reflection Protocols Added
- **auto.md**: Classification accuracy, pipeline completeness, escalation quality, token efficiency. Fixed 4 incorrect `docs/prd/` references to `genesis/`.
- **context.md**: Estimation accuracy, compaction timing, context preservation, budget health.
- **fixer.md**: Routing accuracy, fix quality, escalation rate, regression prevention.
- **gate-keeper.md**: Decision accuracy, violation detection, standards consistency, false positive rate.
- **go.md**: Orchestration completeness, gate compliance, context management, delivery quality.

#### Knowledge Promotion Pipeline
- **New**: `scripts/promote-knowledge.sh` — Full promotion pipeline for knowledge bank
  - Scans `knowledge/staging/`, validates YAML frontmatter and body sections
  - Deduplicates against `knowledge/promoted/`
  - Scores lessons (0-5) with minimum threshold of 3 to promote
  - Commands: `promote`, `scan`, `force`, `reject <id>`, `stats`
  - Pure bash, no external dependencies

#### Visual Overhaul Verification
- All 11 CLI components confirmed using theme.ts (hex colors, Unicode symbols, custom borders)
- No hardcoded colors remaining — visual overhaul from v2.0.8 plan is 100% complete

### Synced
- 5 command files synced to 4 platforms (20 copies total)

---

## [2.0.8] - 2026-02-26

### Changed — Self-Introspection: Full Agent Quality Overhaul

Comprehensive self-introspection cycle across all 60 agents. Each agent audited itself for quality gaps, then specialist agents cross-reviewed and corrected each other. The largest single improvement in framework history.

#### Phase 1: IGNITE — Full Audit
- All 60 agents scored against 7 quality dimensions (Structure, Examples, Output, Reflection, Integration, Specificity, Completeness)
- 8 Gold (60+), 23 Silver (50-59), 14 Bronze (35-49), 15 Failing (<35)
- Weakest dimensions framework-wide: Reflection (75% scored 0), Integration (38% operated as islands)

#### Phase 2: FORGE — Self-Improvement (45 agents modified, +8,830 lines)

**Full Rewrites (15 agents, score < 35):**
- `gosm` (18→359), `goma` (17→383), `blitz` (21→463), `cost` (22→365), `undo` (20→431)
- `profile` (26→382), `status` (28→393), `health` (30→362), `ship` (27→485), `gohm` (30→383)
- `evaluator` (30→371), `workflow` (32→371), `nuke` (33→361), `debugger` (34→456), `swarm` (34→522)

**Major Enhancements (14 agents, score 35-49):**
- `coder`, `forge`, `anvil`, `metrics`, `context`, `replay`, `version`
- `performance`, `api-design`, `accessibility`, `ops`, `tech-lead`, `auto`, `dependency`

**Reflection/Integration Added (16 agents, score 50-59):**
- `i18n`, `sre`, `release`, `math-check`, `educate`, `layer-check`, `security`
- `data-architect`, `senior-engineer`, `prd`, `orchestrate`, `memory`, `stories`, `ux-ui`, `migration`

#### Phase 3: TEMPER — Cross-Agent Peer Review

**Security Agent reviewed 5 agents (12 fixes):**
- `devops`: SAST/DAST checklist, credential rotation, pipeline secrets handling
- `api-design`: Default-deny auth policy, CORS configuration guidance, request body limits
- `ops`: Admin access hardening, audit logging, file upload security
- `sre`: Security incident response, security monitoring signals, security SLIs

**Tester Agent reviewed 5 agents (8 fixes):**
- `coder`: Phase 4 rewrite mandating test execution, deliverables upgrade
- `refactor`: Coverage comparison before/after refactoring
- `migration`: Automated test file mandate, testing checklist expansion
- `fixer`: Regression test requirement for all fix types
- `debugger`: Tester documentation standards for regression tests

**Architect Agent reviewed 5 agents (8 fixes):**
- `data-architect`: Architect approval gate, scalability patterns, ADR checklist
- `api-design`: ADR requirement, backwards compatibility enforcement protocol
- `tech-lead`: Architect escalation rule for boundary decisions
- `coder`: Architect approval check in Phase 1 validation
- `delegate`: Selection Rule 6 for implicit architectural decisions

**Evaluator reviewed 15 agents (22 fixes):**
- 2 Output Format expansions (blitz, swarm)
- 5 Integration table restructures (profile, status, health, ship, gohm)
- 15 Required Challenge additions (all 15 rewritten agents)

#### Phase 4: INSPECT — Quality Gate
- Zero banned pattern violations
- All 45 modified agents verified for structural integrity
- Reflection, Integration, and Output sections present in all improved agents

### Changed
- `.version` bumped to 2.0.8 (from 2.0.7)
- `sf_cli/package.json` version bumped to 2.0.8
- All agents synced across 5 platforms (Claude, Codex, Copilot, Cursor, Gemini)

---

## [2.0.7] - 2026-02-26

### Changed — Documentation Agent Rewrite & Release Version Protocol

Major rewrite of the docs agent to prevent version drift and documentation inconsistencies across the framework. The release agent now cross-references the docs agent's version bump protocol.

#### Docs Agent (`/docs`) — Full Rewrite
- **PHASE 1: VERSION & CONSISTENCY AUDIT** (mandatory first step) — version reconciliation checklist, timestamp verification, terminology consistency, rule: "NEVER hardcode a version in prose"
- **PHASE 2: CONTEXT GATHERING** — required inputs table, rejection criteria for incomplete requests
- **PHASE 3: DOCUMENTATION WRITING** — document types table, required structure template (Version/Last Updated/Status header), code examples standard, API documentation standard
- **PHASE 4: CROSS-DOCUMENT CONSISTENCY VERIFICATION** — consistency matrix, cross-reference integrity, staleness detection
- **PHASE 5: DOCUMENTATION HEALTH SCAN** — `/docs health` and `/docs audit` commands, 6-point scan checklist, health report format
- **PHASE 6: VERSION BUMP DOCUMENTATION PROTOCOL** — checklist of ~15 files that must update on every version bump, automated version check command

#### Release Agent (`/release`) — Version Checklist Enhancement
- Pre-release versioning checklist now references `.version` as single source of truth
- Added mandatory `/docs audit` step (docs agent Phase 6) to release preparation
- Expanded checklist to cover all ~15 files that need version updates (README, AGENTS, QUICK-REFERENCE, DOCUMENTATION-INDEX, HOW-TO, sub-package.json files)
- Added "Last Updated" timestamp refresh requirement

#### Platform Sync
- Docs agent synced to 6 targets: command, persona, Codex, Copilot, Cursor, Gemini
- Release agent synced to 6 targets: command, persona, Codex, Copilot, Cursor, Gemini

### Changed
- `.version` bumped to 2.0.7 (from 2.0.6)
- `sf_cli/package.json` version bumped to 2.0.7

---

## [2.0.6] - 2026-02-26

### Added — Chunk Dispatch Protocol

New protocol for splitting large work items across multiple instances of the same agent type. Addresses LLM quality degradation on long files by chunking work at natural boundaries, dispatching shards in parallel, and merging results with a consistency pass.

#### Protocol (`agents/_chunk-dispatch-protocol.md`)
- **When to chunk**: Input >300 lines, output >300 lines, repetitive structure, quality risk
- **Where to split**: Natural boundaries (section headers, class/function boundaries, file boundaries)
- **Context brief**: Shared context (types, imports, style guide) each shard receives for consistency
- **Chunk limits**: Per-agent max lines (docs: 200, coder: 150, refactor: 100, review: 250)
- **Merge strategies**: Concatenate, concatenate with TOC, interleave, file-per-chunk
- **Consistency pass**: 5-check verification (naming, style, cross-references, completeness, tone)
- **Agent-specific strategies**: Detailed chunking guidance for docs, coder, tester, refactor, review, migration, i18n

#### Agent Updates (7 agents, 35 files across 5 platforms)
- `docs`: Chunk Dispatch Support section added (split by `## ` headers, 200 lines/chunk)
- `coder`: Chunk Dispatch Support section added (split by class/file, 150 lines/chunk)
- `tester`: Chunk Dispatch Support section added (split by module, 200 lines/chunk)
- `refactor`: Chunk Dispatch Support section added (split by file/module, 100 lines/chunk)
- `review`: Chunk Dispatch Support section added (split by PR file, 250 lines/chunk)
- `migration`: Chunk Dispatch Support section added (split by table/entity, 150 lines/chunk)
- `i18n`: Chunk Dispatch Support section added (split by locale/section, 200 lines/chunk)

### Changed
- `.version` bumped to 2.0.6 (from 2.0.5)
- `sf_cli/package.json` version bumped to 2.0.6

---

## [2.0.5] - 2026-02-24

### Changed — Agent Quality Enhancement Sweep

Comprehensive quality upgrade across 10 specialist agents. Every enhanced agent now has numbered phases, concrete code examples (good vs bad), structured output formats, reflection protocols, integration maps, and peer improvement signals.

#### Agents Enhanced (Major Rewrite)

| Agent | Before | After | Key Additions |
|-------|--------|-------|---------------|
| **devops** | 190 lines | 510 | 8 phases: git workflows, GitHub ops, Azure DevOps, CI/CD, IaC, backup/DR, cleanup, monitoring |
| **tester** | 85 lines | 236 | New Phase 3: mandatory test documentation (WHAT/WHY/WHERE/HOW/HOW COME), Arrange/Act/Assert, behavior-driven naming |
| **analytics** | 83 lines | 569 | 4 phases: data collection, analysis with trend detection, ASCII visualizations, pattern-based recommendations |
| **explain** | 65 lines | 553 | 4 phases: context gathering from 9 sources, trace reconstruction, 3 explanation levels (quick/verbose/story), impact assessment |
| **architect** | 97 lines | 524 | 5 phases: requirements interrogation, design patterns catalog, ADR format, persona chain with handoff format, validation checklist |
| **bpsbs** | 73 lines | 543 | 4 phases: scope assessment, rule-by-rule audit with BAD/GOOD code examples, severity classification, remediation guidance |
| **delegate** | 140 lines | 525 | 5 phases: complexity classification, agent selection matrix, concrete workflow examples, failure recovery, progress reporting |
| **security-scanner** | 127 lines | 566 | 5 phases: grep patterns per vulnerability, data flow tracing, severity with SLAs, remediation fix patterns per language, verification re-scan |
| **standards** | 190 lines | 727 | 4 phases: scope identification with applicability matrix, pillar-by-pillar with violation/compliant examples, language-specific standards (Rust/TS/Python/C#), weighted scoring |
| **learn** | 223 lines | 584 | 4 phases: needs assessment, resource curation, guided practice with exercises, knowledge verification (Feynman technique) |

#### Cross-Platform Sync

All 10 agents updated across all 5 platforms:
- Claude Code (`.claude/commands/`)
- OpenAI Codex (`.agents/skills/`)
- GitHub Copilot (`.copilot/custom-agents/`)
- Cursor (`.cursor/rules/`)
- Google Gemini (`.gemini/skills/`)

**Total: 50 files updated, ~20K lines added**

#### Quality Standards Now Enforced

Every specialist agent now includes:
- **Numbered PHASES** with clear workflow steps
- **Concrete examples** (code blocks, command examples, BAD vs GOOD patterns)
- **Structured OUTPUT FORMAT** with copy-paste templates
- **Reflection Protocol** (pre/post self-assessment, self-score)
- **Integration with Other Agents** (handoff matrix, data flow)
- **Peer Improvement Signals** (upstream/downstream reviewers)

### Fixed

- PowerShell Windows compatibility: replaced here-strings with string concatenation for LF line ending compatibility
- PowerShell Windows compatibility: replaced all Unicode characters with ASCII equivalents across 6 `.ps1` files (fixes parse errors on Windows PowerShell 5.1 where UTF-8 multi-byte chars corrupt under Windows-1252 encoding)
- Added `.gitattributes` to force CRLF for `.ps1`/`.cmd` files

### Added

- README: "Two Ways to Use SkillFoundry" section (IDE-native vs CLI usage)
- README: "Persistent Memory (Lessons Learned)" section with memory_bank structure
- README: "Knowledge Sync (Cross-Project Learning)" section
- README: "Autonomous Mode" section with intent classification table
- README: "Agent Evolution" section

---

## [2.0.4] - 2026-02-23

### Changed — Visual Overhaul ("Modern Hacker" Style)

Full visual overhaul across all 11 CLI components. Rich Unicode borders, gradient accents, structured visual hierarchy.

#### Theme System (`src/utils/theme.ts`)
- **Color palette**: 20+ hex colors organized by role (accent, secondary, success, warning, error, text, border, role)
- **Unicode symbols**: 30+ symbols for status, navigation, tools, pipeline, dividers — no emoji
- **Custom borders**: 4 BoxStyle presets (header `┏━┓`, double `╔═╗`, input `╭─╮`, card `┌─┐`)
- **Chalk wrappers**: `theme.accent()`, `theme.success()`, etc. for consistent chalk formatting
- **Helpers**: `statusColor()`, `divider()`, `formatTokens()`

#### Banner — Gradient ASCII Art
- 3-color gradient: cyan `#00d4ff` → blue `#4488ff` → purple `#6e7dff`
- Tagline with `●` bullet separators, amber version number
- Heavy divider `━` below banner

#### Component Visual Changes
- **Header**: Heavy-top border `┏━━━━┓`, cyan accent top edge, `●` separators, `◆` title prefix
- **StatusBar**: Thin divider line above, `/help` in accent color, `○` streaming indicator
- **Input**: Round corners `╭╮╯╰`, cyan left-accent edge, `⟫` chevron prompt
- **Message**: Left-border accent per role (cyan/green/amber/purple), `▸` prompt prefix
- **StreamingMessage**: Green left-border accent, styled token counter, accent spinner
- **ToolCall**: Unicode tool icons (`▸◉◈✶≣`), purple theme, left-border result containers
- **DiffPreview**: Card border, `◆` file header, styled `+`/`-` prefixes
- **ApprovalPrompt**: Double border `╔═╗` in green, `⟫`/`▹` selection indicators
- **PermissionPrompt**: Double border `╔═╗` in amber, `◆` warning prefix
- **GateTimeline**: Pipeline tree `┣━`/`┗━`, Unicode status icons `◉✗◆─○`, verdict card

### Changed
- `.version` bumped to 2.0.4 (from 2.0.3)
- `sf_cli/package.json` version bumped to 2.0.4

---

## [2.0.3] - 2026-02-23

### Added — Active Agent Display & Live Token Usage

Real-time visibility into which agent is working and how many tokens are being consumed during streaming.

#### StreamingMessage Agent Attribution
- Shows `sf:coder>` (routed agent name) instead of generic `sf>` during streaming
- Displays live turn count and session token totals below streaming content: `[turn 3 | 12.4k in / 2.1k out]`

#### Header Token Totals
- Cumulative session token count displayed in header info line (e.g. `14.2k tok`)
- Formatted with `k` suffix for readability (1000+ tokens)

#### StatusBar Agent Indicator
- Shows `coder working` instead of `streaming...` when an agent is active
- Turn indicator `(turn N)` shown for multi-turn agentic loops

#### Streaming Metadata State
- `useStream` now exposes `streamingAgent`, `streamingTurnCount`, `sessionInputTokens`, `sessionOutputTokens` as React state
- Session token accumulators track total input/output tokens across all messages

### Changed
- `.version` bumped to 2.0.3 (from 2.0.2)
- `sf_cli/package.json` version bumped to 2.0.3

---

## [2.0.2] - 2026-02-23

### Added — Team Summon (Multi-Agent Auto-Routing)

Summon a team of agents once with `/team <name>`, and every subsequent message is automatically routed to the best-matching team member via lightweight keyword scoring — no manual `/agent` switching needed.

#### `/team` Command
- **6 preset teams**: `dev`, `fullstack`, `security`, `ops`, `review`, `ship`
- **Custom teams**: `/team custom coder tester reviewer` (min 2 agents)
- **Subcommands**: `/team off`, `/team list`, `/team status`
- **Mutual exclusion**: activating a team clears any single agent, and vice versa

#### Keyword-Based Auto-Router
- 30+ agents mapped to weighted regex patterns in `team-router.ts`
- Scoring: sum matched keyword weights per team member, highest wins
- Confidence levels: high (>=6), medium (>=3), low (>=1), fallback (0)
- Deterministic, no LLM calls — ~300 regex tests worst case

#### UI Integration
- **Header**: shows `team:dev (5 agents)` when team active
- **StatusBar**: shows `/team off` hint when team active
- **Message labels**: `sf:coder>` shows which agent handled each message
- **Metadata**: `routedAgent`, `routingConfidence`, `activeTeam` tracked per message

#### Session State
- `activeTeam` in SessionContext with mutual exclusion against `activeAgent`
- Team routing integrated into `useStream.sendMessage()` pipeline

### Changed
- `.version` bumped to 2.0.2 (from 2.0.1)
- `sf_cli/package.json` version bumped to 2.0.2
- 237 tests across 20 test files (26 new: 15 router + 11 command)

---

## [2.0.1] - 2026-02-23

### Performance — Multi-Layer Caching

Token usage and latency optimizations across the CLI provider layer.

#### Anthropic Prompt Caching
- System prompt and last tool definition now marked with `cache_control: { type: 'ephemeral' }` in both `stream()` and `streamWithTools()`
- ~90% token discount on repeated system prompt + tool schema tokens across agentic turns

#### Provider Singleton
- Provider SDK instances cached via `useRef` — no longer reinstantiated on every `sendMessage()` call
- Separate refs for primary and fallback providers, invalidated only when provider name changes

#### In-Memory Budget Cache
- `checkBudget()` accepts optional pre-loaded `UsageData`, eliminating `readFileSync` on every budget check
- Budget data loaded from disk once per session, updated in-memory after each `recordUsage()` call
- Eliminates 2+ synchronous disk reads per agentic turn

#### Tool Transform Memoization
- `toOpenAITools()` and `toGeminiTools()` results memoized by tool-name key
- Tool schemas are identical every turn of the agentic loop — avoids redundant array mapping

### Changed
- `.version` bumped to 2.0.1 (from 2.0.0)
- `sf_cli/package.json` version bumped to 2.0.1

---

## [2.0.0] - 2026-02-23

### Added — Interactive CLI (Node.js + Ink)

Major release: SkillFoundry now ships with an interactive terminal CLI (`sf`) built on Node.js + Ink (React for terminals). The CLI provides a Claude Code / Gemini CLI style experience with streaming AI responses, agentic tool execution, quality gates, and multi-provider support.

#### Phase 1: Foundation MVP

- **Interactive REPL** with streaming markdown rendering in the terminal
- **Anthropic Claude adapter** with full streaming support (`content_block_start/delta/stop`)
- **Session state machine** persisted to `.claude/state.json` (IDLE, GENERATING_STORIES, VALIDATED, EXECUTING_STORY, COMPLETED, FAILED)
- **TOML configuration** loader for `.skillfoundry/config.toml` and `policy.toml`
- **Secret redaction** pipeline (API keys, passwords, tokens, connection strings)
- **Slash command system** with registry: `/help`, `/status`
- **React terminal components**: Header, MessageList, Message, StreamingMessage, Input, StatusBar
- **Terminal markdown** rendering via `marked` + `marked-terminal`
- **Timeline logger** writing to `.skillfoundry/timeline.log`
- **CLI entry point** with Commander: `sf`, `sf init`, `sf chat`
- **23 unit tests** passing (config, redact, command parsing)

#### Phase 2: Tool System

- **5 tool definitions** for Anthropic tool_use API: bash, read, write, glob, grep
- **Tool executor** with `child_process.execSync` for bash, `fs` for file operations, `glob` for pattern matching, `rg`/`grep` for content search
- **Permission engine** with 4 modes: auto, ask, deny, trusted
- **Dangerous command blocking** — `rm -rf /`, `mkfs`, `dd`, `curl|bash` always blocked
- **Sensitive operation detection** — `git push`, `npm publish` always prompt
- **Agentic loop** — up to 25 tool turns per conversation with automatic tool_use → execute → tool_result cycling
- **ToolCall component** displaying tool execution with status spinners
- **PermissionPrompt component** with keyboard-driven Allow/Deny/Always-allow
- **Extended types**: ContentBlock, AnthropicMessage, AnthropicContentBlock, ActiveToolExecution
- **42 additional tests** (tools, executor, permissions)

#### Phase 3: Workflow Integration

- **`/plan <task>`** — Read-only plan generation with PRD context from `genesis/`, saved to `.skillfoundry/plans/`
- **`/apply [plan-id]`** — Plan execution with pre-apply quality gate checks, run bundles saved to `.skillfoundry/runs/`
- **`/gates [target]`** — Independent quality gate execution
- **`/forge`** — Full 5-phase pipeline: Ignite (PRD validation), Forge (story checks), Temper (quality gates), Inspect (security audit), Debrief (summary)
- **Quality gate runner** wrapping `scripts/anvil.sh` with inline fallbacks:
  - T1: Banned pattern scan (TODO/FIXME/HACK) + syntax check
  - T2: Type check (tsc --noEmit, pyright)
  - T3: Test suite (npm test, vitest, pytest)
  - T4: Security scan (hardcoded secrets, eval/exec patterns)
  - T5: Build verification (npm run build, cargo build)
  - T6: Scope validation (changes match story)
- **DiffPreview component** with colorized inline diff rendering
- **GateTimeline component** with real-time gate progress display
- **ApprovalPrompt component** for approve/reject/edit checkpoints
- **27 additional tests** (gates, diff parsing, forge pipeline)

#### Phase 4: Polish — Multi-Provider & Runtime Features

- **5 AI provider adapters**:
  - Anthropic Claude (native SDK with streaming + tool_use)
  - OpenAI (SDK — also used for xAI and Ollama via baseURL)
  - xAI Grok (OpenAI-compatible at api.x.ai/v1)
  - Google Gemini (native fetch + SSE streaming)
  - Ollama local (OpenAI-compatible at localhost:11434/v1)
- **Provider registry** with `AVAILABLE_PROVIDERS`, `createProvider()` factory, `detectAvailableProviders()`
- **Budget enforcement**: per-run and monthly cost caps, usage persisted to `.skillfoundry/usage.json`
- **Memory system**: JSONL knowledge recall with relevance scoring + recency boost, capture to `memory_bank/knowledge/`
- **`/provider [list|set <name>]`** — List available providers or switch active provider
- **`/config [key] [value]`** — View or edit configuration with type coercion
- **`/cost`** — Token usage and cost report with provider breakdown
- **`/memory [stats|recall|capture]`** — Knowledge base operations
- **`/lessons <content>`** — Quick-capture a lesson learned
- **Model pricing tables** for cost estimation across all providers
- **28 additional tests** (providers, budget, memory)

#### Phase 5: Global Deployment & Credential Management

- **Global CLI wrapper** — `install.sh` builds the CLI and creates `~/.local/bin/sf` so users can run `sf` from any project directory
- **`SF_FRAMEWORK_ROOT` env var** — Shell wrapper sets this so the CLI finds framework resources (scripts/anvil.sh, genesis/TEMPLATE.md) regardless of CWD
- **Framework root discovery** (`core/framework.ts`) — resolves framework location from env var or file-based detection
- **`sf setup` CLI subcommand** — Non-interactive credential configuration: `sf setup --provider anthropic --key sk-ant-...`
- **`/setup` slash command** — Configure API keys from within the REPL session
- **Credential storage** at `~/.config/skillfoundry/credentials.toml` with `0600` permissions
- **First-run setup wizard** — Interactive provider selection with API key URLs when no credentials detected
- **`ANTHROPIC_AUTH_TOKEN`** support — Bearer token auth in addition to API key
- **`GEMINI_API_KEY`** alt env var detection for Google Gemini
- **Credential injection** at startup — stored keys injected into `process.env` so SDK constructors auto-discover them (env vars always take precedence)
- **Improved auth error messages** — Auth failures now suggest `sf setup` or `/setup` instead of cryptic SDK errors
- **ASCII art banner** on CLI startup with colored gradient
- **`/exit` and `/quit` commands** — Clean exit from REPL (replaces Ctrl+C guidance)
- **`update.sh` CLI rebuild** — Framework updates now rebuild the CLI and regenerate the wrapper
- **Dynamic version** from `.version` file via `getFrameworkVersion()`

#### CLI Summary

- **30+ source files** across core, commands, components, hooks, utils
- **154 tests** across 14 test files, all passing
- **13 slash commands**: help, status, setup, plan, apply, gates, forge, provider, config, cost, memory, lessons, exit
- **5 AI providers** supported out of the box
- **5 tools** with permission controls and dangerous command blocking
- **Global `sf` command** available system-wide after install

### Changed

- `.version` bumped to 2.0.0 (from 1.9.0.23)
- `sf_cli/package.json` version bumped to 2.0.0
- Version references updated in README.md, AGENTS.md, DOCUMENTATION-INDEX.md, QUICK-REFERENCE.md
- README.md rewritten to feature the Interactive CLI prominently
- New visual user guide: `docs/USER-GUIDE-CLI.md`
- `install.sh` now builds CLI and deploys shell wrapper (Phase 3)
- `update.sh` now rebuilds CLI on framework updates
- Status bar shows `/exit quit` instead of `Ctrl+C exit`
- Provider detection now checks alternate env vars (`ANTHROPIC_AUTH_TOKEN`, `GEMINI_API_KEY`)

---

## [1.9.0.23] - 2026-02-23

### Added — 53-Agent Security Evolution (Full Pipeline Hardening)

Systematic audit of all 53 agents revealed that data isolation, Top 12 security checks, error leakage prevention, and version enforcement were inconsistently applied. This release hardens every agent in the pipeline.

#### Top 7 → Top 12 Security Checks (Framework-Wide)
- **All platforms updated**: `.agents/skills/`, `.claude/commands/`, `.cursor/rules/`, `.copilot/custom-agents/`, `.gemini/skills/`, `agents/`, `bpsbs.md`, `DOCUMENTATION-INDEX.md`, `docs/API-REFERENCE.md`, `docs/MARKET-COMPARISON.md`
- **5 new checks added**: Data isolation/query scoping, pagination/input size limits, error information leakage, concurrent modification safety (optimistic locking), session/token lifecycle

#### Critical Pipeline Agents
- **blitz/SKILL.md**: Non-Negotiable Security Gate — Top 12 checks never skipped even in speed mode
- **ship/SKILL.md**: Steps 2.5 (Data Isolation Spot-Check), 2.6 (Top 12 Security Gate), 2.7 (Version Verification)
- **anvil/SKILL.md**: T1 expanded with data isolation + error leakage scans; T3 expanded with mandatory failure modes
- **go/SKILL.md**: Pre-story data isolation check blocks stories missing ownership specs; project completion expanded
- **gate-keeper/SKILL.md**: 6 new violation types (unscoped query, missing WHERE, scope from params, error leakage, missing pagination, missing idempotency)
- **stories/SKILL.md**: Security checklist expanded (6 items), definition of done expanded, Gherkin cross-user isolation scenarios
- **_autonomous-protocol.md**: Execution rules 7-8 (Top 12 scan, data isolation escalation), 3 new escalation triggers

#### Review & Scanner Agents
- **review/SKILL.md**: Data Isolation & Query Scoping Review section, Extended Security Review section, items 8-12 added
- **security-scanner/SKILL.md**: Quick Scan expanded to Top 12, Prevention Mode expanded with items 8-12
- **senior-engineer/SKILL.md**: Security checks expanded to Top 12 with descriptions
- **forge/SKILL.md**: Phase 3 TEMPER + Phase 4 INSPECT expanded with data isolation and Top 12
- **fixer/SKILL.md**: 6 new violation types in routing table

#### Development Agents
- **debugger/SKILL.md**: Data isolation check in root cause summary, Security-Aware Debugging Checklist
- **refactor/SKILL.md**: Core principle 6 (Security Preservation), Security Invariants Check section
- **migration/SKILL.md**: Data Isolation Requirements section (8 requirements)
- **performance/SKILL.md**: Query & Pagination Safety section (7 checklist items)
- **dependency/SKILL.md**: Package hallucination check enhanced with AI hallucination rate + backdoor checking

#### Operations & Infrastructure Agents
- **devops/SKILL.md**: Test stage + best practices expanded with Top 12, cross-user tests, observability
- **sre/SKILL.md**: SEV1 expanded with cross-tenant exposure, Non-Negotiable Requirements section
- **release/SKILL.md**: Pre-Release Security Gate (MANDATORY) with 8 checklist items
- **ops/SKILL.md**: Data Isolation Monitor section, admin panel scope note
- **health/SKILL.md**: Security configuration checks expanded (3 new items)
- **nuke/SKILL.md**: Safety checks before nuking section (4 items)
- **data-architect/SKILL.md** (skill): Anti-patterns expanded, requirements checklist expanded

### Changed
- `.version` bumped to 1.9.0.23
- Version references updated in README.md, AGENTS.md, DOCUMENTATION-INDEX.md, QUICK-REFERENCE.md

---

## [1.9.0.22] - 2026-02-22

### Added — Data Isolation & 27 Enforcement Gap Fixes

Real-world testing revealed that the agent pipeline enforced authentication and role-based access but never verified data ownership. A systematic audit uncovered 27 gaps where agents mention concerns but lack concrete enforcement. This release closes all of them.

#### PRD Template (`genesis/TEMPLATE.md`)
- **Entity Cards**: `Data Ownership` and `Access Scope` rows — forces specifying which column scopes rows and the access boundary
- **Permissions Matrix**: `Data Scope` column mapping each action to a concrete WHERE clause pattern
- **Section 6.7 — Data Isolation Specification**: query scope rules, isolation enforcement, cross-tenant rules, mandatory test cases
- **Section 4.2 — Security**: session lifecycle, rate limits, CORS policy, concurrent access, file uploads, error handling
- **Section 4.5 — Observability**: structured logging, health checks, monitoring, audit logging requirements
- **API Contract**: pagination max cap, rate limits, data scoping on endpoints
- **Error Codes**: `VERSION_CONFLICT`, `IDEMPOTENCY_CONFLICT`, `PAYLOAD_TOO_LARGE`
- **PRD Checklist**: data isolation, observability, pagination, rate limits, concurrent modification

#### Layer-Check (`layer-check/SKILL.md`)
- **Database**: ownership columns, version/ETag for optimistic locking, migration safety (backward compat, NOT NULL backfill, idempotent, perf on large tables), soft delete scoping, cascade documentation, UTC timestamps
- **Backend API**: input size limits, error leakage prevention, CORS specifics, session management, file upload validation, structured logging with correlation ID, health/readiness probes, config validation on startup, circuit breaker
- **Backend Evidence**: negative tests, boundary tests, concurrent access, rate limit verification required
- **Documentation Gate**: version bump enforcement added

#### Coder Skills (`coder/SKILL.md`, `ruthless-coder.md`)
- **Top 7 → Top 12** critical security checks
- New checks: pagination/input size limits, error information leakage, concurrent modification safety (optimistic locking), session/token lifecycle

#### Data Architect (`data-architect.md`)
- **Query Anti-Pattern**: `Unscoped Query on Owned Entity`
- **New Checklist Categories**: Data Ownership, Concurrent Modification, Soft Delete Integrity, Cascade Rules, Timestamp Standards

#### API Design (`api-design/SKILL.md`)
- **Design Checklist**: pagination caps, input constraints, idempotency, optimistic locking, deprecation policy
- **Security Checklist**: expanded from 6 to 15 items — data isolation, file uploads, bulk endpoint limits, session lifecycle, structured error responses

#### Security Specialist (`security-specialist.md`)
- **STRIDE**: cross-user/cross-tenant exposure added to Info Disclosure
- **OWASP A01**: unscoped queries, missing ownership WHERE, scope from request params
- **OWASP A04**: optimistic locking, unbounded endpoints, idempotency
- **OWASP A05**: verbose errors, CORS wildcard, config validation, secrets in config
- **OWASP A07**: token expiry, session invalidation, refresh token rotation, auth rate limiting
- **OWASP A09**: WHO/WHAT/WHICH/WHEN audit, failed access logging, correlation ID, bulk op logging

#### Tester (`ruthless-tester.md`, `tester/SKILL.md`)
- **Test Categories**: expanded from 6 to 15 — data isolation, concurrent modification, pagination abuse, rate limit verification, input size attacks, error leakage audit, idempotency, session lifecycle, soft delete verification
- **Coverage Summary**: expanded from 4 to 9 checkpoints

#### Merciless Evaluator (`merciless-evaluator.md`)
- **What to Look For**: 6 new evaluation criteria (unbounded endpoints, optimistic locking, error leakage, negative tests, session lifecycle, audit logging)
- **BPSBS Compliance**: expanded from 3 to 7 checks

### Changed
- Version bump from `1.9.0.21` to `1.9.0.22`
- Documentation gate now requires version bump on framework changes

---

## [1.9.0.21] - 2026-02-22

### Added — Google Gemini Platform Support
- **`.gemini/skills/*.md`** — New Gemini skill target directory generated from framework command sources
- **`install.sh` / `install.ps1`** — Added `gemini` to platform selection, validation, dry-run summaries, install copy, and quick-start output
- **`update.sh` / `update.ps1`** — Added Gemini platform detection, version marker propagation, and per-platform skill updates
- **`scripts/install-unified.sh` / `scripts/install-unified.ps1`** — Added Gemini auto-detection, menu selection, and post-install guidance
- **`scripts/sync-platforms.sh`** — Extended sync/check/list/diff flows to include Gemini as 5th generated platform

### Changed
- **Platform count** updated from 4 to 5 in install/update headers and sync summaries
- **Documentation** updated to reflect 5-platform support (Claude Code, GitHub Copilot CLI, Cursor, OpenAI Codex, Google Gemini)

### Notes
- Bash validation/runtime steps could not be executed in this environment due local `bash.exe` WSL mount failure; PowerShell script parsing completed successfully

---

## [1.9.0.20] - 2026-02-22

### Added — 53-Agent Evolution & Perfection Loop
- **`scripts/agent-evolution.ps1`** — Debate -> implement -> iterate engine with deterministic peer reviewers, strict debate findings, auto-remediation, and `perfection_achieved` gate
- **`scripts/agent-evolution.sh`** — Bash parity for analyze/cycle workflows with roster-aware target counts
- **`config/core-agents-53.txt`** — Canonical 53-agent core roster (default baseline)
- **`config/core-agents-46.txt`** — Legacy roster fallback for compatibility
- **`docs/AGENT-EVOLUTION.md`** — Complete usage guide: analyze/debate/cycle, reports, perfection criteria, 100-iteration stress command
- **`tests/test-agent-evolution.ps1`** and **`tests/test-agent-evolution.sh`** — Validation for report schema and debate/perfection signals

### Changed
- **`.agents/skills/*/SKILL.md`** — Added continuous-improvement contracts, peer-improvement signals, and explicit execution sections to support iterative hardening
- **`README.md`** — Updated with v1.9.0.20 highlights and current version bump
- **`DOCUMENTATION-INDEX.md`** — Updated framework version and references to 53-agent core roster
- **`docs/QUICK-REFERENCE.md`** — Updated version and added agent evolution command set
- **`docs/AGENTS.md`** — Updated headline statistics for 53-agent core / 60 skills

### Verified
- 100-iteration forced cycle executed with auto-fix:
  - `core_count=53`
  - `debate_open_findings=0`
  - `perfection_score=100`
  - `perfection_achieved=true`

---

## [1.9.0.19] - 2026-02-20

### Added — Autonomous Developer Loop & Knowledge Sync
- **`agents/_autonomous-protocol.md`** — Intent routing rules, execution pipeline, review format. Classifies every user input as FEATURE/BUG/REFACTOR/QUESTION/OPS/MEMORY and routes to the correct pipeline
- **`agents/_intent-classifier.md`** — Classification examples, edge cases, confidence thresholds, disambiguation rules
- **`.claude/commands/autonomous.md`** — `/autonomous` toggle command (on/off/status) with flag file `.claude/.autonomous`
- **`scripts/knowledge-sync.sh`** — Background daemon (1295 lines): init, start, stop, sync, status, register, promote, log. Interval-based sync (default 5 min) with PID management and log rotation
- **`scripts/sanitize-knowledge.sh`** — Pre-commit sanitizer (601 lines): strips secrets (API_KEY, TOKEN, PASSWORD, PRIVATE_KEY, AWS_ACCESS), normalizes paths to `$PROJECT_ROOT`, validates JSON/JSONL, skips .env/.key/.pem files
- **`scripts/session-init.sh`** — Session start: pulls global knowledge from remote, starts sync daemon
- **`scripts/session-close.sh`** — Session end: records session end, forces final sync, runs promotion check, stops daemon
- **Global knowledge repo structure** — `global/` (lessons, preferences, anti-patterns, tech-stack) + `projects/<name>/` (per-project knowledge, sessions, agent stats)
- **Lesson promotion engine** — Patterns appearing 3+ times in `errors.jsonl` auto-promoted to `global/lessons.jsonl`
- **PRD** — `genesis/2026-02-20-autonomous-developer-loop.md` with 9 stories, dependency graph, parallel execution groups
- **CLAUDE.md** — Added Autonomous Developer Loop section with protocol files, session lifecycle, quick start

### Fixed
- **PowerShell Linux dotfile handling** — `Get-Item` cannot find files starting with `.` on Linux without `-Force` flag; added to `install.ps1` and `update.ps1`
- **install.ps1 rollback safety** — Error trap rollback now checks `$resolvedTarget` against `$ScriptDir` to prevent deleting the framework source directories when `TargetDir` defaults to `.`

---

## [1.9.0.18] - 2026-02-15

### Fixed
- **install.ps1 execution order** — Dry-run check was placed after file installation, step counter was initialized after use, duplicate directory creation; restructured entire post-validation flow
- **memory_bank seed files not tracked** — `.gitignore` blanket `memory_bank/*` rule had no negation for `relationships/` and `retrieval/` directories; 4 JSON seed files never committed (fixed 8 test failures)
- **wizard.sh macOS syntax error** — `$(case $REPLY in 1) echo ...)` pattern fails on bash 3.2 (macOS default) because parser interprets case `)` as closing `$(`; replaced with portable case blocks
- **macOS bash 4+ incompatibilities** — `declare -A` (associative arrays) in `install.sh` caused all install tests to fail with exit code 2 on macOS bash 3.2; replaced with loop-based dedup and `eval`-based variables. `${var^^}` case conversion in `notify.sh`, `heartbeat.sh`, `compliance-evidence.sh` replaced with `tr`. Added bash 4 version guards to `parallel/visualize.sh` and `scripts/monorepo.sh` which require associative arrays for graph algorithms

### Changed — Script Modernization (all 6 scripts)
- **`--yes`/`-y`/`-Yes`** non-interactive mode on all install and update scripts (bash + PowerShell)
- **`--dry-run`/`-DryRun`** preview mode on install scripts
- **`--help`/`-Help`** and **`--version`/`-Version`** flags on install scripts
- **Progress indicators** `[1/N]` step counter through installation phases
- **Elapsed timer** shows duration in completion summary
- **What's New** parses CHANGELOG.md and displays latest version highlights
- **Compact summary** replaces 130-line verbose output with ~35-line quick-start
- **Auto-derived dates** from `.version` file mtime instead of hardcoded strings
- **Modern headers** `┌───┐` box style with version and date
- **Unified installers** now use single `install.sh --platform=csv --yes` call instead of per-platform loop

### Fixed — update.sh
- **`local` outside function** bug at line 1176 (pre-existing)
- **`$CHANGELOG_FILE`** variable defined but never used — now referenced in What's New display

---

## [1.9.0.17] - 2026-02-17

### Added — OpenClaw-Inspired Monitoring & Developer Memory

Three new features inspired by OpenClaw's proactive intelligence:

#### Heartbeat — Proactive Monitoring Daemon
- **`scripts/heartbeat.sh`** — Background daemon for project health monitoring
- **Commands:** `start`, `stop`, `status`, `run-once`, `logs`, `init`
- **5 health checks:** Test suite, git health (secrets/uncommitted/divergence), session health, gate rejection rate, disk/log health
- **User-editable `HEARTBEAT.md`** at project root enables/disables checks and sets severity
- **Daemon pattern:** Background loop with PID file, configurable interval via `HEARTBEAT_INTERVAL` env var (default: 30 min)
- **State tracking:** `.claude/heartbeat-state.json` stores last check results
- **Log rotation:** `logs/heartbeat.log` keeps last 1000 lines

#### Notify — Multi-Channel Notification System
- **`scripts/notify.sh`** — Multi-channel notification dispatcher
- **Commands:** `send`, `test`, `config`, `history`, `init`
- **4 channels:** Slack (webhook), Discord (webhook), desktop (notify-send/osascript), terminal (colored stderr + bell)
- **5 notification levels:** info, success, warning, error, critical (color-coded)
- **Throttling:** SHA-256 message hashing, suppress duplicates within configurable window (default: 5 min)
- **Quiet hours:** Optional time range to suppress non-critical notifications
- **Sourceable:** `notify()` function callable from other scripts

#### Preferences — Developer Behavioral Memory
- **`scripts/preferences.sh`** — Persistent developer preference management
- **Commands:** `set`, `get`, `list`, `learn`, `inject`, `init`, `reset`
- **Auto-learning:** Scans codebase for indentation, naming conventions, frameworks (package.json/requirements.txt), test patterns, commit style
- **Confidence scoring:** Each preference has 0.0-1.0 confidence; only >0.7 injected into agents
- **Preference hierarchy:** Project overrides global, explicit overrides learned
- **`inject` command:** Generates ~20-30 line markdown summary for agent prompt injection
- **`agents/_preferences-protocol.md`** — Shared module enforcing preference compliance across all agents

### Changed
- **Companion panel** — Added `/heartbeat`, `/notify`, `/prefs` to always-available commands
- **`.gitignore`** — Added heartbeat.pid, heartbeat-state.json, notifications.json/jsonl, preferences.json

---

## [1.9.0.16] - 2026-02-15

### Added — Competitive Leap: CI/CD + Quality Intelligence + Moonshots

Full execution of the Competitive Leap PRD — 17 stories across 6 phases.

#### Phase 0-1: CI/CD & Bug Fixes
- **GitHub Actions CI pipeline** — Automated test suite on every push and PR with multi-OS matrix (Ubuntu 22.04, Ubuntu 24.04, macOS)
- **CI platform sync verification** — `sync-platforms.sh check` runs in CI to catch platform drift
- **CI shell syntax validation** — `bash -n` validation on all scripts
- **CI status badge** in README.md

#### Phase 3: Standards & Capture
- **Agent Trace format** — `scripts/attribution.sh --format=agent-trace` outputs Cursor-compatible Agent Trace JSON
- **Prompt/response capture** — `scripts/session-recorder.sh prompt` with opt-in recording, sanitization (redacts keys/tokens), SHA-256 hashing, 50KB per-entry limit
- **Cost-aware routing** — `scripts/cost-router.sh` routes agents to haiku/sonnet/opus based on task complexity. Disabled by default, configurable via `.claude/routing.json`

#### Phase 4: Quality & Intelligence
- **Quality-at-generation primer** — `agents/_quality-primer.md` injects banned patterns, security rules, and test requirements into agent generation prompts
- **Rejection tracker** — `scripts/rejection-tracker.sh` records gate rejections, auto-proposes rules after 3+ identical patterns, supports approve/reject/inject lifecycle
- **Self-improving quality rules** — Rejection patterns auto-propose rules → human approves → `rules inject` updates quality primer

#### Phase 5: Moonshots
- **A2A protocol agent cards** — `scripts/a2a-server.sh` generates A2A-compatible JSON cards for all 62 agents per Google/Linux Foundation spec. Commands: `card`, `cards`, `discover`, `validate`
- **Arena mode** — `scripts/arena-evaluate.sh` + `agents/_arena-protocol.md` for competitive agent evaluation. Weighted scoring: correctness (40%), quality (25%), security (20%), performance (15%)
- **Compliance-as-code pipeline** — `compliance/` directory with HIPAA (15 checks), SOC2 (12 checks), GDPR (10 checks). Each profile: `checks.sh`, `profile.json`, `README.md`
- **Compliance evidence collection** — `scripts/compliance-evidence.sh` with SHA-256 tamper-evident manifests. Commands: `collect`, `package`, `verify`, `report`

#### PRD & Stories
- **Competitive Leap PRD** — `genesis/2026-02-15-competitive-leap.md` with 6 phases, 17 stories, 46 functional requirements
- **17 implementation stories** in `docs/stories/competitive-leap/`

### Fixed
- **`harvest.sh --status`** — Exit code 1 on empty `.project-registry-meta.jsonl` (grep on empty file under `set -o pipefail`). Added `-s` file check and `|| true` guard.

### Security
- **Removed `eval()` command injection** in `rejection-tracker.sh` — replaced with safe `jq` filtering
- **Secured `mktemp`** in `rejection-tracker.sh` — project-dir + `chmod 600` instead of world-readable `/tmp`
- **Replaced unsafe `sed`** with `awk` for quality primer rule injection (no delimiter injection)
- **Added input validation** with category allowlist in rejection tracker

### Removed
- **`scripts/convert-to-copilot.sh`** — Deprecated script superseded by `sync-platforms.sh` since v1.9.0.3
- **`.project-registry-meta.jsonl`** — Removed 0-byte file; harvest.sh already handles missing file gracefully

---

## [1.9.0.15] - 2026-02-15

### Added — Observability & Reasoning Layer

Native session tracking, line attribution, named checkpoints, and structured commit metadata — inspired by Entire.io concepts but built natively into the framework.

- **`scripts/attribution.sh`** — Line attribution tracking (human vs AI code %). Commands: `baseline` (snapshot before agent session), `calculate` (diff after session), `report` (per-file breakdown), `trailer` (git commit trailer format), `status`. Stores results in `.claude/attribution/`.
- **`scripts/session-recorder.sh`** — Session lifecycle management. Creates session entry when agent starts, logs events/decisions/file operations, records outcome. Commands: `start`, `log`, `decision`, `file`, `end`, `show` (timeline), `list` (recent sessions). Stores in `logs/sessions/{date}/session-{id}.jsonl`.
- **`scripts/checkpoint.sh`** — Named rewindable save points using lightweight git tags. Commands: `create "description"`, `list`, `rewind <name|index>`, `diff <a> <b>`, `show`, `clean`. Tag format: `cas-cp-{timestamp}-{description}`.
- **`agents/_commit-trailers.md`** — Shared module defining structured git commit metadata. Trailers: `Claude-AS-Agent`, `Claude-AS-Story`, `Claude-AS-Session`, `Claude-AS-Attribution`, `Claude-AS-Gate`. Referenced by `/coder`, `/go`, `/ship`, `/forge`.
- **`agents/_session-protocol.md`** — Shared module defining mandatory session lifecycle and decision logging. Four phases: START (baseline + recorder), ACTIVE (log decisions/events/files), CLOSING (end session + attribution), END (harvest + trailers). Minimum 1 decision record per story.
- **`/replay --show`** — New session viewer mode. List recent sessions and display full timeline with events, decisions, file operations, and gate results. Read-only (no re-execution). Available across all 4 platforms.

### Changed
- `/replay` enhanced from "Replay Last Execution" to "Replay & Session Viewer" across all 4 platforms
- Documentation updated for observability layer (DOCUMENTATION-INDEX, QUICK-REFERENCE, AGENTS.md)
- Tests added for all 3 new scripts and 2 new shared modules

---

## [1.9.0.14] - 2026-02-13

### Added
- **OpenAI Codex platform support** — 4th platform with native Skills integration
- **60 Codex Skills** — `.agents/skills/*/SKILL.md` generated from agent sources + standalone commands
- **AGENTS.md** — Root-level Codex always-on context (framework overview, skill index)
- **Sync engine 4-platform support** — `sync-platforms.sh` now generates Claude, Copilot, Cursor, and Codex files
- **Codex SKILL.md format** — YAML frontmatter with `name` and `description` for implicit activation
- **Anvil skill scripts** — Symlinked `scripts/anvil.sh` for native Codex execution

### Changed
- Platform sync now generates 4 x agents files (was 3 x)
- Install scripts detect and support Codex CLI (`codex` command)
- Companion panel recognizes Codex platform
- `sync-platforms.sh list` shows 4-column status `[C|P|R|X]`
- Documentation updated for quad-platform support

---

## [1.9.0.13] - 2026-02-09

### Added — The Anvil (6-Tier Quality Gate System)

LLMs generate code optimistically (forward, single-pass) but debug analytically (backwards from evidence). **The Anvil** inserts 6 tiers of validation between every agent phase to catch issues early before they cascade through the pipeline.

- **The Anvil** — 6-tier quality gate system running between every agent handoff:
  - **T1: Shell Pre-Flight** (`scripts/anvil.sh`) — Pure bash, no LLM. Syntax validation, banned pattern scan, import resolution, scope check. Runs between EVERY agent handoff.
  - **T2: Canary Smoke Test** (`agents/_canary-smoke-test.md`) — Quick single test after Coder: can the module import? Does it compile? FAIL skips Tester entirely → routes to Fixer.
  - **T3: Self-Adversarial Review** (`agents/_self-adversarial-review.md`) — Forces Coder to list 3+ failure modes with mitigations before handoff. Verdict: RESILIENT or VULNERABLE.
  - **T4: Scope Validation** (`agents/_scope-validation.md`) — Compares story's `Expected Changes` against `git diff --name-only`. Missing files → BLOCK, unexpected files → WARN.
  - **T5: Contract Enforcement** (`agents/_contract-enforcement.md`) — Validates API implementation matches story's declared API Contract table. Missing endpoint → BLOCK.
  - **T6: Shadow Tester** (`agents/_shadow-tester.md`) — Read-only parallel agent generating prioritized risk list for Tester. HIGH/MEDIUM/LOW severity.
- **`scripts/anvil.sh`** — T1 shell validation script (~340 lines). Commands: `check`, `syntax`, `patterns`, `imports`, `scope`, `--help`. Exit codes: 0=pass, 1=warn, 2=block.
- **`agents/_anvil-protocol.md`** — Master protocol defining all 6 tiers, pipeline integration, severity levels (BLOCK/WARN/INFO), output format.
- **`/anvil` command** — Manual Anvil invocation across all 3 platforms (Claude Code, Cursor, Copilot). Run specific tiers or full report.
- **Pipeline integration** — `go.md` updated: `Architect → ANVIL T1 → Coder (+T6 Shadow) → ANVIL T1+T2+T3 → Tester → ANVIL T1 → Gate-Keeper (T4+T5)`
- **Fast-fail behavior** — T1/T2 failures skip downstream agents to avoid wasting tokens
- **`--no-anvil` flag** — Disable Anvil checks in `/go` for debugging
- **Story template** — `stories.md` now includes `Expected Changes` section for T4 scope validation

### Changed

- **`coder.md`** — Added mandatory Self-Adversarial Review (T3) section across all 3 platforms
- **`tester.md`** — Added Canary Smoke Test pre-condition (T2) and Shadow Tester risk input (T6) across all 3 platforms
- **`gate-keeper.md`** — Added Scope Validation (T4) and Contract Enforcement (T5) integration across all 3 platforms
- **`go.md`** — Added ANVIL INTEGRATION section with checkpoint details, fast-fail, and `--no-anvil` flag
- **`forge.md`** — Added Anvil reference in Phase 2 (FORGE) description

---

## [1.9.0.12] - 2026-02-09

### Added — Enhanced DX + Templates + Analytics

- **4 new commands** across all 3 platforms: `/status`, `/profile`, `/replay`, `/analytics`
  - `/status` — Project status dashboard (PRDs, stories, layers, memory, execution state)
  - `/profile` — Session profile manager (load/create workflow presets: default, blitz, cautious, autonomous)
  - `/replay` — Re-run last execution (with `--failed`, `--from=<phase>`, `--dry-run`)
  - `/analytics` — Agent usage analytics dashboard (invocations, success rates, trends)
- **Session profiles** — 4 built-in profiles in `.claude/profiles/` (default, blitz, cautious, autonomous)
- **PRD templates library** — `genesis/TEMPLATES/` with 4 quick-start templates:
  - `api-service.md` — REST APIs and backend services
  - `cli-tool.md` — Command-line tools and automation
  - `fullstack-feature.md` — Full-stack features (DB + Backend + Frontend)
  - `dashboard.md` — Analytics and data visualization dashboards
- **Agent usage analytics** — `memory_bank/knowledge/agent-stats.jsonl` for tracking invocations
- **Forge Phase 6: Debrief** — Auto-writes scratchpad summary to `.claude/scratchpad.md` after `/forge`

### Fixed

- **Reflection protocol tests** — Added reflection protocol sections to coder, tester, and architect across all 3 platforms (9 files)
- **DX command sync** — Synced cost, explain, undo, health, swarm to Cursor and Copilot (10 files)
- **`/gohm --push`** — Added auto-commit + push flag across all 3 platforms
- **`/nuke` confirmation** — Replaced typed "NUKE" confirmation with standard (y/N) pattern

---

## [1.9.0.11] - 2026-02-09

### Added — Shortcut Commands + The Forge

- **The Forge** — The 46-agent team now has an official name: "The Forge" (cold-blooded agents forging production code)
- **7 new shortcut commands** across all 3 platforms (Claude Code, Cursor, Copilot):
  - `/forge` — Full pipeline: validate PRDs + implement (semi-auto+parallel) + layer-check + security audit + harvest memory
  - `/gosm` — Go Semi-Auto (`/go --mode=semi-auto`) — recommended default
  - `/goma` — Go Autonomous (`/go --mode=autonomous`)
  - `/blitz` — Lightning mode: parallel + TDD + semi-auto
  - `/gohm` — Harvest memory from current project
  - `/ship` — Pre-release pipeline: layer-check + security audit + release prepare
  - `/nuke` — Clean slate: rollback + clean state (requires confirmation)
- **21 new files** — 7 per platform (.claude/commands, .cursor/rules, .copilot/custom-agents)
- **No install script changes needed** — existing wildcard copy picks up new files automatically

---

## [1.9.0.10] - 2026-02-09

### Added — Auto-Memory Recording

- **Orchestrator & Coder agents** now automatically record lessons learned after each story
  - `memory_bank/knowledge/decisions.jsonl` — Architectural choices, trade-offs
  - `memory_bank/knowledge/corrections.jsonl` — Bugs found, wrong assumptions fixed
  - `memory_bank/knowledge/patterns.jsonl` — Reusable code patterns discovered
- **Updated across all 3 platforms** — 8 files (2 shared agents + 6 platform copies: Claude Code, Cursor, Copilot)
- **End-to-end knowledge lifecycle**: Install → Agents learn automatically → Harvest → Git push → Available everywhere
- JSONL format with reality anchors, tags, and lineage tracking

---

## [1.9.0.9] - 2026-02-08

### Fixed — Memory Bank Install Gap

- **install.sh / install.ps1** — Now create `memory_bank/knowledge/` directory in target projects
  - Seeds with `bootstrap.jsonl` (framework facts) so agents can write lessons from session one
  - Previously missing: harvest would fail with "No knowledge directory" on every installed project
- **Knowledge lifecycle now works end-to-end**:
  - Install creates `memory_bank/knowledge/` with bootstrap
  - Agents write lessons during sessions (via `/memory`)
  - `scripts/memory.sh harvest <project>` collects lessons into framework
  - `git commit + push` shares lessons across machines

---

## [1.9.0.8] - 2026-02-08

### Changed — Documentation Deduplication & Cleanup

- **CLAUDE.md** — Slimmed from 2023 lines to 267 lines (framework-specific only)
  - Removed sections duplicating global `~/.claude/CLAUDE.md` (path safety, security heuristics, LLM failures, test coverage, module skeleton, etc.)
  - Relocated enterprise production patterns to `docs/enterprise-standards.md`
  - Added header referencing global rules, enterprise standards, and ANTI_PATTERNS
- **docs/enterprise-standards.md** (NEW, ~1352 lines) — Relocated production operations reference:
  - .gitignore security, auth/token management, admin credentials, LoggerService
  - PM2 deployment, SEO, DB migrations, observability, incident response
  - Graceful shutdown, API versioning, concurrency, error resilience
  - Dependency management, feature flags, caching, performance budgets
  - Soft delete/data retention, load testing
- **ANTI_PATTERNS install path** — Files now install to `docs/` instead of project root
  - Updated `install.sh`, `update.sh`, `install.ps1`, `update.ps1`
  - `update.sh` auto-migrates existing root files to `docs/`
  - Updated 68+ file references across agents, commands, cursor rules, and copilot agents
- **bpsbs.md** — No longer copied to target projects (covered by CLAUDE.md + global rules)
  - All references across 51 files updated from `bpsbs.md` to `CLAUDE.md`
- **Token savings** — ~13,000 tokens/session reduced by eliminating triple-injection of same rules

---

## [1.9.0.7] - 2026-02-08

### Added - Deliberation Protocol

- **Deliberation Protocol** (`agents/_deliberation-protocol.md`) — Structured multi-perspective design review before implementation
  - Mandatory triggers: architectural decisions, security-sensitive changes, multiple valid approaches, cross-cutting concerns
  - 3-phase format: Proposal (architect) → Challenge (perspectives) → Synthesis (architect)
  - 3 depth levels: Quick (low-risk), Standard (moderate), Deep (irreversible/security-critical)
  - Resolution rules: reality anchors win, security escalates, simplicity breaks ties
  - Decision records preserved append-only in scratchpad

### Changed
- `agents/project-orchestrator.md` — Added Deliberation Phase between Architecture and Implementation
- `agents/cold-blooded-architect.md` — Architect opens and closes deliberation, synthesizes feedback

---

## [1.9.0.6] - 2026-02-08

### Added — NASAB Framework Integration

7 concepts from the NASAB framework (Pillars 3, 4, 7, 8, 9, 10) absorbed into existing agents:

- **`agents/_bidirectional-iteration.md`** — Track fix-break oscillation cycles, detect convergence, recommend refactoring over patching (Pillar 9)
- **`agents/_dissent-resolution.md`** — Protocol for resolving conflicting agent recommendations: reality anchor wins, thin consensus escalates, security always escalates (Pillar 4)
- **`agents/gate-keeper.md`** — Evidence-based capability gates: 5 levels (syntax → execution → domain → ambiguity → financial) with evidence accumulation thresholds (Pillar 3)
- **`agents/cold-blooded-architect.md`** — Constraint classification: Physical/Conventional/Regulatory/BestPractice. Explore alternatives for non-physical constraints (Pillar 10)
- **`agents/memory-curator.md`** — Pattern detection (parental inheritance): 6 pattern types, unconscious pattern surfacing, conscious marking (Pillar 8)
- **`agents/mathematical-ground-checker.md`** — Context-aware usage validation: check formula assumptions against current context, warn when violated (Pillar 7)
- **`agents/fixer-orchestrator.md`** — Oscillation detection: stop retrying when fix-break cycles detected, escalate with refactoring recommendation (Pillar 9)

### Changed

- **`agents/_agent-protocol.md`** — Added disagreement resolution section referencing dissent protocol

---

## [1.9.0.5] - 2026-02-08

### Added

#### Git-Based Knowledge Hub — Remote Distribution & Cross-Machine Sync
Framework is now a git repository. Knowledge, scratchpads, and metrics sync across machines via GitHub.

- **`scripts/companion.sh`** - Context-aware tmux companion panel:
  - Reads `.claude/scratchpad.md` to determine current phase, task, and agent
  - Shows phase-relevant commands (architecture, implementation, testing, validation, docs, ops)
  - Displays hub sync status and modified files
  - Auto-refreshes every 5 seconds, press 'q' to quit
  - `--tmux` flag: auto-creates a tmux side pane (35 columns)
  - `--once` flag: render once and exit
  - Pure bash, ANSI colors, zero dependencies beyond tmux

- **`scripts/knowledge-sync.sh`** - Hub sync engine (remote transport layer):
  - `setup <repo-url> [--machine-id=name]` - Configure hub URL and machine identity
  - `push [lesson-file]` - Push knowledge (markdown lessons or promoted JSONL) to hub
  - `pull` - Pull latest from hub with conflict handling (rebase with merge fallback)
  - `scratchpad push` - Push project scratchpad for cross-machine continuity
  - `scratchpad pull [machine-id]` - Pull scratchpad from another machine
  - `metrics push` - Aggregate and push usage metrics
  - `status` - Show hub configuration, sync state, and knowledge counts
  - Offline-first: all push commands commit locally, push when online

- **Hub directories**:
  - `knowledge/promoted/` - Curated markdown lessons
  - `knowledge/staging/` - Submitted lessons awaiting review
  - `knowledge/schema.md` - Lesson format specification
  - `scratchpads/` - Cross-machine session state
  - `metrics/` - Aggregated usage metrics

- **`.claude/hub.json`** - Per-machine hub configuration (hub_url, machine_id, sync timestamps)

### Changed

- **`.gitignore`** - Selectively un-ignore central knowledge files (bootstrap.jsonl, *-universal.jsonl) for distribution
- **`update.sh`** - Added `--remote` flag to pull from hub before updating projects
- **`scripts/install-unified.sh`** - Added GitHub clone option for framework installation
- **`scripts/harvest.sh`** - Auto-push promoted knowledge to hub after promotion cycle
- **`scripts/memory.sh`** - Added `hub` command (delegates to knowledge-sync.sh)
- **`tests/run-tests.sh`** - Added 7 hub test functions under `--test hub` filter, 4 companion tests under `--test companion`
- **`agents/_agent-protocol.md`** - Hub pull added to session boot sequence (step 0, silent, non-blocking)
- **`agents/_context-discipline.md`** - Hub push added to post-action protocol; new session end protocol
- **`agents/_state-machine.md`** - Hub sync in INITIALIZING and COMPLETED transition actions

---

## [1.9.0.4] - 2026-02-08

### Changed

#### Persistent Scratchpad — Cross-Platform Session Continuity
Scratchpad is now a live file on disk (`.claude/scratchpad.md`) instead of an in-memory concept. Agents write it after every major action and read it on session start. When a user hits the context limit in Claude Code and switches to Copilot CLI or Cursor, the next session picks up exactly where the previous one left off — automatically, no manual handoff needed.

- **`agents/_context-discipline.md`** - Scratchpad management rewritten:
  - Scratchpad persisted to `.claude/scratchpad.md` after every major action
  - Read on session start with staleness detection (>24h triggers verification)
  - New scratchpad format: includes timestamp, platform, agent, continuation notes
  - New "Cross-Platform Continuity" section with platform-specific resume behavior
  - Persistence rules (write-after-action, overwrite-not-append, 200-400 token target)

- **`agents/_agent-protocol.md`** - Session boot sequence added:
  - Every agent session reads `.claude/scratchpad.md` on start
  - Platform switch detection (announces continuation from previous platform)
  - Cross-references with `.claude/state.json` for `/go` executions
  - Agent response format extended with `scratchpad_update` field

- **`agents/_state-machine.md`** - Scratchpad integrated into state machine:
  - `persist_scratchpad` added to transition actions (INITIALIZING, EXECUTING_STORY)
  - `.claude/scratchpad.md` added to state file locations
  - Resume protocol updated: scratchpad loaded alongside state.json

---

## [1.9.0.3] - 2026-02-07

### Added

#### Platform Sync Engine
Generates all 3 platform command files (Claude Code, Copilot, Cursor) from agent source files, eliminating manual triple-file creation when adding new agents.

- **`scripts/sync-platforms.sh`** - Platform Sync Engine:
  - `sync [--all | agent-name]` - Generate platform files from agent source
  - `check` - Verify all agents have in-sync platform files
  - `list` - Show agent-to-command mapping with sync status
  - `diff [agent-name]` - Show differences between existing and generated files
  - `--dry-run` flag for preview without writing
  - Section stripping: removes "Integration with Other Agents" and "Context Discipline" sections
  - Persona injection: adds persona reference after first paragraph
  - Claude/Cursor: identical stripped content; Copilot: metadata wrapper + usage boilerplate

- **`command:` YAML frontmatter field** - Added to all 26 public agent files:
  - Maps agent filename to command name (e.g., `ruthless-coder` → `coder`)
  - 24 agents mapped to commands, 2 set to `none` (agent-profile, knowledge-curator)

### Changed

- **72 platform files regenerated** - All 24 agent-backed commands across 3 platforms synced from source
- **`scripts/convert-to-copilot.sh`** - Added deprecation notice (superseded by sync-platforms.sh)
- **`tests/run-tests.sh`** - Added 5 platform sync test functions
- **`DOCUMENTATION-INDEX.md`** - Added sync-platforms.sh reference, updated version to 1.9.0.3
- **`README.md`** - Added sync-platforms.sh to scripts section

---

## [1.9.0.2] - 2026-02-07

### Added

#### Ops Tooling Generator Agent
Operational tooling generation for completed projects: admin panels, debug overlays, and feedback systems.

- **`agents/ops-tooling-generator.md`** - Ops Tooling Generator agent (46th agent):
  - `/ops admin` - Admin/monitoring panel: console log viewer, API health monitor, system metrics
  - `/ops debug` - Debug mode overlay activated via Ctrl+Shift+D: element inspector showing component name, file path, event handlers, API calls; network inspector panel; state diff viewer
  - `/ops feedback` - End-user feedback system: bug/issue reports, feature requests, screenshot upload (file picker + clipboard paste), automatic context capture
  - `/ops all` - Generate all three components
  - Tech stack detection: React/Next.js, Angular, Vue, ASP.NET, FastAPI, vanilla JS
  - Output directory: `src/ops/` with admin/, debug/, feedback/ subdirectories
  - Dark-mode-first design, WCAG AA accessibility, responsive

- **`/ops` command** - Available on all 3 platforms:
  - Modes: admin, debug, feedback, all
  - `.claude/commands/ops.md`, `.copilot/custom-agents/ops.md`, `.cursor/rules/ops.md`

### Changed

- **`DOCUMENTATION-INDEX.md`** - Added Ops Tooling Generator, updated version to 1.9.0.2, agent count to 46
- **`docs/AGENTS.md`** - Added Ops Tooling Generator to agent list, updated count to 46
- **`README.md`** - Updated agent count references (45 -> 46)
- **`tests/run-tests.sh`** - Added 5 ops-tooling-generator test functions

---

## [1.9.0.1] - 2026-02-07

### Added

#### Project Educator Agent
End-user learning material generation for completed projects.

- **`agents/project-educator.md`** - Project Educator agent (45th agent):
  - Quick-start guides ("Get started in 5 minutes")
  - Comprehensive user guides
  - Project-specific glossary generation
  - User journey maps with Mermaid diagrams
  - Step-by-step tutorials with difficulty levels
  - FAQ/troubleshooting generation
  - Multi-level concept explainers (beginner, intermediate, advanced)
  - Output directory: `docs/guides/`
  - Runs after or alongside documentation-codifier at project end

- **`/educate` command** - Available on all 3 platforms:
  - Modes: quick-start, guide, glossary, journey, tutorial, faq, concepts, all
  - `.claude/commands/educate.md`, `.copilot/custom-agents/educate.md`, `.cursor/rules/educate.md`

### Changed

- **`DOCUMENTATION-INDEX.md`** - Added Project Educator, updated version to 1.9.0.1, agent count to 45
- **`docs/AGENTS.md`** - Added Project Educator to agent list, updated count to 45
- **`README.md`** - Updated agent count references (44 -> 45)
- **`tests/run-tests.sh`** - Added 5 project-educator test functions

---

## [1.9.0.0] - 2026-02-07

### Added

#### Phase 4: Advanced Intelligence
Semantic knowledge search, agent learning profiles, compliance presets, and monorepo support. This is the fourth and final phase of the Framework Evolution PRD.

- **`scripts/semantic-search.sh`** - TF-IDF Knowledge Search (FR-030):
  - Natural language query over all JSONL knowledge files
  - Keyword-weighted ranking: exact phrase (+100), word match (+10), type match (+20), weight bonus
  - Searches framework and project knowledge bases
  - Supports `--type` filter, `--limit`, and `--json` output
  - Not ML-based; uses TF-IDF inspired keyword matching

- **`scripts/monorepo.sh`** - Cross-Package Dependency Resolution (FR-036):
  - Detects packages across 6 ecosystems: Node.js, Python, Rust, Go, .NET
  - Commands: detect, deps, order, status
  - Extracts cross-package workspace dependencies
  - Topological sort for build order (Kahn's algorithm)
  - Supports up to 20 packages per monorepo
  - JSON output mode for tooling integration

- **`agents/agent-profile.md`** - Agent Learning Profile Protocol (FR-031, FR-032):
  - Style pattern detection: naming, formatting, imports, error handling, tests, comments, architecture
  - Pattern promotion pipeline: PROJECT_LOCAL (0.3) -> HARVESTED (0.5) -> CANDIDATE (0.7) -> PROMOTED (0.9)
  - Cross-agent learning: fixer patterns teach gate-keeper prevention, coder adapts proactively
  - Knowledge categories: error patterns, security fixes, test patterns, performance, style

- **`agents/compliance-profiles/`** - Compliance Presets (FR-033):
  - **HIPAA.md**: 22 rules across encryption (ENC), audit logging (AUD), access control (ACC), data handling (DAT), BAA requirements. PHI field identifiers and scan patterns.
  - **SOC2.md**: 28 rules across 5 Trust Service Criteria (Security, Availability, Processing Integrity, Confidentiality, Privacy) plus change management. Monitoring requirements.
  - **GDPR.md**: 27 rules across consent, data subject rights (DSR), data protection by design (DPD), security, breach notification, international transfers. Cookie compliance and PII field identifiers.
  - All presets are additive (never weaken existing gate-keeper rules)
  - Activated via `/go --compliance=hipaa|soc2|gdpr`

### Changed

- **`DOCUMENTATION-INDEX.md`** - Added Advanced Intelligence section, updated version to 1.9.0.0, agent count to 44
- **`tests/run-tests.sh`** - Added 13 advanced intelligence test functions

---

## [1.8.0.2] - 2026-02-07

### Added

#### Phase 3: Developer Experience & Observability
New slash commands and tooling for execution visibility, cost tracking, and framework diagnostics. This is the third phase of the Framework Evolution PRD.

- **`scripts/cost-tracker.sh`** - Token Usage Tracker (FR-022):
  - Record token usage per agent, story, and phase
  - Generate reports grouped by agent, story, phase, or all
  - Quick summary with totals and unique counts
  - Commands: record, report, summary, reset, status

- **`scripts/dashboard.sh`** - Live Execution Dashboard (FR-028):
  - Terminal UI with auto-refresh (default 2s)
  - Progress bar visualization with completion percentage
  - Shows swarm task status, active agents, scratchpad alerts
  - Displays file conflict warnings and cost summary
  - Reads state passively (never blocks agent execution)
  - Supports `--once` for single render and `--refresh=N` for custom interval

- **`.claude/commands/explain.md`** - `/explain` Slash Command (FR-023):
  - Explains last agent action in plain English
  - References story/PRD requirements
  - Shows file changes and next steps

- **`.claude/commands/undo.md`** - `/undo` Slash Command (FR-024):
  - Reverts last reversible agent action
  - Checks reversibility before proceeding
  - Requires confirmation (per CLI confirmation matrix)

- **`.claude/commands/cost.md`** - `/cost` Slash Command (FR-022):
  - Token usage report via cost-tracker.sh
  - Supports grouping by agent, story, phase

- **`.claude/commands/health.md`** - `/health` Slash Command (FR-025):
  - Framework self-diagnostic
  - Checks version, structure, agents, memory bank, swarm, security, PRDs

### Changed

- **`DOCUMENTATION-INDEX.md`** - Added Developer Experience section
- **`tests/run-tests.sh`** - Added 10 developer experience test functions

---

## [1.8.0.1] - 2026-02-07

### Added

#### Phase 2: Swarm Agent Coordination
Self-organizing agent coordination replaces top-down wave dispatch. Agents independently pull tasks from a shared queue, communicate via scratchpad, and detect file conflicts in real-time. This is the second phase of the Framework Evolution PRD.

- **`parallel/swarm-queue.sh`** - Shared Task Queue (FR-010, FR-015, FR-016, FR-017):
  - SwarmTask CRUD with full state machine enforcement (PRD Section 6.1)
  - States: QUEUED -> CLAIMED -> IN_PROGRESS -> COMPLETE/FAILED/BLOCKED
  - Invalid transition guards (COMPLETE is terminal, QUEUED cannot skip to IN_PROGRESS)
  - File-based locking via flock for concurrent access safety
  - Max concurrent agent limit (5, configurable)
  - Dependency checking before task claim
  - File conflict detection during claim
  - Retry with exponential backoff (max 3 retries)
  - Agent availability pool tracking
  - Commands: init, add, claim, start, complete, fail, block, unblock, list, status, pool, reset

- **`parallel/swarm-scratchpad.sh`** - Inter-agent Communication (FR-012):
  - Agents write notes about interface changes, decisions, warnings
  - Project-scoped (never crosses project boundaries per security req)
  - Priority levels: normal, high (for breaking changes)
  - Acknowledge mechanism for read tracking
  - Filter by target agent, task, or unread status
  - Commands: write, read, list, ack, clear, status

- **`parallel/conflict-detector.sh`** - File Conflict Detection (FR-014):
  - Register file locks per task before starting work
  - Real-time conflict detection when multiple agents touch same file
  - Resolution strategies: serialize (wait) or skip (omit file)
  - Confirmation required per CLI confirmation matrix
  - Commands: register, release, check, status, resolve, list

- **`agents/_swarm-coordinator.md`** - Swarm Coordination Protocol Agent:
  - Defines SwarmTask state machine and valid transitions
  - Documents dynamic handoffs (FR-011) between agents
  - Agent availability pool rules and configuration
  - Swarm vs wave mode decision criteria
  - Automatic fallback to wave mode on coordination failure (FR-016)
  - References all shell tools in parallel/

- **`.claude/commands/swarm.md`** - `/swarm` Slash Command:
  - Unified swarm management interface
  - Subcommands: status, queue, scratchpad, conflicts, pool, init, fallback
  - Integrates with swarm-queue.sh, swarm-scratchpad.sh, conflict-detector.sh

### Changed

- **`agents/_parallel-dispatch.md`** - Added swarm tool references to Shell Tool References section
- **`DOCUMENTATION-INDEX.md`** - Added Swarm Agent Coordination section, updated agent count to 43, updated parallel execution section
- **`tests/run-tests.sh`** - Added 10 swarm coordination test functions

---

## [1.8.0.0] - 2026-02-07

### Added

#### Phase 1: Bidirectional Knowledge Exchange
Projects now harvest learned knowledge back to the central framework, making every future installation smarter. This is the first phase of the Framework Evolution PRD.

- **`scripts/harvest.sh`** - Knowledge Harvest Engine (FR-001, FR-003, FR-004, FR-007):
  - Extracts learned knowledge from project memory_bank to central framework
  - Security sanitization: blocks secrets, API keys, tokens, PII from harvesting
  - Deduplication: detects exact-match duplicates, boosts weight on re-encounter
  - Scope detection: distinguishes project-specific vs universal knowledge
  - Promotion cycle: HARVESTED -> CANDIDATE (2+ projects) -> PROMOTED (3+ projects OR weight > 0.8)
  - Promoted entries auto-added to bootstrap.jsonl for future installations
  - Supports `--all` to harvest from all registered projects
  - Supports `--promote` to run standalone promotion cycle
  - Supports `--status` to show harvest statistics

- **`scripts/registry.sh`** - Project Registry Manager:
  - CRUD operations for project registry with rich metadata (JSONL)
  - Commands: register, unregister, list, dashboard, status, update-meta
  - Dashboard shows all projects with version, platform, health, knowledge count
  - Metadata tracking: last_harvested, health_status, total_go_runs, total_tokens_used
  - Confirmation prompts for destructive operations (per CLI confirmation matrix)

- **`agents/knowledge-curator.md`** - Knowledge Curator Agent:
  - Evaluates and promotes harvested knowledge entries
  - Implements KnowledgeEntry promotion state machine (PRD Section 6.2)
  - Quality gates: content quality, security, scope, weight thresholds
  - Knowledge categories: decision, error, fact, pattern, preference

- **Universal Knowledge Files** (central framework knowledge stores):
  - `memory_bank/knowledge/decisions-universal.jsonl` - Promoted decisions from all projects
  - `memory_bank/knowledge/errors-universal.jsonl` - Promoted error patterns
  - `memory_bank/knowledge/patterns-universal.jsonl` - Promoted code patterns

### Changed

- **`scripts/memory.sh`** - Added `harvest` and `sync` subcommands:
  - `memory.sh harvest` delegates to scripts/harvest.sh
  - `memory.sh sync` performs bidirectional knowledge exchange (push central -> project, pull project -> central)
  - Sync requires confirmation prompt (per CLI confirmation matrix)

- **`update.sh`** - Harvest integration (FR-006):
  - Now runs `harvest.sh` on each project during update cycle
  - Knowledge automatically flows back to central framework during updates

- **`install.sh`** - Registry integration:
  - Now registers projects in enhanced registry with metadata via registry.sh
  - Tracks platform, version, knowledge count at install time

### Tests Added

- 10 new test functions for Knowledge Exchange (knowledge test category):
  - harvest.sh existence, executability, --help support
  - registry.sh existence, executability, --help support
  - knowledge-curator.md agent validation (3 required sections)
  - Universal knowledge files existence (3 files)
  - memory.sh harvest/sync command presence
  - update.sh harvest integration verification
  - harvest.sh security sanitization (5 sensitive patterns)
  - harvest.sh deduplication logic presence
  - harvest.sh scope detection presence
  - harvest.sh promotion criteria verification (3+ projects OR weight > 0.8)

---

## [1.7.0.2] - 2026-02-07

### Added

#### Autonomous Execution System
Eliminates Claude Code permission prompts during Dream Team agent execution by pre-approving safe operations at the tool level, while keeping framework guardrails (Gate Keeper, Fixer, Evaluator) as the real safety net.

- **`.claude/settings.json`** - Shared permission profile with comprehensive allowlists:
  - All file operations (Read, Edit, Write, Glob, Grep) pre-approved
  - Development tools (npm, python, dotnet, pytest) pre-approved
  - Git operations (status, diff, commit, branch, merge, rebase) pre-approved
  - Framework scripts (./parallel/*, ./scripts/*) pre-approved
  - Docker read + compose operations pre-approved
  - GitHub CLI operations pre-approved
  - Task (subagent) dispatch pre-approved
  - Destructive operations always denied (rm -rf /, force push main, mkfs, etc.)

- **`.claude/hooks/validate-bash.sh`** - PreToolUse safety hook:
  - Emergency deny patterns for system-destructive commands
  - Network piped execution detection (curl | bash)
  - Protected branch force push detection
  - Environment exfiltration detection
  - Suspicious pattern warnings (sudo, eval, exec) logged to audit
  - Fail-open design: only explicitly dangerous patterns blocked

- **`docs/AUTONOMOUS-EXECUTION.md`** - Setup guide:
  - Two-layer safety architecture explained
  - Quick setup (automatic via install.sh or manual)
  - Pre-approved vs denied operations table
  - Permission customization guide
  - Framework execution mode combination matrix
  - Troubleshooting guide

### Changed

#### Installer Updates
- **`install.sh`** now deploys `.claude/settings.json` and `.claude/hooks/` during Claude platform installation
- Creates `.claude/hooks/` directory in installation structure
- Installation summary shows hooks and permission profile

---

## [1.7.0.1] - 2026-02-06

### Added

#### Populated Empty Directories

Three previously empty directory structures now contain practical, high-value content:

##### Project Templates (`templates/`)
- **`templates/README.md`** - Directory guide and usage instructions
- **`templates/prd-web-app.md`** - Full-stack web app PRD template (auth, DB, UI, API)
- **`templates/prd-api.md`** - REST API PRD template (endpoints, rate limiting, OpenAPI)
- **`templates/prd-cli.md`** - CLI tool PRD template (arg parsing, exit codes, output formats)
- **`templates/prd-library.md`** - Library/package PRD template (public API, semver, packaging)
- Templates use `{{VARIABLE}}` substitution, wired into `scripts/wizard.sh`

##### Parallel Execution Tooling (`parallel/`)
- **`parallel/README.md`** - Architecture overview and usage guide
- **`parallel/wave-planner.sh`** - Topological sort (Kahn's algorithm) for wave computation from story dependencies
- **`parallel/dispatch-state.sh`** - CRUD for `.claude/dispatch-state.json` (init, update, query, report)
- **`parallel/visualize.sh`** - ASCII DAG and Mermaid diagram generation from story dependencies
- All shell-based (consistent with framework tooling, no Node.js required)

##### Memory Bank Seed Files (`memory_bank/`)
- **`memory_bank/README.md`** - Architecture overview and schema documentation
- **`memory_bank/knowledge/README.md`** - JSONL schema documentation with field descriptions
- **`memory_bank/knowledge/bootstrap.jsonl`** - 15 pre-seeded framework facts, decisions, and error patterns
- **`memory_bank/relationships/knowledge-graph.json`** - Valid empty graph structure
- **`memory_bank/relationships/lineage.json`** - Valid empty lineage structure
- **`memory_bank/retrieval/query-cache.json`** - Valid empty cache structure
- **`memory_bank/retrieval/weights.json`** - Valid empty weights structure

### Changed

#### Wizard Template Integration
- **`scripts/wizard.sh`** now copies from `templates/prd-{type}.md` with variable substitution instead of generating inline PRD
- Fallback to inline generation for custom/unknown project types

#### Memory Manager Improvements
- **`scripts/memory.sh`** `init_memory_bank()` now writes valid JSON structures (not empty files)
- Copies `bootstrap.jsonl` to new projects on first init
- **`scripts/memory.ps1`** updated with same improvements for Windows

#### Parallel Dispatch Agent
- **`agents/_parallel-dispatch.md`** updated with shell tool references

#### Documentation Updates
- **`docs/PARALLEL-EXECUTION.md`** updated to reference shell scripts instead of JavaScript
- **`DOCUMENTATION-INDEX.md`** updated with templates/, parallel/, memory_bank/ entries
- **`tests/run-tests.sh`** expanded with tests for new directories and files

### Statistics
- **16 new files** created across 3 directories
- **8 existing files** updated
- **Version**: 1.7.0.0 -> 1.7.0.1 (iteration bump)

---

## [1.7.0.0] - 2026-02-05

### Added

#### Auto-Remediation & Autonomous Execution System

**Game-Changing Feature:** Self-healing development pipeline that fixes 90%+ of violations autonomously.

#### Version Management System

**NEW:** Comprehensive versioning system with semantic versioning format `MAJOR.FEATURE.DATABASE.ITERATION`

##### Version Components
- **MAJOR** (1) - Breaking changes, requires fresh install
- **FEATURE** (7) - New features, safe update
- **DATABASE** (0) - Schema changes, requires migration
- **ITERATION** (0) - Patches and bug fixes, safe update

##### New Tools
- **Version Check Script** (`scripts/version-check.sh`) - Detects installed version, compares with available, recommends action
- **Version Command** (`/version`) - Show version information and check for updates
- **Install/Update Integration** - Automatic version display and comparison during installation/updates

##### Update Decision Logic
- **UP_TO_DATE** - No action needed
- **PATCH_UPDATE** (X.X.X.0 → X.X.X.1) - Safe update, run `./update.sh`
- **FEATURE_UPDATE** (X.X.0.0 → X.Y.0.0) - Safe update, run `./update.sh`
- **DATABASE_MIGRATION** (X.X.0.0 → X.X.1.0) - Backup first, run `./update.sh --migrate`
- **MAJOR_UPDATE** (1.X.X.X → 2.X.X.X) - Backup first, run `./install.sh --force`

##### Version Display
- Version banner in install.sh and update.sh
- `/version` command for detailed version information
- `--version` flag in update.sh shows full version breakdown
- Version comparison when updating existing installations

##### New Agent: Fixer Orchestrator (`/fixer`)
- Auto-remediation intelligence that routes violations to appropriate specialists
- Smart retry loops (3 attempts with exponential backoff)
- Escalation only when necessary (critical decisions requiring user expertise)
- Parallel remediation (independent violations fixed simultaneously)
- Full audit trail (`logs/remediations.md`, `logs/escalations.md`)

##### Three Execution Modes
- **Supervised Mode** (default) - Stop at every violation, user approves all fixes
- **Semi-Autonomous Mode** (recommended) - Auto-fix routine violations, escalate critical decisions
- **Autonomous Mode** - Full autonomy, user checkpoint only at phase/project end

##### Auto-Fix Capabilities
**Routine Violations (No User Interruption):**
- Missing tests → Tester generates them
- Security headers missing → Security Specialist adds them
- Dead code detected → Refactor Agent removes it
- N+1 query patterns → Data Architect optimizes them
- Performance bottlenecks → Performance Optimizer fixes them
- Accessibility violations → Accessibility Specialist corrects them
- Missing documentation → Documentation Codifier generates them

**Critical Decisions (Escalated to User):**
- Architectural choices (multiple valid approaches with trade-offs)
- Business logic ambiguities not specified in PRD
- Security/compliance policy decisions
- Breaking API changes affecting external consumers
- Domain expertise required (tax rules, legal requirements)

##### Enhanced Gate Keeper
- Added **auto-fix mode** alongside traditional blocking mode
- Routes violations to Fixer Orchestrator for remediation
- Re-validates after fixes applied
- Maintains all existing quality standards while enabling automation

##### New Documentation
- **Escalation Criteria Matrix** (`docs/ESCALATION-CRITERIA.md`) - Complete guide on when to auto-fix vs. escalate
- **Remediation Logs** (`logs/remediations.md`) - Audit trail of all auto-fixes
- **Escalation Logs** (`logs/escalations.md`) - Record of all user decisions

##### Enhanced `/go` Command
New execution mode flags:
- `/go --mode=supervised` - Traditional blocking behavior
- `/go --mode=semi-auto` - Auto-fix routine, escalate critical (recommended)
- `/go --mode=autonomous` - Full autonomy, minimal interruptions

##### Violation → Agent Routing Table
Complete mapping of 20+ violation types to appropriate specialist agents:
- Missing tests → Tester
- Security issues → Security Specialist
- Dead code → Refactor Agent
- Database issues → Data Architect
- Performance → Performance Optimizer
- Accessibility → Accessibility Specialist
- i18n gaps → i18n Specialist
- Missing observability → SRE Specialist
- Architectural ambiguity → **ESCALATE**
- Business logic unclear → **ESCALATE**

### Changed

#### Gate Keeper Enhancements
- Added operating modes: `--mode=block`, `--mode=auto-fix`, `--mode=report`
- Generates structured violation reports in JSON format for Fixer Orchestrator
- Maintains existing validation rigor while enabling auto-remediation

#### Workflow Improvements
- **90%+ reduction** in user interruptions for routine quality issues
- **Faster execution** - No waiting for manual test/doc/security fixes
- **Consistent quality** - Standards automatically enforced
- **User time focused** on strategic decisions, not routine quality tasks

### Dream Team Audit (Self-Audit - 2026-02-06)

Framework audited itself using 6 specialist agents (81 findings). All remediated:

#### P0 - Critical Security Fixes
- **Created `.gitignore`** - Framework was missing gitignore entirely; added BPSBS-compliant exclusions
- **Fixed `rm -rf` safety** in `install.sh` - Added path validation, root/home protection
- **Fixed injection vulnerabilities** in `scripts/memory.sh` - jq `--arg`, `grep -F --`, type whitelist
- **Added `set -o pipefail`** to all 11 shell scripts
- **Fixed symlink race** in `scripts/test-version-system.sh` - Uses `mktemp -d` now

#### P1 - This Release Fixes
- **Updated version references** from 1.6.0 → 1.7.0.0 across all documentation
- **Fixed agent counts** 38/39 → 41 across README, AGENTS.md, QUICK-REFERENCE, DOCUMENTATION-INDEX, version files
- **Deleted temp files** (.goutputstream-SUL1I3, install.sh.backup)
- **Renamed .mdf → .md** in `.cursor/rules/` (fixer, version)

#### P2 - User-Directed Improvements
- **Ported security-scanner** to Claude Code + Cursor (new agent, counts 40→41)
- **Merged reptilian-gate-keeper.md** into gate-keeper.md (removed duplicate)
- **Moved ANTI_PATTERNS** to `docs/` (updated all installer paths in .sh and .ps1)
- **Moved scripts** install-unified.sh/ps1, convert-to-copilot.sh → `scripts/`
- **Moved docs** CLAUDE-SUMMARY, V1.1.0-RELEASE-NOTES, AGENTS-ENHANCEMENT-COMPLETE → `docs/`
- **Archived 9 historical docs** to `docs/archive/`
- **Wired 11 shared modules** into 33 platform files (agents/ persona references)
- **Documented 5 Copilot-only agents** in docs/AGENTS.md (GitHub-specific)

### Statistics
- **41 agents** (was 38) - Added Fixer Orchestrator, Version, Security Scanner agents
- **46 Copilot agents** (41 shared + 5 GitHub-specific)
- **3 execution modes** - Supervised, Semi-Autonomous, Autonomous
- **20+ auto-fixable** violation types
- **Target: >90%** auto-fix rate, <10% escalation rate
- **33 platform files** wired to shared agent modules

---

## [1.6.0] - 2026-02-03

### Added

#### The Dream Team - 8 New Specialist Agents

Completing the full software development lifecycle:

##### Security Specialist (`/security`)
- STRIDE threat modeling for new features
- OWASP Top 10 audit checklist
- Penetration testing mindset
- Attack vector enumeration
- Security-focused code review
- Incident response guidance
- System hardening recommendations

##### Data Architect (`/data-architect`)
- Schema design with ERD generation
- Query optimization with execution plan analysis
- Normalization analysis and recommendations
- Safe migration strategy (non-breaking changes)
- Index decision framework
- Database health audits
- Anti-pattern detection (EAV, God tables, N+1)

##### Release Manager (`/release`)
- Semantic versioning enforcement
- Keep a Changelog format
- User-facing release notes generation
- Pre-release and post-release checklists
- Rollback plan templates
- Hotfix process guidance
- Error budget integration

##### i18n Specialist (`/i18n`)
- Internationalization infrastructure setup
- Hardcoded string detection and extraction
- ICU message format for plurals/gender
- RTL (right-to-left) support with logical CSS
- Locale-specific formatting (numbers, dates, currencies)
- Translation quality review
- Multi-country context (Luxembourg, Belgium, France)

##### Tech Lead (`/tech-lead`)
- Technical decision arbitration (RFC process)
- Cross-team coordination
- Technical mentorship
- Project planning with milestones
- Technical debt management
- Stakeholder communication
- Technical health metrics

##### SRE Specialist (`/sre`)
- Incident response framework (SEV1-4)
- SLO/SLI/Error budget definition
- Four Golden Signals monitoring
- Blameless postmortem templates
- Operational runbook creation
- Chaos engineering experiments
- Alert design principles

##### UX/UI Specialist (`/ux-ui`)
- UI audit protocol (visual, responsive, a11y, interactions)
- Design system enforcement (tokens, patterns)
- Framework migration (Bootstrap→Tailwind, etc.)
- Component rewrite protocol
- Anti-pattern detection (magic numbers, !important chains)
- Dark mode requirements
- Responsive breakpoint strategy

##### Senior Software Engineer (`/senior-engineer`)
- Assumption surfacing (explicit ASSUMPTIONS blocks)
- Confusion management (stop and clarify)
- Push-back when warranted (not a yes-machine)
- Simplicity enforcement (1000 lines when 100 suffice = fail)
- Scope discipline (surgical precision)
- Dead code hygiene (ask before removing)
- Inline planning for multi-step tasks

#### Documentation
- **[docs/AGENTS.md](docs/AGENTS.md)** - Complete agent team reference
- Updated **[docs/QUICK-REFERENCE.md](docs/QUICK-REFERENCE.md)** - All agent modes and commands
- Updated **[DOCUMENTATION-INDEX.md](DOCUMENTATION-INDEX.md)** - New agent listings

#### Platform Support
- All 8 new agents available on Claude Code, GitHub Copilot CLI, and Cursor
- 38 shared agent modules in `agents/` directory
- Consistent behavior across all three platforms

### Changed

#### Statistics
- Claude Code Skills: 30 → 38 (+8)
- Copilot CLI Agents: 36 → 44 (+8)
- Cursor Rules: 30 → 38 (+8)
- Shared Modules: 28 → 36 (+8)
- Total: 96 → 120 agents/skills/rules

---

## [1.5.0] - 2026-01-25

### Added

#### Phase 4: Observability & Tracing System

##### Observability Infrastructure
- **Observability Manager** (`observability/observability-manager.js`):
  - Unified interface for tracing, metrics, and auditing
  - Singleton pattern for global access
  - Automatic metrics collection and saving

- **Trace Logger** (`observability/trace-logger.js`):
  - Structured logging to JSONL files
  - Session-based trace organization
  - Span-based distributed tracing
  - Automatic trace ID and span ID generation
  - Decision logging support

- **Metrics Collector** (`observability/metrics-collector.js`):
  - Token usage tracking (total, by agent, by action)
  - Latency measurement (average, by agent, by action)
  - Error rate calculation
  - Action counting and status tracking
  - Session tracking
  - Metrics persistence to JSON file

- **Audit Logger** (`observability/audit-logger.js`):
  - Story completion tracking
  - Security event logging
  - Decision logging
  - File operation logging
  - Agent action logging
  - Audit trail search functionality

##### Trace Viewer
- **Trace Viewer Server** (`observability/trace-viewer-server.js`):
  - Express.js server for trace visualization
  - RESTful API endpoints for traces, metrics, and audit trails
  - Session listing and trace retrieval

- **Trace Viewer Client** (`logs/dashboards/trace-viewer.html`):
  - Web-based trace visualization interface
  - Timeline view of agent activities
  - Metrics summary dashboard
  - Session selection and filtering
  - Detailed trace entry inspection

##### Start Scripts
- `scripts/start-trace-viewer.sh` (Linux/Mac)
- `scripts/start-trace-viewer.ps1` (Windows)

##### Documentation
- `docs/OBSERVABILITY-TRACING.md` - Complete implementation guide

### Enhanced
- **Log Directory Structure**: Organized logs into traces/, audit/, and dashboards/ subdirectories
- **Package Management**: Added `observability/package.json` with uuid dependency

---

## [1.4.1] - 2026-01-25

### Added

#### Full Node.js Implementation for Phase 3 Features

##### MCP Servers - Complete Implementation
- **Filesystem Server** (`mcp-servers/filesystem/server.js`):
  - Full Node.js implementation with all 6 tools (read_file, write_file, list_directory, create_directory, delete_file, search_files)
  - Permission model with confirmation requirements
  - File size limits and safety checks
  - Package.json with MCP SDK dependency

- **Database Server** (`mcp-servers/database/server.js`):
  - Full Node.js implementation with PostgreSQL support
  - Schema inspection (tables, columns, constraints)
  - Read-only query execution (SELECT only)
  - Migration file generation and management
  - Migration status checking
  - Package.json with pg dependency

- **Testing Server** (`mcp-servers/testing/server.js`):
  - Full Node.js implementation with test framework detection
  - Support for Jest, Mocha, Vitest, pytest
  - Test execution, coverage, and listing
  - Watch mode support
  - Package.json with MCP SDK dependency

- **Security Server** (`mcp-servers/security/server.js`):
  - Full Node.js implementation for security scanning
  - Dependency vulnerability scanning (npm, yarn, pip, maven, gradle)
  - Code scanning for hardcoded secrets
  - Permission auditing
  - Comprehensive security report generation
  - Package.json with MCP SDK dependency

##### Dashboard - Complete Implementation
- **Dashboard Server** (`dashboard/server/index.js`):
  - Full Express.js server implementation
  - RESTful API endpoints for PRDs, stories, agents, and metrics
  - In-memory data storage (JSON files)
  - Health check endpoint
  - Package.json with Express dependency

- **Dashboard Client** (`dashboard/client/`):
  - Complete HTML/CSS/JS frontend
  - Tabbed interface (Overview, PRDs, Stories, Agents, Metrics)
  - Real-time data loading and rendering
  - Summary cards with statistics
  - List views for PRDs, stories, and agent activity
  - Filtering and search capabilities
  - Modern dark theme UI

### Enhanced
- **MCP Server READMEs**: Updated with installation and usage instructions
- **Dashboard Start Scripts**: Ready to use with `npm start`

---

## [1.4.0] - 2026-01-25

### Added

#### Phase 3: Advanced Features

##### Persistent Memory System
- **Memory Bank Structure**: `memory_bank/` directory with knowledge, relationships, and retrieval subdirectories
- **CLI Tools**: `scripts/memory.sh` (Linux/Mac) and `scripts/memory.ps1` (Windows)
- **Commands**: `/remember`, `/recall`, `/correct` for knowledge management
- **Storage Format**: JSONL-based append-only storage with weight management
- **Weight Algorithm**: Automatic weight calculation based on recency, validation, usage, and reality anchors
- **Documentation**: `docs/PERSISTENT-MEMORY-IMPLEMENTATION.md` with full technical details
- **Integration**: Updated memory agents across all platforms (Claude Code, Copilot CLI, Cursor)

##### MCP (Model Context Protocol) Integration
- **MCP Server Framework**: `mcp-servers/` directory structure
- **Four MCP Servers**:
  - `mcp-skillfoundry-filesystem` - Safe file operations with permission model
  - `mcp-skillfoundry-database` - Database schema inspection and migration management
  - `mcp-skillfoundry-testing` - Test runner integration
  - `mcp-skillfoundry-security` - Security scanning and vulnerability detection
- **Documentation**: `docs/MCP-INTEGRATION.md` with server specifications and usage
- **Server READMEs**: Individual README files for each MCP server

##### Visual Dashboard
- **Dashboard Structure**: `dashboard/` directory with server and client components
- **Features**: PRD management, story tracking, agent activity log, metrics dashboard, project health
- **Tech Stack**: Node.js + Express backend, vanilla HTML/CSS/JS frontend
- **Start Scripts**: `scripts/start-dashboard.sh` and `scripts/start-dashboard.ps1`
- **API Endpoints**: RESTful API for PRDs, stories, agents, and metrics
- **Documentation**: `docs/VISUAL-DASHBOARD.md` with architecture and implementation details

##### Parallel Execution
- **DAG-Based Execution**: `parallel/` directory with DAG builder and executor
- **Dependency Resolution**: Automatic dependency analysis and batch creation
- **Parallel Batches**: Execute independent tasks concurrently
- **Error Handling**: Circular dependency detection, task failure handling, resource conflict resolution
- **Documentation**: `docs/PARALLEL-EXECUTION.md` with usage examples and architecture

### Enhanced
- **Memory Agents**: Updated to reference CLI tools and implementation documentation
- **Documentation Index**: Added entries for all Phase 3 features

---

## [1.3.5] - 2026-01-25

### Added

#### Phase 2 Polish - Reflection Protocol Expansion
- **Reflection Protocol** added to 8 specialized agents:
  - Refactor Agent
  - Performance Optimizer
  - Dependency Manager
  - Code Review Agent
  - Migration Specialist
  - API Design Specialist
  - DevOps Specialist
  - Accessibility Specialist
- All agents now include pre/post reflection, self-scoring, and contradiction detection

#### Enhanced Integration Tests
- **Wizard Workflow Test**: Validates quick start wizard end-to-end
- **Update Workflow Test**: Validates update preserves custom files
- **Multi-Platform Test**: Validates multiple platforms can coexist
- Total integration tests: 19 → 22+ tests

#### Windows PowerShell Error Handling
- **Comprehensive error handling** in `install.ps1` and `update.ps1`
- Automatic rollback on failed installations
- Restore from backup on failed updates
- Enhanced error messages with actionable solutions
- Diagnostic mode (`--Debug` flag)
- Error codes (0-8) matching bash scripts

#### Enhanced Diagnostic Collection
- **Additional system information**: Computer name, platform selection, debug mode
- **Better permission details**: AccessToString for PowerShell, detailed ls output for bash
- **Update status tracking**: Projects processed, failures
- **Recent operations log**: Last 20 operations (bash)

### Enhanced
- **Install Scripts**: Better error handling, rollback, diagnostics
- **Update Scripts**: Better error handling, diagnostics, backup restore
- **Test Suite**: More comprehensive integration test coverage

### Changed
- Error messages now include actionable solutions across all platforms
- Diagnostic information more comprehensive
- All specialized agents now engage in structured self-reflection

---

## [1.3.4] - 2026-01-25

### Added

#### Phase 2: Core Enhancements

- **Agent Reflection Protocol** (`agents/_reflection-protocol.md`)
  - Pre-action reflection (risks, assumptions, patterns, simplicity)
  - Post-action reflection (goal achievement, edge cases, quality, learning)
  - Contradiction detection protocol
  - Self-scoring system (0-10 on 4 dimensions: Completeness, Quality, Security, Confidence)
  - Reflection output format
  - Integrated into Coder, Tester, and Architect agents

- **Enhanced Test Suite**
  - **Agent Protocol Tests** (2 tests): Reflection protocol validation
  - **Integration Tests** (2 tests): Install/update workflows, all platforms
  - **Performance Tests** (2 tests): Install speed, file count validation
  - **Security Tests** (2 tests): Security pattern detection, agent security references
  - **Cross-Platform Tests** (2 tests): Script existence, unified installer validation
  - Total: 19+ tests across 8 categories (up from 9 tests)

- **Error Handling & Recovery Protocol** (`agents/_error-handling-protocol.md`)
  - Actionable error messages (what, why, where, how)
  - Error categories (FATAL, ERROR, WARNING, INFO)
  - Automatic recovery mechanisms
  - Rollback on failure
  - Diagnostic mode (`--debug` flag)
  - Error codes (0-8)
  - Retry with exponential backoff
  - Graceful degradation

### Enhanced

- **Install Script** (`install.sh`)
  - Added comprehensive error handling
  - Automatic rollback on failure
  - Diagnostic information collection
  - Debug mode (`--debug` flag)
  - Enhanced error messages with solutions
  - Better error codes

- **Test Suite** (`tests/run-tests.sh`)
  - Expanded from 9 to 19+ tests
  - Added 5 new test categories
  - Improved test documentation

### Changed
- Error messages now include actionable solutions
- Test suite provides comprehensive coverage
- Agents now engage in structured self-reflection

---

## [1.3.3] - 2026-01-25

### Added

#### Quick Wins - Enhanced Onboarding
- **One-Click Installation Scripts** (`install-unified.sh`, `install-unified.ps1`)
  - Auto-detects platform (Claude Code, Copilot CLI, Cursor)
  - Auto-detects OS (Linux, Mac, Windows)
  - Interactive mode with smart defaults
  - Single command installation: `curl ... | bash` or `iwr ... | iex`

- **Quick Start Wizard** (`scripts/wizard.sh`, `scripts/wizard.ps1`)
  - Interactive project setup wizard
  - Platform selection
  - Project type selection (Web App, API, CLI, Library)
  - Tech stack selection
  - Auto-generates starter PRD template

- **Enhanced Documentation with Examples**
  - `docs/EXAMPLES/example-web-app.md` - Complete web app walkthrough
  - `docs/EXAMPLES/example-api.md` - REST API implementation guide
  - Real-world examples with step-by-step instructions
  - Common issues and solutions

- **Strategic Improvement Plan**
  - `docs/IMPROVEMENT-PLAN.md` - Comprehensive roadmap
  - `docs/MARKET-COMPARISON.md` - Competitive analysis
  - Prioritized enhancement list

### Changed
- Updated installation documentation to include one-click installer
- Enhanced README with quick start wizard instructions

### Fixed
- Installation scripts now handle edge cases better
- Improved error messages for better user experience

---

## [1.3.2] - 2026-01-25

### Added

#### New Specialized Agents (8 Agents)
- **Refactor Agent** (`refactor.md`) - Code quality improvement with TDD safety net
  - Common code smells identification
  - Refactoring techniques (Extract Method, Extract Class, Rename, etc.)
  - Safety-first approach with test verification
  - Integration with Tester agent

- **Performance Optimizer** (`performance.md`) - Performance bottleneck identification
  - Measurement-first approach (never optimize without metrics)
  - Performance profiling and analysis
  - Common performance issues (N+1 queries, missing indexes, etc.)
  - Performance budgets (frontend and backend)

- **Dependency Manager** (`dependency.md`) - Secure dependency management
  - Vulnerability scanning and assessment
  - Update strategy (patch/minor/major)
  - Dependency optimization (remove unused, consolidate)
  - Package hallucination detection (AI-specific vulnerability)

- **Code Review Agent** (`review.md`) - Merciless code review
  - High signal-to-noise ratio (only real issues)
  - Security review (Top 7 vulnerabilities)
  - Test coverage review
  - Code quality and architecture review

- **Migration Specialist** (`migration.md`) - Database schema changes
  - Safety-first migrations (never lose data)
  - Reversibility (every migration has rollback)
  - Migration types and risk assessment
  - Data migration patterns

- **API Design Specialist** (`api-design.md`) - API interface design
  - RESTful design principles
  - HTTP status codes and URL design
  - Request/response design
  - API versioning strategies
  - OpenAPI/Swagger documentation

- **DevOps Specialist** (`devops.md`) - CI/CD and infrastructure
  - CI/CD pipeline design
  - Infrastructure as code
  - Deployment strategies (Blue-Green, Canary, etc.)
  - Monitoring and observability

- **Accessibility Specialist** (`accessibility.md`) - WCAG compliance
  - WCAG 2.1 Level AA compliance
  - Accessibility audit and testing
  - Common accessibility issues
  - Keyboard navigation and screen reader support

#### Platform Expansion
- **Claude Code**: 22 → 30 skills (+8)
- **Copilot CLI**: 28 → 36 agents (+8)
- **Cursor**: 22 → 30 rules (+8)
- **Total**: 72 → 96 agents/skills/rules (+24)

### Enhanced

#### Existing Agents Enhanced
- **Coder Agent**: Added references to refactor and performance agents
- **Tester Agent**: Added references to performance testing
- **Architect Agent**: Added Performance, Accessibility, and DevOps personas
- **Go Agent**: Enhanced workflow with optional specialized agents (Refactor → Performance → Review → Migration)

### Changed

- All new agents available on all platforms (Claude Code, Copilot CLI, Cursor)
- Enhanced agent integration across workflow
- Improved documentation and examples

---

## [1.3.1] - 2026-01-20

### Added

#### TDD Enforcement Protocol
Adopted from SkillsMP Superpowers collection.

- **`agents/_tdd-protocol.md`** - Complete TDD enforcement specification
  - RED-GREEN-REFACTOR cycle enforcement
  - Test-first requirement before implementation
  - Enforcement levels: STRICT (block), WARN (log), OFF (track)
- **TDD state tracking** - `.claude/tdd-state.json` for cycle metrics
- **TDD anti-patterns** - Detection and blocking of test-after development
- **Framework patterns** - Jest/Vitest, pytest, xUnit examples
- **Integration with /coder** - Automatic TDD mode activation

#### Parallel Agent Dispatching
Adopted from SkillsMP Superpowers collection.

- **`agents/_parallel-dispatch.md`** - Concurrent subagent execution
  - Wave execution mode (groups of independent tasks)
  - Eager execution mode (start as dependencies complete)
  - Conservative mode (limit concurrent agents)
- **Dispatch state tracking** - `.claude/dispatch-state.json`
- **Conflict detection** - File overlap and resource conflicts
- **Speedup calculation** - Parallel vs sequential comparison
- **Integration with /go** - `--parallel` flag for story execution
- **Integration with /delegate** - Enhanced orchestration with waves

#### Git Worktree Isolation
Based on git worktree best practices.

- **`agents/_git-worktrees.md`** - Isolated branch development
  - PRD-level worktree creation
  - Safe experimentation without affecting main
  - Easy rollback (delete worktree folder)
  - Parallel PRD development support
- **Worktree state tracking** - `.claude/worktree-state.json`
- **Post-create hooks** - Automatic environment setup
- **Conflict resolution** - Rebase/merge strategies
- **Integration with /go** - `--worktree` flag for isolated execution

#### Systematic Debugging Protocol
Adopted from SkillsMP Superpowers collection.

- **`agents/_systematic-debugging.md`** - Four-phase debugging
  - Phase 1: OBSERVE - Gather facts without assumptions
  - Phase 2: HYPOTHESIZE - Form testable explanations
  - Phase 3: TEST - Validate/invalidate hypotheses
  - Phase 4: VERIFY - Confirm fix, add regression tests
- **Five Whys technique** - Trace to root cause
- **Debug session tracking** - `.claude/debug-state.json`
- **Defense in depth** - Add guards after every fix
- **Integration with /debugger** - Enhanced debugging workflow

### Changed

- `/coder` skill updated with mandatory TDD enforcement
- `/debugger` skill updated with four-phase protocol
- `/delegate` skill updated with parallel dispatch capabilities
- `/go` skill updated with worktree and parallel flags
- Framework version bumped to 1.3.1

### New /go Flags

```
/go --parallel           Enable parallel story execution
/go --parallel=EAGER     Use eager execution mode
/go --parallel=2         Limit concurrent agents
/go --no-parallel        Force sequential execution
/go --worktree           Execute PRD in isolated worktree
/go --no-worktree        Force inline execution
/go --tdd                Enforce TDD mode (STRICT)
/go --tdd=WARN           TDD in warning mode
```

---

## [1.3.0] - 2026-01-20

### Added

#### Execution State Machine
Based on crash recovery and rollback requirements.

- **`agents/_state-machine.md`** - Complete state machine specification
  - States: IDLE → INITIALIZING → LOADING_PRD → VALIDATING → GENERATING_STORIES → EXECUTING_STORY → VALIDATING_LAYERS → SECURITY_AUDIT → DOCUMENTING → COMPLETED
  - Error state with recovery options
  - Rolling back state for undo operations
- **`.claude/state.json`** - Persistent execution state
- **State transitions** - Deterministic flow with action triggers
- **Recovery protocol** - Automatic detection of interrupted executions

#### Rollback Protocol
- **`agents/_rollback-protocol.md`** - Complete rollback specification
- **Automatic backups** - Files backed up before modification to `.claude/backups/`
- **Rollback manifest** - Tracks all changes for reversal
- **Database rollback** - Migration down scripts executed
- **Package rollback** - Installed packages tracked and removed
- **Partial rollback** - Rollback to specific story point with `--rollback STORY-XXX`

#### Story Dependency Graph
- **`agents/_story-dependency-graph.md`** - Dependency management specification
- **Dependency types** - Hard (blocks) and soft (prefers) dependencies
- **INDEX.md template** - Automatic generation of story index with Mermaid graph
- **Parallel execution** - Independent stories can run simultaneously
- **Critical path calculation** - Identifies bottleneck sequence
- **Cycle detection** - Fatal error on circular dependencies

#### Inter-PRD Dependencies
- **`agents/_prd-dependencies.md`** - PRD coordination specification
- **Dependency metadata** - `requires`, `recommends`, `blocks`, `shared_with` fields
- **PRD validation** - Checks dependencies before execution
- **Execution waves** - PRDs grouped by dependency level
- **Impact analysis** - Shows downstream effects of PRD changes

#### Metrics & Analytics System
- **`agents/_metrics-system.md`** - Complete metrics specification
- **`.claude/commands/metrics.md`** - New `/metrics` skill
  - `/metrics` - Dashboard view
  - `/metrics agents` - Agent performance breakdown
  - `/metrics stories` - Story completion analysis
  - `/metrics errors` - Error analysis and patterns
  - `/metrics trends` - Trend analysis over time
  - `/metrics export [format]` - Export to JSON/CSV/Markdown
- **Automatic collection** - Metrics gathered during `/go` execution
- **Agent tracking** - Success rates, token usage, response times
- **Story tracking** - By complexity, by layer, completion rates
- **Error categorization** - By type, by agent, recovery rates
- **Trend analysis** - Weekly/monthly comparisons

#### Agent Communication Protocol
- **`agents/_agent-protocol.md`** - Inter-agent messaging standard
- **Request/Response format** - Structured JSON messages
- **Status codes** - SUCCESS, PARTIAL, FAILED, BLOCKED
- **Handoff protocol** - Clean agent-to-agent transitions
- **Error propagation** - Standardized error codes and handling
- **Chain execution** - Sequential, parallel, and conditional flows
- **Traceability** - Correlation IDs and audit trail

#### Test Execution Integration
- **`agents/_test-execution.md`** - Cross-framework test running
- **Auto-detection** - Detects Jest, Vitest, pytest, dotnet test, cargo test, go test
- **Unified result format** - Normalized test output across frameworks
- **Failure categorization** - assertion, timeout, type_error, network, database, etc.
- **Coverage analysis** - Line, branch, function coverage with thresholds
- **Integration with gate-keeper** - Test evidence for capability gates

#### Gate Verification Commands
- **`agents/_gate-verification.md`** - Automated capability checks
- **Verification commands**:
  - `/verify tests` - Run tests and verify all pass
  - `/verify build` - Verify clean build with no warnings
  - `/verify coverage [--threshold X]` - Check coverage meets threshold
  - `/verify lint` - Verify code passes all linting
  - `/verify security` - Run security scans
  - `/verify api` - Check API health and smoke tests
  - `/verify migration` - Test database migrations and rollback
  - `/verify docs` - Check documentation completeness
  - `/verify patterns` - Scan for banned patterns
- **Composite gates** - `/verify production` runs all checks
- **Custom gates** - Define in `.claude/gates.json`

#### PRD Schema Validation
- **`genesis/.schema.json`** - JSON Schema for PRD validation
- **Required fields** - prd_id, title, status, problem_statement, user_stories, security_requirements, out_of_scope
- **Dependency metadata** - requires, recommends, blocks, shared_with
- **Validation rules** - Critical checks that block implementation

#### Enhanced /go Command
- **`--resume`** - Resume interrupted execution from saved state
- **`--rollback`** - Rollback all changes from last execution
- **`--rollback STORY-X`** - Rollback to before specific story
- **`--skip STORY-XXX`** - Skip specific story during execution
- **`--from STORY-XXX`** - Start from specific story
- **`--state`** - Show raw state file
- **`--clean`** - Clear state file and start fresh
- **`--deps`** - Show PRD dependency graph
- **`--metrics`** - Show execution metrics dashboard

#### Update Script Enhancements
- **`--sync PATH`** - Validate/regenerate CLAUDE-SUMMARY.md
- **Summary sync validation** - Checks CLAUDE.md and CLAUDE-SUMMARY.md are aligned
- **PRD schema installation** - Auto-copies genesis/.schema.json

### Changed
- Framework version bumped to 1.3.0
- PRD template updated with dependency metadata section
- `/go` skill updated with state machine, rollback, and metrics integration
- `update.sh` enhanced with sync validation and schema copying

### Technical Details
- State machine provides deterministic execution flow
- Rollback uses manifest-based file tracking
- Dependency graphs use topological sort for ordering
- Metrics stored in JSON for easy export and analysis
- All new shared modules follow `_` prefix convention

---

## [1.2.0] - 2026-01-18

### Added

#### Context Engineering
Based on [Recursive Language Models (arXiv:2512.24601)](https://arxiv.org/abs/2512.24601) and [Anthropic's Context Engineering Guide](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents).

- **CLAUDE-SUMMARY.md** - Condensed standards (~2K tokens) for active context loading
- **`/context` skill** - New context management command
  - `/context` - Show status and budget
  - `/context compact` - Force context compaction
  - `/context budget` - Detailed token breakdown
  - `/context load <level>` - Load specific context level
  - `/context clear` - Clear non-essential context
  - `/context scratchpad` - View/update session tracking
- **Hierarchical Context Loading** - Level 1/2/3 strategy for token efficiency
- **Token Budget Thresholds** - GREEN (<50K), YELLOW (50-100K), RED (>100K)
- **Auto-compaction** - Triggers at 100K tokens or every 5 stories

#### Recursive Task Decomposition
- **`agents/_recursive-decomposition.md`** - Shared protocol for task breakdown
- **Decision function** - When to decompose (complexity, budget, parallelization)
- **Isolated context execution** - Each subtask gets minimal, focused context
- **Maximum recursion depth** - 3 levels enforced
- **Result aggregation** - Combine subtask outcomes with conflict detection

#### Shared Agent Modules
- **`agents/_context-discipline.md`** - Token-aware behavior protocol for all agents
- **`agents/_subagent-response-format.md`** - Standardized <500 token response format
- **Scratchpad pattern** - Persistent notes across turns for all agents

#### Enhanced /go Command
- **Phase 0: Context Preparation** - Mandatory context budget check
- **Context-aware story execution** - Budget check before each story
- **Sub-agent delegation rules** - Enforces response format
- **Story complexity estimation** - Simple/Medium/Complex classification
- **Emergency compaction protocol** - Handles approaching context limits
- **Session summary format** - Structured end-of-session reporting

### Changed
- All 13 agent personas updated with Context Discipline section
- Agent Orchestrator enhanced with recursive decomposition workflow
- Project Orchestrator enhanced with sub-phase isolation

### Technical Details
- Estimated token counts using ~4 chars per token heuristic
- Level 1 context: ~5-10K tokens (essential only)
- Level 2 context: ~20-40K tokens (working set)
- Level 3 context: ~50-80K tokens (extended, reference only)

---

## [1.1.0] - 2026-01-18

### Added

#### Security
- `.gitignore Security (MANDATORY)` - Comprehensive .gitignore template with all sensitive patterns
- Pre-commit hook template for secret detection
- Emergency recovery steps for accidentally committed secrets
- Sensitive data verification checklist

#### LoggerService
- Full LoggerService implementation pattern with sanitization
- ESLint `no-console` rule enforcement
- Verification commands to confirm all console.* replaced
- Sign-off template for LoggerService compliance

#### Production Readiness
- **Database Migration Strategy** - Migration workflow, naming conventions, rollback testing
- **Observability/APM** - Required stack, RED metrics, log schema, alert thresholds
- **Incident Response Protocol** - P0-P4 severity levels, runbooks, postmortem template
- **Graceful Shutdown** - SIGTERM handling, connection draining, PM2 config
- **API Versioning Strategy** - URL path versioning, deprecation headers, changelog requirements
- **Concurrency/Locking** - Optimistic locking pattern, deadlock prevention
- **Error Resilience Patterns** - Circuit breaker, exponential backoff, bulkhead pattern
- **Dependency Management** - Security scanning, CVE response times, license compliance
- **Feature Flags** - Flag types, lifecycle management, cleanup requirements
- **Caching Strategy** - Cache layers, TTL guidelines, invalidation patterns
- **Performance Budgets** - Core Web Vitals targets, API latency budgets
- **Soft Delete/Retention** - Data retention policies, GDPR compliance
- **Load Testing** - k6/Artillery tools, test scenarios, capacity planning

#### Framework Management
- `update.sh` - Push latest framework version to existing projects
- Project registry for tracking installations
- Version markers in projects
- Diff preview before updates
- Backup system for updates

### Changed
- Enhanced Zero Tolerance banned patterns table with 6 additional patterns
- Philosophy section updated with "ONLY REAL LOGIC" and "Three-Layer Completeness" principles
- PM2 scripts now include graceful shutdown configuration

---

## [1.0.0] - 2026-01-17

### Added
- Initial release of SkillFoundry Framework
- Genesis-first development workflow
- PRD and Story templates
- Three-layer enforcement (Database, Backend, Frontend)
- Zero tolerance policy for placeholders/TODOs
- Skills system with `/go`, `/prd`, `/layer-check` commands
- CLAUDE.md with BPSBS standards
- `install.sh` for framework installation
- Authentication & token management security standards
- Admin password security requirements
- PM2 production deployment scripts
- SEO implementation checklist

---

## Version History Summary

| Version | Date | Focus |
|---------|------|-------|
| 1.9.0.14 | 2026-02-13 | OpenAI Codex platform support: 4th platform, 60 Codex Skills, AGENTS.md, quad-platform sync engine |
| 1.9.0.13 | 2026-02-09 | The Anvil: 6-tier quality gate (shell pre-flight, canary, self-adversarial, scope, contract, shadow) |
| 1.9.0.5 | 2026-02-08 | Knowledge Hub: git-based distribution, cross-machine scratchpad/knowledge sync |
| 1.9.0.4 | 2026-02-08 | Persistent scratchpad: cross-platform session continuity (Claude/Copilot/Cursor) |
| 1.9.0.3 | 2026-02-07 | Platform Sync Engine: generate platform files from agent source, command: field |
| 1.7.0.2 | 2026-02-07 | Autonomous execution: permission profiles, safety hooks, zero-prompt workflow |
| 1.7.0.1 | 2026-02-06 | Populated templates/, parallel/, memory_bank/ with practical content |
| 1.7.0.0 | 2026-02-05 | Auto-remediation, fixer orchestrator, 3 execution modes, security scanner, dream team audit |
| 1.6.0 | 2026-02-03 | Dream Team (8 specialist agents), full SDLC coverage |
| 1.5.0 | 2026-01-25 | Observability & tracing system |
| 1.4.1 | 2026-01-25 | Full Node.js MCP/dashboard implementation |
| 1.4.0 | 2026-01-25 | Persistent memory, MCP integration, dashboard, parallel execution |
| 1.3.5 | 2026-01-25 | Reflection protocol expansion, Windows error handling |
| 1.3.4 | 2026-01-25 | Agent reflection protocol, enhanced test suite |
| 1.3.3 | 2026-01-25 | Quick start wizard, one-click installers |
| 1.3.2 | 2026-01-25 | 8 new specialized agents (refactor, performance, dependency, etc.) |
| 1.3.1 | 2026-01-20 | TDD enforcement, parallel dispatch, git worktrees, systematic debugging |
| 1.3.0 | 2026-01-20 | State machine, rollback, metrics, dependency graphs, gate verification |
| 1.2.0 | 2026-01-18 | Context engineering, recursive decomposition, token optimization |
| 1.1.0 | 2026-01-18 | Production readiness, security enhancements, update system |
| 1.0.0 | 2026-01-17 | Initial release |

---

## Upgrade Guide

### From 1.6.0 to 1.7.0.0

1. Run the update script:
   ```bash
   /path/to/skillfoundry/update.sh /path/to/your/project
   ```

2. New files added:
   - `.claude/commands/fixer.md` - Fixer Orchestrator (auto-remediation)
   - `.claude/commands/version.md` - Version management
   - `.claude/commands/security-scanner.md` - AI vulnerability scanner
   - `docs/ESCALATION-CRITERIA.md` - Auto-fix vs escalation matrix
   - `.gitignore` - BPSBS-compliant security exclusions

3. Moved files (paths updated automatically):
   - `ANTI_PATTERNS_BREADTH.md` → `docs/ANTI_PATTERNS_BREADTH.md`
   - `ANTI_PATTERNS_DEPTH.md` → `docs/ANTI_PATTERNS_DEPTH.md`
   - `CLAUDE-SUMMARY.md` → `docs/CLAUDE-SUMMARY.md`
   - `install-unified.sh` → `scripts/install-unified.sh`

4. Deleted files:
   - `agents/reptilian-gate-keeper.md` (merged into `agents/gate-keeper.md`)

5. Updated files:
   - All `.claude/commands/*.md` - Added persona references to shared modules
   - All `.cursor/rules/*.md` - Added persona references to shared modules
   - `agents/gate-keeper.md` - Added auto-fix mode, regression detection
   - All shell scripts - Added `set -o pipefail`

6. Using new features:
   ```
   /go --mode=semi-auto       # Auto-fix routine violations
   /fixer                     # View auto-remediation stats
   /security-scanner          # AI-specific vulnerability scan
   /version                   # Check version and updates
   ```

---

### From 1.3.0 to 1.3.1

1. Run the update script:
   ```bash
   /path/to/skillfoundry/update.sh /path/to/your/project
   ```

2. New files added:
   - `agents/_tdd-protocol.md` - TDD enforcement
   - `agents/_parallel-dispatch.md` - Parallel agent execution
   - `agents/_git-worktrees.md` - Git worktree isolation
   - `agents/_systematic-debugging.md` - Four-phase debugging

3. Updated files:
   - `.claude/commands/coder.md` - TDD enforcement added
   - `.claude/commands/debugger.md` - Four-phase protocol added
   - `.claude/commands/delegate.md` - Parallel dispatch added
   - `.claude/commands/go.md` - New flags (--parallel, --worktree, --tdd)

4. Using new features:
   ```
   # TDD enforcement (default: STRICT)
   /go --tdd              # Enforce TDD mode
   /go --tdd=WARN         # Warning mode

   # Parallel execution
   /go --parallel         # Enable wave-based parallel
   /go --parallel=EAGER   # Eager mode
   /go --parallel=2       # Limit to 2 concurrent

   # Git worktree isolation
   /go --worktree         # Execute in isolated worktree
   ```

5. The /coder agent now requires tests FIRST:
   - RED phase: Write failing test
   - GREEN phase: Minimal implementation
   - REFACTOR phase: Improve quality

6. The /debugger agent now uses four phases:
   - OBSERVE: Gather facts
   - HYPOTHESIZE: Form explanations
   - TEST: Validate hypotheses
   - VERIFY: Confirm fix

---

### From 1.2.0 to 1.3.0

1. Run the update script:
   ```bash
   /path/to/skillfoundry/update.sh /path/to/your/project
   ```

2. New files added:
   - `agents/_state-machine.md` - Execution state machine
   - `agents/_rollback-protocol.md` - Rollback protocol
   - `agents/_story-dependency-graph.md` - Story dependencies
   - `agents/_prd-dependencies.md` - PRD dependencies
   - `agents/_metrics-system.md` - Metrics system
   - `agents/_agent-protocol.md` - Agent communication
   - `agents/_test-execution.md` - Test integration
   - `agents/_gate-verification.md` - Gate verification
   - `.claude/commands/metrics.md` - New `/metrics` skill
   - `genesis/.schema.json` - PRD validation schema

3. Updated files:
   - `genesis/TEMPLATE.md` - Now includes dependency metadata
   - `.claude/commands/go.md` - New flags and features
   - `update.sh` - New `--sync` command

4. Using new features:
   ```
   /go --status        # Check current state
   /go --resume        # Resume interrupted execution
   /go --rollback      # Undo last execution
   /go --metrics       # View execution metrics
   /metrics            # Dedicated metrics dashboard
   ```

5. PRD dependencies:
   - Add dependency metadata to PRDs:
     ```yaml
     dependencies:
       requires: [other-prd]
       blocks: [dependent-prd]
     ```

6. Story dependencies:
   - Stories now support `depends_on` and `blocks` fields
   - INDEX.md generated with dependency graph

7. Validate sync:
   ```bash
   /path/to/skillfoundry/update.sh --sync /path/to/your/project
   ```

### From 1.1.0 to 1.2.0

1. Run the update script:
   ```bash
   /path/to/skillfoundry/update.sh /path/to/your/project
   ```

2. New files added:
   - `CLAUDE-SUMMARY.md` - Use this for active context instead of full CLAUDE.md
   - `.claude/commands/context.md` - New context management skill
   - `agents/_context-discipline.md` - Shared agent module
   - `agents/_subagent-response-format.md` - Sub-agent format standard
   - `agents/_recursive-decomposition.md` - Task decomposition protocol

3. Using context engineering:
   ```
   /context           # Check current token budget
   /context compact   # Force compaction when needed
   /go                # Now includes Phase 0 context prep
   ```

4. All agents now include:
   - Scratchpad pattern for session tracking
   - Token-aware behavior
   - Structured output format

### From 1.0.0 to 1.1.0

1. Run the update script:
   ```bash
   /path/to/skillfoundry/update.sh /path/to/your/project
   ```

2. Review the diff first (optional):
   ```bash
   /path/to/skillfoundry/update.sh --diff /path/to/your/project
   ```

3. Choose how to handle CLAUDE.md:
   - **Overwrite**: Get all new sections (backup saved)
   - **Keep**: Preserve your customizations
   - **Merge**: Save new version as `.new` file for manual merge

4. Verify new requirements:
   - [ ] .gitignore updated with security patterns
   - [ ] LoggerService implemented (if frontend exists)
   - [ ] Pre-commit hooks configured (optional but recommended)
