# Changelog

All notable changes to **ai-flow-kit** will be documented in this file.

Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

---

## [Unreleased]

### Changed

- **`evidence-helper.ts`'s loading-detection became technology-agnostic instead of relying on a hand-maintained CSS-selector list.** The original `LOADING_SELECTORS` fast-path (`.spinner`, `.loading`, role `progressbar`) worked only for apps whose loading overlay happened to match one of those class names — a real-world fix for ec-core's Element Plus `.el-loading-mask` overlay had to be hand-edited directly into the deployed `Shared/evidence-helper.ts` copy, with no path to reach other projects or survive a re-sync. `waitForUiSettled()` is now five layers, cheapest/most-specific to most-general: (1) `networkidle` + selector fast-path, now including the WAI-ARIA-standard `[aria-busy="true"]` — a signal not tied to any framework; (2) no CSS animation/transition still running (Web Animations API); (3) DOM stopped mutating for a short quiet period (`MutationObserver`); (4) web fonts loaded; (5) **new, opt-in** — consecutive viewport screenshots come back pixel-identical, a last-resort check that needs zero app knowledge and catches canvas/WebGL loaders, GIF/APNG spinners, `background-position` sprite animations, or a plain server-rendered page (Java/JSP, PHP, ...) with no DOM/ARIA hook to watch at all. **Off by default** — enable per-call via `{ enableVisualStability: true }` only for a screen known to need it, and raise that spec's `timeout` to match. It shipped default-ON in an earlier draft and was caught by re-running MFG113 against ec-core: a test with 14 `captureStepEvidence()` calls in a loop (asserting 7 sortable columns × 2 directions) blew past Playwright's default 30s test timeout purely from the extra polling, with no actual app defect — confirming this layer must stay opt-in.
- **`captureStepEvidence()`/`openAndCapture()` no longer trust Playwright's auto-generated per-test output directory for evidence file paths — they derive the `{TC_ID}-{kebab-scenario}` folder name directly from `testInfo.title` instead.** Found during the same MFG113 re-run: Playwright's built-in per-test directory naming (sanitize + truncate + hash-on-collision) had, in an earlier run of the exact same suite, coincidentally produced clean `TC-MFG113-013-...` folders; re-running the unchanged suite produced garbled hashed names (`MFG113-MFG113-MFG113---Dan-30c80-...`) for the same tests instead — undocumented, Playwright-version-dependent, and especially unstable for titles heavy with non-ASCII (Vietnamese/Japanese) text once diacritics are stripped for sanitization. New `tcFolderName()`/`tcEvidenceDir()` split `testInfo.title` on the mandated `'{TC_ID} - {Test Case Name}'` format (see script-sync SKILL.md) and write straight to `path.join(testInfo.project.outputDir, tcFolderName, fileName)`, making the evidence path fully deterministic regardless of Playwright's internal naming behavior. Playwright's own auto-captured failure artifacts (`screenshot: 'only-on-failure'`, `video`, `trace`) still land in Playwright's own auto-named directory since those aren't routed through `evidence-helper.ts` — `execute-flow`'s Gate 3 "Bước 4" now documents merging the final attempt's `test-failed-*.png`/`trace.zip`/`video.webm` into the canonical `{TC_ID}-{kebab-scenario}/` folder as `failure-screenshot.png`/`trace.zip`/`video.webm` and deleting the auto-named leftover, so both passing and failing TCs end up evidenced in one consistently-named place.
- **New `evidence-helper.config.ts` template** — a small, always-empty-by-default companion file scaffolded once alongside `evidence-helper.ts` and never touched again by tooling. App-specific loading conventions (a UI kit's directive-driven overlay class, a bespoke spinner component, ...) now go here via `PROJECT_LOADING_SELECTORS`, imported by `evidence-helper.ts`. This is the actual fix for the ec-core case above: `.el-loading-mask` becomes a one-line addition to the project's own config file instead of a hand-edit to the "generic" shared file, so it survives every future `evidence-helper.ts` re-sync and the pattern now generalizes to any other project's own overlay convention (React, Angular, plain Java-rendered pages, ...). Because `evidence-helper.ts` itself now carries no project-specific knowledge, `execute-flow`/`script-sync`'s scaffold step changed from "copy once, never recreate" to "always re-sync from the latest template" for this one file — `evidence-helper.config.ts` keeps the old "copy once" rule.
- **`playwright.config.ts` template's default test `timeout` raised from Playwright's built-in 30s to 60s.** Also found re-running MFG113: a TC that calls `captureStepEvidence()` many times in one test (looping over every sortable column) was already ~26s at baseline; the restored animation/DOM-stability wait layers above pushed it past 30s and the test timed out on infra grounds alone, no app defect involved. The extra wait time these layers add is deliberate (see previous entry), so the timeout budget needs to account for it rather than the other way around.
- **`execute-flow`'s Bước 1b now proactively proposes `evidence-helper.config.ts` additions instead of relying on someone to notice a bad screenshot.** Filling `evidence-helper.config.ts` was designed as a one-time manual step, but that assumes a developer runs execute-flow — in practice it's often a Tester, who has no way to know a given screen's loading overlay needs a config entry at all until evidence quietly comes back mid-spinner. Bước 1b's existing source-code read (already done for Gate 2 selectors) now also scans the screen's own component for known UI-kit loading conventions (Element Plus/Element UI `v-loading` → `.el-loading-mask`, Vuetify `v-overlay`, MUI `CircularProgress`/`Backdrop`, Ant Design `Spin`, Bootstrap `spinner-border`/`spinner-grow`, Chakra `Spinner`, or an in-house `*Loading*`/`*Spinner*`/`*Overlay*` component), skipping anything already covered by the generic selectors or already present in the project's config. A match pauses with one plain-language, non-technical confirm question (cites the source file, explains the "evidence captured mid-loading" consequence, no ARIA/directive jargon) before writing anything — declining doesn't get remembered as a permanent no, so a later screen hitting the same selector is free to ask again. Verified against this session's own finding: scanning ec-core's `ManagementTable/index.vue` (the shared table component MFG113 renders through) surfaces `v-loading={appStore.loading}` exactly as the heuristic expects, i.e. the same `.el-loading-mask` gap this session found and fixed by hand would have been caught and proposed automatically.
- **New Gate 1 pre-flight item 7 makes `evidence-helper.ts` re-sync reach already-onboarded projects, not just brand-new ones.** The scaffold step that copies `evidence-helper.ts`/`evidence-helper.config.ts` only ever ran behind "`{repo}/playwright.config.ts` missing" (item 4) — true once per repo, at first-ever setup. Every above change was correctly documented as "safe to re-sync on update," but with no pre-flight item actually re-checking it once a repo already has `Shared/`, updating ai-flow-kit alone did nothing for a project already using execute-flow — evidence-helper.ts stayed frozen at whatever version it was scaffolded with, and evidence-helper.config.ts never got backfilled for repos scaffolded before it existed. New item 7 runs independently of item 4: if `Shared/evidence-helper.ts` exists, overwrite it from the latest template every Gate 1 run; if `Shared/evidence-helper.config.ts` is missing, create it (empty defaults), never touching one that already exists. This is what makes "update ai-flow-kit, run `ak execute` again" actually pick up future evidence-helper.ts improvements without a manual file copy or full rescaffold.
- **Scaffold's `package.json` devDependencies gained `@types/node`** — `evidence-helper.ts` importing Node's `path` module plus `tsconfig.json`'s pre-existing `"types": ["node"]` both require it; missing before, this only surfaced as an IDE/`tsc --noEmit` error (never as a runtime failure, since Playwright's esbuild-based transform doesn't type-check).

## [0.2.2] - 2026-08-24

### Added

- **`create-spec` and `create-testcase` gained a Mode CREATE/UPDATE branch, closing the biggest gap found in `docs/internal/Token Problems.md`'s token-cost investigation: neither workflow had any way to tell "this UC Spec/Test Case already exists" from "this is the first time" — every re-elicitation after a UC Spec was already PM-approved re-ran the full Gate 1 (re-read the whole input twice, re-investigate all source code, re-list every Gap/Assumption) exactly like a brand-new feature, even for a 1-line Business Rule tweak.
  - `create-spec-workflow.md` Gate 1 Bước 0 now resolves `Mode` right after `functionId`: no existing `UC-Spec_v{N}.md` → `CREATE` (unchanged behavior, still `_v1`); an existing, PM-merged one → `UPDATE`, version `N+1`, with Bước 1/1b/2 scoped to the delta described in the new input (source-code investigation limited to the affected area, Gap/Assumption listing limited to what's new or affected) plus a mandatory, cheap side-effect scan (grep the current UC Spec for other mentions of the same field/entity/actor) before trusting that scope — explicitly **not a 100%-safe substitute** for full re-investigation, so a BA who suspects a large change can still force `CREATE`. `skill-ba-uc-template-v1.md` gained a mandatory `UC-Spec-Version` header and a new "6. Change Log" section (parallel to System Requirement's existing one) as the anchor this mode writes against.
  - `create-testcase-workflow.md` Gate 1 Bước 0.6 gained the matching check against `[functionId]_TestCase.md`'s new `UC-Spec-Version`/`System-Requirement-Version` header fields (added to `testcase-template.md` Mục 1); `UPDATE` mode scopes Gate 2/3 test design to scenarios mapped to changed Business Rules only, carrying forward unaffected Test Cases verbatim. Because scoping test design by "what changed" risks missing cases that only emerge from a **combination** of a changed rule and an unchanged one, Gate 4 Bước 1 gained a mandatory combinatorial-check item specific to `UPDATE` mode that a Fully/Conditionally Approved sign-off cannot skip.
- **`create-system-requirement` gained Step 1.5 (RESYNC Diff), run before source-code investigation instead of after drafting.** The skill's own existing `RESYNC` mode already diffed the new UC Spec version against the previous one — but only at Step 3 (drafting), by which point Step 2 (source investigation, the skill's own documented "single most expensive step") had already re-investigated the whole UC regardless of how small the actual change was. Step 1.5 now runs the same diff earlier and hands its "changed / unchanged / removed" classification to Step 2 as the investigation scope, so an unchanged Flow/BR carries forward its prior `Implementation Reference` without a fresh read. Because "UC Spec unchanged" doesn't guarantee "code unchanged" (Dev may have refactored independently between System Requirement versions), Step 2 also gained a mandatory, cheap `git log --since=<prior-approval-date> -- <files from Section 6.1>` check before treating an unchanged section as safe to skip — not a complete guarantee (a brand-new file outside the known Section 6.1 list still won't be caught), but far cheaper than re-investigating everything.
- **`create-system-requirement` gained a Source Checklist Crosswalk (new Section 0.1) and two new Step 3.5 audit directions (C: Acceptance-Test coverage, D: Decision traceback), following a real Opus-vs-Sonnet output comparison documented in `docs/internal/Token Problems.md` §4.** Same skill, same UC Spec, two models: Opus's output cited ~30 of the UC Spec's underlying BA decision IDs (`OQ-xx`, from a Q&A/decision appendix) and caught a UC Spec item that referenced UI text (`履歴`) not present anywhere in the codebase; Sonnet's output cited **zero** `OQ-xx` IDs and missed that item entirely, and left ~45% of its own Validation Rules with no Acceptance Test covering them. None of this was a raw-capability gap requiring more tokens to fix — it was missing forcing functions. Step 1 now flags when the UC Spec has a Q&A/decision appendix (must be read in full, not skimmed) or references a numbered/enumerated source list (e.g. "23 hạng mục ở Phụ lục E"); Step 3 gained a worked example clarifying Functional Requirement granularity (one per distinct behavior, not one per numbered UC Flow step) and an explicit warning that the existing "investigate once, reuse across items" cost-control principle governs *re-reading files*, not *how many FR/VR/AT items the content deserves*; Step 3.5 Direction C rejects the draft if any VR/ER has zero Acceptance Test in its `Requirement Coverage`, and Direction D rejects it if any `Classification: Decision` line lacks its source `OQ-xx` where an appendix exists. The Gate 2 prompt (Step 7) now reports all four Step 3.5 counts, not two.
- **`execute-flow`'s Playwright harness can now target a browser other than Chromium via `PW_BROWSER`, gated behind an explicit tester confirmation before it's ever used.** Prompted by a real report: a project's evidence screenshots were coming back with missing/garbled fonts because its `playwright.config.ts` had drifted to running on WebKit, whose font-fallback behavior differs from Chromium's (especially for CJK glyphs on Linux) — the exact failure class the existing `deviceScaleFactor`/`locale` settings were already tuned to avoid, but nothing stopped a project from silently ending up on a different browser project. `templates/playwright.config.ts` now resolves `projects[0]` from `PW_BROWSER` (`chromium` default, or `webkit`/`firefox`) via a `devices[...]` map, throwing on any other value. New Gate 1 pre-flight item 5 (existing items 5-7 renumbered to 6-8) determines the effective browser for the run — `PW_BROWSER` if the tester set it for this session, else the already-scaffolded config's `projects[0].name`, else the `chromium` default — and if it resolves to anything but `chromium`, stops and asks the tester to confirm before proceeding, explaining the font-rendering risk and how to revert to Chromium. A confirmed choice carries through the whole run, including the RETEST loop, so the tester is only asked once per run. Item 6 (`npx playwright install`) now installs whichever browser was resolved instead of always installing `chromium` unconditionally.

### Changed

- **`execute-test` flow (`execute-flow` + `script-sync` skills) no longer uses an `ak-test/` working dir at all — everything, including binary evidence, now lives inside `AK-Docs/03.Testing/`.** Previously the whole flow (Playwright scripts, per-TC `result.md`, bug drafts, `testreport.md`, and evidence) lived under `ak-test/{repo}/`, outside the project's docs tree — reports/bugs/scripts had no place in version control alongside the rest of `AK-Docs/03.Testing/` (Testcases, Reports, Bugs). New mapping: `05.Scripts/{repo}/{featureDir}/{ScreenID}.spec.ts` (Gate 2), `04.Evidence/{repo}/{featureDir}/run-{N}/` (Gate 3, screenshots/video/`trace.zip`/raw `results.json`), `02.Reports/{repo}/{featureDir}/run-{N}/{result.md, testreport.md}` (Gate 3/4), `06.Bugs/{repo}/{featureDir}/run-{N}/BUG-NNN-*.md` (Gate 3) — this restores `docs/common/Testing-Structure.md`'s original Gate 3 → `04.Evidence/` mapping instead of diverging from it (an earlier iteration of this change had evidence live in `ak-test/` to keep binaries out of AK-Docs entirely; superseded before release in favor of `.gitignore`). `05.Scripts/` is a self-contained, runnable Playwright project (`package.json`/`node_modules`/`tsconfig.json`) living inside AK-Docs — Gate 1 auto-scaffolds it and appends `03.Testing/04.Evidence/` plus `03.Testing/05.Scripts/**/{node_modules,test-results,playwright-report,blob-report}` to `.gitignore` if missing, so the binary evidence and Playwright build artifacts never get committed even though they're colocated with the rest of the docs tree. `playwright.config.ts`'s `outputDir`/JSON reporter path read `EVIDENCE_DIR` (set by the AI per run to the `04.Evidence/` path, a simple 1-level-up relative path from `05.Scripts/` since both now live under the same `03.Testing/` parent) so each run gets its own evidence folder.

- **`execute-flow`/`script-sync` gained explicit DOM-assertion and evidence-quality rules** to fix reported false pass/fail results and low-quality screenshots: locators that match more than one element are now called out as the primary root cause of mis-graded TCs (fix: scope to the right container or use `data-testid`, not `.first()`/broad CSS); assertions must check the actual Expected Result content (`toHaveText`/`toBeDisabled`/etc.), not just element presence; negative/validation TCs need an assertion on the actual blocking behavior, not "page didn't crash." New shared helper `custom/skills/execute-flow/templates/evidence-helper.ts` (copied once to `AK-Docs/03.Testing/05.Scripts/Shared/`) provides `waitForUiSettled()` (networkidle + no loading indicator + fonts ready — fixes screenshots taken mid-spinner), `highlightElement()`/`removeHighlight()` (red 3px outline around the item to confirm), and `captureStepEvidence()`/`openAndCapture()` (per-TC-Step screenshot, click-to-open-modal before capturing, `scrollIntoViewIfNeeded()` for scrollable content) — every generated spec must use these instead of ad-hoc screenshot calls. `playwright.config.ts` template gained `deviceScaleFactor: 2` and a configurable `locale` (default `ja-JP`) for sharper, correctly-rendered Kanji/Katakana text in evidence, plus 1 retry to absorb timing flakes before a TC is reported FAIL.
- **`script-sync` now caches Playwright locators per screen instead of re-deriving them per Test Case, while still verifying against a fresh `browser_snapshot` for every TC — not skipping the snapshot.** Also from `docs/internal/Token Problems.md`'s investigation: Gate 2 previously ran a full `navigate` → `snapshot` → `generate_locator` cycle per TC, even though most TCs on the same screen share the same starting state (list → open modal → field → submit), a real cost driver directly named in user feedback. The first TC generated for a screen still snapshots and derives locators for every interactive element visible (not just its own), building `{ScreenID}Page.ts` up front; every subsequent TC still calls `browser_snapshot` (cheap, and the only thing standing between this change and the exact false-pass/false-fail failure mode `script-sync`'s own "Assertion Rules" section warns about) but only calls the more expensive `browser_generate_locator` when the snapshot shows an element genuinely new or changed from what the Page Object already has. An earlier draft of this change dropped the per-TC snapshot entirely; kept instead once the risk was reviewed — see `docs/internal/Token Problems.md` §4.2.
- **`create-testcase`'s Gate 2/Gate 3 "always apply" skill reads collapsed from up to 14 separate `Read` calls per run down to 4 merged files** (`custom/skills/test-skills/categories/_gate2-always-apply.md`, `_gate3-test-design-always-apply.md`, `_gate3-ui-always-apply.md`, `_gate3-business-data-always-apply.md`) — these are static, mandatory-for-every-functionId reference files (BVA, Equivalence Partitioning, Decision Table, Error Guessing, UI Layout, Form Validation, Navigation, Localization, CRUD, Permission, Database, Duplicate-Handling) that never changed content between runs but were previously read as 12+ individual tool calls every single Gate 2/3 invocation. The original per-technique files are untouched (still the source of truth for standalone edits) and merged into the 4 new files at a sub-category boundary rather than one giant per-Gate file, preserving the ability to edit one technique without touching unrelated ones. Conditional (not-always-applicable) skill files were left unmerged, unchanged.
- **Extracted `create-system-requirement`'s "investigate once, reuse across items" methodology (GitNexus-first → `Explore` sub-agent delegation → investigate per module not per rule → running Investigation Notes table) into a new shared rule file, `custom/rules/investigation-cost-control.md`.** It had only ever been written out in `create-system-requirement/SKILL.md`, despite `read-study-requirement`, `create-spec` (BA source-code investigation), and `test-analysis` all doing the same "read source before analyzing" work with none of the same cost discipline — each now references the shared file with one line instead of re-deriving (or lacking) the same guidance independently.

### Fixed

- **Doc/code drift between `execute-flow`/`script-sync` SKILL.md prose and the actual `evidence-helper.ts` signatures**, found during a consistency audit of the above two entries: `execute-flow`'s "Evidence Quality Rules" described calling `highlightElement(page, selector)` / `removeHighlight(page)` and `captureStepEvidence(page, evidenceDir, ...)` — neither matches the real exports (`highlightElement(target: Locator)`, `removeHighlight(target: Locator)`, `captureStepEvidence(page, testInfo, stepIndex, stepDesc, opts)`); corrected to describe passing a `Locator` via `highlightSelector` and the real `testInfo` param so an AI following the prose literally doesn't generate code that fails to compile.
- **`Shared/fixtures/test.ts` and `Shared/BasePage.ts` were referenced everywhere** (directory trees, generated-code import examples, the "don't recreate if exists" rule) **but had no scaffold instruction and no template of their own** — only `playwright.config.ts` and `evidence-helper.ts` had a documented "copy from templates/" step. `execute-flow`'s "Scaffold Playwright Project" section now also copies the existing, already-tested `custom/harness/playwright/tests/e2e/fixtures/test.ts` and `tests/e2e/pages/BasePage.ts` (from the separate `ak scaffold playwright` harness) into `Shared/`, and `script-sync`'s Page Object generation step now explicitly says `class {ScreenID}Page extends BasePage`.
- **`AIFLOW.md`'s Execute Test Flow Gate 4 was mislabeled `*(skill: generate-test-report)*`** — that skill belongs to the older, separate `testing` task-type workflow (`evidence/`, `bugs/`, `test-plan/` dirs) and is never invoked by `execute-flow`, whose Gate 4 does report generation and bug logging inline. Label removed; a stale `bugs/BUG-*.md` path fragment in the same Gate 4 step was also corrected to the current `06.Bugs/{repo}/{featureDir}/run-{N}/` location.
- **`docs/common/Testing-Structure.md`'s File Naming Convention table implied `execute-test` output folders follow `F-{3-digit}_{Pascal-Case}` / `{Feature}.spec.ts`**, but `execute-flow`/`script-sync` have always keyed off the TC file's `ScreenID` (e.g. `AD10`), not a Feature-ID — added a callout documenting the actual `featureDir = {ScreenID}_{Screen-Name-kebab-case}` / `{ScreenID}.spec.ts` convention instead of silently conflicting with the general table.

## [0.2.1] - 2026-08-17

### Added

- **`ingest-data` gained Gate 3 — auto-triggered task proposal & real ticket creation on Backlog/Jira, closing the gap after Gate 2 where the flow used to just stop once an entry landed in `AK-Docs/01.QnA/`.** Implements "Vấn đề 5" in `docs/internal/PM Workflow_v1.0.md`, decided to run **automatically** right after Gate 2 (not on-demand as the doc's earlier tentative proposal had it):
  - AI re-reads the entry just ingested plus related source code/docs to judge impact, then decides whether it needs a task at all — pure-reference content (FYI, status update) ends the gate with no task proposed, no ticket created.
  - When action is needed, proposes a task list (`type`: spec/coding/test/other, `title`, `track`, `description` built from the PM Workflow §6.1 template — spec-type tasks additionally require a PM-supplied "Nguồn tham chiếu" link, never inferred). The user can add/edit/remove tasks directly during review — not just approve/reject the whole list — before the single explicit confirmation point ("Danh sách task như trên — đồng ý tạo trên Backlog/Jira?", never auto-`--yes`'d).
  - New `scripts/ticket-writer.js` — `ak tasks create-tickets <file>.json [--json]` posts the approved list as real Backlog/Jira issues. `scripts/link-resolver.js` gained the write-side API calls it needed (`createBacklogIssue`, `createJiraIssue`, `fetchBacklogIssueTypes`, `fetchBacklogPriorities`) plus a generic `httpsPost` helper (form-encoded for Backlog, JSON for Jira) — the existing `httpsGet`-only file had no POST capability before this.
  - **Deliberately separate WRITE credentials** (`BACKLOG_API_KEY_WRITE` / `JIRA_API_TOKEN_WRITE`) from the read-only keys `ak fetch-links`/`ak use` already rely on, per the PM Workflow doc's policy of never letting the read key create tickets. When missing, `ak tasks create-tickets` returns a structured `{"error":"missing-write-credentials", field, message}` instead of failing silently — the AI surfaces this in chat, asks the user to paste the key, saves it via the new `ak credentials set <key> <value>` (allowlisted to the keys this feature introduced — dedicated adapter credentials still go through `ak init --adapter`), and retries once.
  - Project-id resolution reuses the existing `BACKLOG_DEFAULT_PROJECT_ID`/`ak backlog-projects`/`ak backlog-set-default-project` pattern; added the Jira equivalents (`ak jira-projects`, `ak jira-set-default-project`, `fetchJiraProjects` in `scripts/use.js`) so both adapters check local config before ever prompting.
  - Approved tickets get their link written back into the originating `Meetings-Log`/`QnA-Log`/`Confirmations-Log` entry (`→ Tasks created: TICKET-101 (coding), ...`), keeping the traceability chain from PM Workflow §6 intact end-to-end.
  - **Still open, tracked in the PM Workflow doc's Vấn đề 5 implementation note:** no fixed feedback→task-type rule table (AI still judges per-context); new tickets don't auto-attach `functionId`/labels (Dev/BA/QA still assign on `ak use TICKET-XXX`); Backlog issueType/priority default to the project's first issueType and a "Normal"-named priority unless overridden explicitly in the task JSON.

- **`ak gate <n> skip --ticket <id> [--reason <text>]`** — a gate can now close as "skipped" (legitimately produced no deliverable) instead of only `start`/`approved`. First consumer: `ingest-data` Gate 3, when the AI decides the ingested content is reference-only and no task list is needed — it now runs `ak gate 3 skip` instead of leaving the gate untouched. `scripts/task.js`'s `updateTaskGateState()` gained a `skip` branch that records `skippedGates[gate] = {at, reason}` in `task-state.json` and advances `currentGate` exactly like `approved` does, so every existing "is this task done" check (which only ever inspects `currentGate`) keeps working with zero changes. Prompted by an impact assessment for the `ai-flow-ex` VS Code extension's dashboard, which was showing skipped-Gate-3 ingest-data tasks stuck as "ready to run Gate 3" forever — see `docs/superpowers/specs/2026-08-06-ingest-data-gate3-skipped-state-design.md` in `ai-flow-ex` for the paired UI-side change (reads `skippedGates` to render a distinct "⏭ Skipped" badge instead of the generic "✓ Approved").

### Changed

- **Per-framework rule sections (Architecture, layer rules, naming, security, anti-patterns) moved out of `CLAUDE.md`/`AGENTS.md` into `.rules/<lang>/<framework>-rules.md`, alongside the existing `-examples.md`.** Extends the same on-demand `.rules/` pattern already used for code samples to the rules themselves: `custom/templates/<framework>.md` now holds only the title, a one-line intro, and a single "> **Rules & code examples:**" pointer to both files — everything else (Controller/Service/Repository/Entity/DTO/Mapper/Exception/Testing/Naming/API/Performance/Security/Logging/anti-patterns, per framework) lives in the new `-rules.md` file. Applied to all 9 templates that had this structure (`spring-boot`, `php`, `php-plain`, `reactjs`, `nestjs`, `nodejs-express`, `python`, `python-django`, `python-fastapi`, `python-ml`) — `nextjs`/`vue-nuxt`/`laravel` were already ~15 lines with no such structure and are untouched. Unlike the workflow-file pointer (read once at a clear Gate-start trigger), these rules apply continuously across every code edit in Gate 3, so `custom/templates/shared/gate-workflow.md` and `ml-gate-workflow.md` both gained an explicit bullet at the top of their Gate 3 (`Code Generation` / `Implement, Train & Iterate`) step: read the rules + examples files pointed to at the top of `CLAUDE.md`/`AGENTS.md` before the first line of code, and keep applying them to every subsequent edit, not just the first. Also fixed `generateSkillNameList()`'s "Codex indexes these automatically" wording, which became inaccurate once `claude` also uses the compact skill list (see previous entry) — reworded to name neither tool specifically. Measured on the kit's own dogfood skill set: solo `spring-boot`/`reactjs`/`php` 247/211/~205 → **41 lines each**; multi `spring-boot`+`php` 385 → **55 lines**.

- **`CLAUDE.md` now uses the same compact skill list as `AGENTS.md`, and 2 techstack templates dropped a redundant "Project Stack" section.** `AI_TOOL_SKILL_LIST_STYLE` gained `'claude': 'compact'` — Claude Code auto-discovers each skill's name + description from `.claude/skills/*/SKILL.md` frontmatter on its own (same mechanism the original Codex-only rationale assumed only Codex had), so restating the full description table in `CLAUDE.md` was duplicating information the tool already surfaces natively. `custom/templates/spring-boot.md` and `reactjs.md` also dropped their "## Project Stack" bullet list (Java/Spring Boot/Maven version pins, React/TypeScript/Vite/Router/etc.) — for spring-boot every item was already restated in a more specific rule section further down (Testing Rules, Entity Rules, Mapper Rules...); for reactjs most items were too (State Management, Form, Styling, API Layer Rules), except **Router (React Router v6), the shadcn/ui pairing with Tailwind, and Vitest as the specific test runner**, which had no other home in the file and are now gone rather than relocated — worth restoring into an existing rule section later if that specificity is missed. Measured on the kit's own dogfood skill set (~46 skills): solo `spring-boot` 306 → 247 lines, solo `reactjs` ~264 → 211 lines, multi `spring-boot`+`php` 444 → 385 lines.

- **`CLAUDE.md` now uses the pointer layout too, not just `AGENTS.md`.** `AI_TOOL_LAYOUT` in `scripts/init.js` gained `'claude': 'pointer'` alongside the existing `'codex': 'pointer'` — CLAUDE.md is loaded in full at the start of every session regardless of which gate (if any) is active, so inlining the ~115 KB DEV/TESTER/EXECUTE/gen-doc/ingest-data + BA + QA workflow set spent context on gates most sessions never touch. The workflow bodies now live in `.aiflow/instructions/` and CLAUDE.md just links to them, same as Codex. Unlike Codex's pointer layout, the skill registry keeps its full description table for `claude` (`resolveSkillListStyle()`/`resolveSkillsRoot()`) — Claude Code has no skill index of its own the way Codex does, so only the workflow bodies move out, not the registry.
- **Techstack rule templates (`custom/templates/<framework>.md`) no longer inline full code samples for every layer.** Following the pattern already used for `spring-boot.md`/`custom/rules/java/spring-boot-examples.md`, the same split was applied to the other 9 templates that had grown a "✅ Good / ❌ Bad" code block per rule area: `reactjs`, `php`, `php-plain`, `python-ml`, `nestjs`, `nodejs-express`, `python`, `python-django`, `python-fastapi`. Each template keeps its bullet rules, naming table, and anti-pattern list, with a one-line pointer to a new `custom/rules/<lang>/<framework>-examples.md` file holding the actual code samples — read on demand when generating code for that specific layer instead of being inlined into every session's context. `FRAMEWORK_LANGUAGE` in `scripts/init.js` also gained entries for `nodejs-express`, `python`, `python-django`, `python-fastapi`, and `php-plain` (previously missing, so `.rules/<lang>/` was never copied into projects using those frameworks).
- **Multi-framework projects no longer duplicate the tool header, skill registry, and workflow-files pointer once per framework.** A project with 2+ frameworks (e.g. a `spring-boot` backend + a `reactjs` frontend) calls `setupFramework()` once per framework with `multi: true`; each call used to emit a fully self-contained block (tool header + full skill registry + framework rules + "Installed workflow files" pointer note), so all three non-framework-specific sections got repeated verbatim per framework — the ~46-skill registry was the dominant cost in `CLAUDE.md` once the per-framework code samples above were split out. `setupFramework()` now builds all three via `buildSharedBlock()` once and writes it under its own fixed `<!-- aiflow-kit-start:shared -->` marker; per-framework blocks (`buildToolBlock(tool, ..., { includeShared: false })`) carry only the framework-specific rules and (for inline tools) the inlined gate-workflow body. The "Installed workflow files" note moved to the shared block because its 3 listed paths (`.aiflow/instructions/gate-workflow.md`, `create-spec-workflow.md`, `create-testcase-workflow.md`) are always the same 3 filenames regardless of framework — only their on-disk *content* varies per framework (e.g. ML vs standard gate workflow), not the pointer text itself. Re-running for an already-present framework upserts its block in place (new `upsertMarkerBlock()` helper) instead of appending another copy. Single-framework projects are unaffected (`includeShared` defaults to `true`, same single block as before). Measured on the kit's own dogfood project (spring-boot + php, ~46 real skills): 452 → 444 lines.

- **QnA-Log table (`skill-ba-qna-template-v1.md`) gained 3 response-tracking columns — Người trả lời, Ngày trả lời, Nguồn.** `skill-ba-qna-v1.md`'s Bước 4 now spells out how each is filled: **Người trả lời** defaults to `git config user.email` (fallback `user.name`) of whoever is running the session, overridden only when the BA explicitly names a different responder (e.g. answering on the customer's behalf); **Ngày trả lời** is stamped automatically from the current system date (`dd/mm/yyyy`), never asked; **Nguồn** is always BA-entered manually (e.g. "Khách hàng", "Nội bộ team", "Team Marketing") with no default or inference. Questions still **Open** leave all three columns blank (`—`). Checklist gained a matching item to catch missing values on **Confirmed** rows.

### Fixed

- **`ak task next` treated `ingest-data` as a 2-gate flow** — a stale assumption left over from before Gate 3 (task creation & ticket generation) was added to `ingest-data` earlier in the same release cycle. `scripts/task.js` grouped it with `gen-doc`/`create-system-requirement` (`maxGate = 2`), so pausing via `ak task next` on Gate 2 would prematurely mark the task `status: 'done'` and `gateLabel(3, 'ingest-data')` returned `'Done'` instead of `'Sinh Task & Tạo Ticket'`. Split into its own 3-gate branch (`maxGate = 3`); `gen-doc`/`create-system-requirement` are unaffected.

## [0.2.0] - 2026-08-04

### Added

- **`create-system-requirement` — new task type, bridging UC Spec (BA) into a Dev-facing System Requirement.** Until now, "System Requirement" only existed as whatever a coding ticket's Gate 1 (`read-study-requirement`) happened to write into its own per-ticket `requirement.md` — no single document traced 1-1 to a UC Spec version, so N tickets under one `functionId` (including bug fixes) left no coherent, BA-reviewable picture of what the system as a whole is required to do. New skill `custom/skills/create-system-requirement/SKILL.md` runs as its own 2-gate task type, scoped to a `functionId` (not a ticket):
  - **Gate 1 — Investigate UC & Draft:** resolve the current UC Spec version, investigate existing source code/error-handling conventions (same methodology as `read-study-requirement`, including the GitNexus MCP shortcut), translate every Main/Alternative/Exception Flow step and Business Rule into Functional/Non-Functional Requirements, Validation Rules, Exception & Error Handling, and Acceptance Test scenarios (Given/When/Then) — every item carries a traced UC reference, nothing is invented. Q&A loops one question at a time until every Fact/Assumption/Gap is Confirmed; a genuinely unanswerable Gap blocks progress to Gate 2 rather than being guessed.
  - **Gate 2 — Finalize & Approve:** decide single-file vs. split (default is one file, mirroring the UC Spec 1-1; splits only on measurable signals — business-rule domain fan-out, module/service fan-out, flow-count overload, or a ~400-line size ceiling, always along a semantic seam, never by raw line count; a UC Spec that reads like 2+ bundled independent use cases is escalated back to BA instead of silently split), write `AK-Docs/04.Coding/01.Requirements/[functionId]/System-Requirement_v{N}.md` (`N` pinned to the UC Spec version it was traced against, carried in a mandatory `UC-Spec-Version` header), and wait for `APPROVED`.
  - Selectable via `ak use`'s "Task type:" prompt ("📐 Create System Requirement") or auto-detected by `aiflow prompt` — added to `scripts/detect.js` (keywords), `scripts/use.js` (both task-type selectors), and `scripts/task.js` (`maxGate = 2`, custom gate labels, alongside `gen-doc`'s existing 2-gate handling).
- **Coding Gate 1 (`read-study-requirement`) now requires System Requirement to exist and match the current UC Spec version before it can run.** New blocking Step 0: resolves the ticket's `functionId`, locates its current UC Spec, and checks for a `System-Requirement_v*.md` whose `UC-Spec-Version` header matches. Missing or stale → Gate 1 cancels outright and tells DEV to run the new `create-system-requirement` task type first (`⏸️ Gate 1 cancelled — run "ak use" and pick "📐 Create System Requirement" for [functionId] first...`); this check runs even in Fast Track mode (it's a 2-file header check, not a heavy investigation). Root `CLAUDE.md`'s Gate 1 section gained a matching "0. Pre-check (blocking)" line.
  - Once unblocked, Step 1 now reads the System Requirement as mandatory input (`FR-*`/`NFR-*`/`VR-*`/`ER-*` item IDs are referenced, not restated), and a new **Step 3.5 — Reconcile with System Requirement** requires every ticket's scope to trace to an existing item, a UC-Spec-backed case System Requirement missed (proposed as a diff for DEV to confirm, appended with a Change Log row — never written directly, never bumping `System-Requirement-Version`), or a stop-and-ask when a ticket's scope traces to neither document at all.
- **Memory recall now has a profile for `create-system-requirement`.** `scripts/hooks/session-start.js`'s `inferWorkflow()` previously had no mapping for this task type (it would fall through to `null` → the generic `gen-doc` default), so memory entries tagged for it would never score the `workflows`-match bonus in `memory-store.js`'s `scoreMemory()`. Added the mapping, plus a guidance row in `docs/common/Memory-Architecture-v1.0.md`'s workflow-profile table (§5.2) — `domain` + `glossary` + `architecture`/`lessons-dev` + related `decisions` — since this task type bridges BA business language and Dev technical convention rather than sitting fully in either camp.
- **`ingest-data` — new task type for PM/BrSE/Comtor, ingesting customer communication into `AK-Docs/01.QnA/`.** Until now the only way link/text content from Backlog or SharePoint reached `AK-Docs` was a developer manually editing `QnA-Log.md` — no fetch, no classification, no drafted trace fields. New skill `custom/skills/ingest-data/SKILL.md`, wired as a 2-gate task type in `custom/templates/shared/gate-workflow.md`:
  - **Gate 1 — Fetch, Classify, Draft:** resolves the source (Backlog ticket/comment/Document/Wiki link, Jira ticket/comment link, SharePoint link, or plain pasted text — via `ak fetch-links`, see below), classifies it into `QnA-Log.md` / `Meetings-Log.md` / `Confirmations-Log.md`, and drafts the entry with trace fields (`Nguồn`, `functionId`, `Người tổng hợp`, `Người approve tại nguồn`). When the target log is ambiguous — most notably Confirmations vs. regular feedback, a rule PM has not yet finalized (see `docs/internal/PM Workflow_v1.0.md` "Vấn đề còn mở" #1) — it asks instead of guessing. Displays the full draft (never summarized) and loops on edits until `APPROVED`.
  - **Gate 2 — Branch + Merge Request:** writes the approved entry to `AK-Docs/01.QnA/{QnA-Log,Meetings-Log,Confirmations-Log}.md` (creating the file with its header template if it doesn't exist yet), then reuses the existing `ak docs branch`/`ak docs submit` (no new Git-writing code) behind the same explicit-confirmation gate every other docs-writing flow uses.
  - Selectable via `ak use`'s "Task type:" prompt ("📥 Ingest Data" — new `PM` category). Output paths documented in `custom/rules/project-conventions.md` as a new, flat (non-`[functionId]/[ticketId]`) section, since these are project-wide logs, not per-ticket documents.
  - Deliberately keeps `AK-Docs/01.QnA/` as the folder name rather than renaming to `01.Communications/` per the still-undecided proposal in `docs/internal/PM Workflow_v1.0.md` §1 — avoids a breaking rename on projects already using `01.QnA/QnA-Log.md` (e.g. the `ast-ai-agent` pilot). `docs/common/Docs-Management-Flow.md` §3's scope table now explicitly lists `01.QnA/` alongside `02.BA-Specs/`/`03.Testing/`/`04.Coding/`/`99.Memory/` as requiring the branch+MR flow.
- **`link-resolver.js` / `ak fetch-links` now fetch Backlog Document and Wiki links, not just ticket/comment — built for `ingest-data`, reusable anywhere.** `classifyLink()` gained a `kind` field (`ticket` | `document` | `wiki` | `unsupported`) and two new URL patterns: Backlog Document permalinks (`/document/{id}`, `/alias/document/{id}#comment-{id}`) and Wiki permalinks (`/alias/wiki/{id}`). New fetchers `fetchBacklogDocument`, `fetchBacklogDocumentComment`, `fetchBacklogWiki` call the same read-scoped `BACKLOG_API_KEY` already used for tickets — no new credentials needed. ⚠️ The Document API (`/api/v2/documents/:id`) is a genuinely new Nulab endpoint (added 2026) and its exact path has **not been verified against a live Backlog space** — expect to adjust it if it 404s. Also added `SHAREPOINT_RE` so a `*.sharepoint.com` URL is recognized and returns a clear `{ sourceType: "unsupported", reason: "sharepoint-not-configured" }` stub (with guidance to paste text instead) rather than the generic "not a recognized URL" error — SharePoint still has no real connector (Microsoft Graph API/OAuth is unbuilt, see `docs/internal/PM Workflow_v1.0.md` "Vấn đề 4").
  - Auto-resolution of links found inside a ticket description (`ak use`'s `resolveLinks`, capped at 5) is **unchanged in scope** — `scanLinks()` now explicitly filters to `kind === 'ticket'` only, so Document/Wiki/SharePoint links are never auto-fetched en masse, only via an explicit single `ak fetch-links <url>` call.
- **`ak use` now captures `projectId`/`projectKey` from the loaded Backlog/Jira ticket.** `buildContextFromBacklog`/`buildContextFromJira` in `scripts/use.js` read `issue.projectId` (Backlog) and `fields.project.id`/`fields.project.key` (Jira), falling back to parsing the key out of the ticket ID (`PROJ-33` → `PROJ`) via a new `projectKeyFromIssueKey()` helper. Persisted into `.aiflow/context/current.json` and `.aiflow/state.json` (`current_context_project_id`/`current_context_project_key`), and shown in the `ak use` summary output. This is a read-only, informational addition — no code yet uses it to pick a Backlog/Jira project when creating a new ticket (that remains future work, tracked as "Vấn đề 5.1" in the PM Workflow doc).

### Fixed

- **`ak use`'s "Task type:" selector crashed on every invocation once "📐 Create System Requirement" was added to the list.** `td()` (`scripts/use.js`) looks up `CATEGORY_COLOR[cat]` and calls it as a chalk styling function; the `"Dev"` category used by the Create System Requirement entry had no entry in `CATEGORY_COLOR`, so building the choices array threw `TypeError: CATEGORY_COLOR[cat] is not a function` before the prompt could even render — meaning `ak use <ticket>` and `ak use --manual` were both broken outright. Added `Dev` (and `PM`, for the new `ingest-data` entry) to `CATEGORY_COLOR`.

---

## [0.1.9] - 2026-08-04

### Added

- **Codex (OpenAI) support — `ak init --env codex`.** One install covers all three local Codex surfaces, since they share the same `CODEX_HOME` config, skills and MCP setup: the **Codex IDE extension** (VS Code / Cursor / Windsurf), **Codex mode in the ChatGPT desktop app**, and the **`codex` CLI**. Generated artifacts:
  - **`AGENTS.md`** — the instruction file Codex reads automatically at the repo root. Registered as the `codex` entry in `AI_TOOL_FILES` (`scripts/init.js`), so `ak update`, `ak sync-skills` and `ak remove` pick it up through the paths they already use.
  - **`.codex/skills/`** — a mirror of `.claude/skills/`. Codex discovers any directory under it containing a `SKILL.md` with `name`/`description` frontmatter, which is the exact layout the kit's skills already use, so all 44 skills are indexed and auto-triggered with no rewriting. Four entry-point skills are added on top: `ak-coding`, `ak-create-spec`, `ak-create-testcase`, `ak-ask`.
  - **`.codex/config.toml`** — project-scoped Codex config. MCP servers are mirrored from `.mcp.json` into `[mcp_servers.<id>]` tables (`command` / `args` / `env`), so Backlog, Jira, Figma and GitNexus work in Codex exactly as they do in Claude Code. Regenerated by `ak init`, `ak update` and `ak sync-skills` after adapters and GitNexus have registered their servers.
  - **`.aiflow/instructions/`** — `gate-workflow.md` (resolved per framework, so `python-ml` gets the ML variant), `create-spec-workflow.md` and `create-testcase-workflow.md`.

- **Pointer layout for instruction files (`AI_TOOL_LAYOUT` / `resolveToolLayout()` in `scripts/init.js`).** Codex truncates the combined `AGENTS.md` chain at `project_doc_max_bytes` — **32 KiB by default** — and the assembled workflow set is ~115 KB, so inlining it the way `CLAUDE.md` does (132 KB for a React project) would have silently cut the instructions off mid-gate with no error. Tools are now either `inline` (all existing tools — unchanged behaviour) or `pointer` (Codex): a pointer-layout file carries the tool header, framework rules and a compact skill **name** list, then links to `.aiflow/instructions/` for the workflows themselves. Measured on a React project: `AGENTS.md` is 20 KB against a 32 KiB floor, versus 132 KB inlined.
  - The skill **registry table** is also replaced by a name-only list for pointer tools — Codex already indexes every skill's name and description from `.codex/skills/`, so restating them cost ~11 KB of doc budget per turn for nothing.
  - `.codex/config.toml` additionally raises `project_doc_max_bytes` to 128 KiB as headroom for multi-framework projects, which append one block per framework.

- **`ak doctor` — Codex health section.** Runs when `codex` is among the project's configured tools. Verifies `AGENTS.md` exists and fits the *active* byte budget (parsed from `.codex/config.toml`, falling back to Codex's 32 KiB default), that `.codex/skills/` holds all four entry points, that the three `.aiflow/instructions/` workflow files are present, and that `.codex/config.toml` has not drifted from `.mcp.json`.

### Changed

- **`ak remove`** now deletes `.codex/skills/`, and `.codex/config.toml` **only when it still carries the `# ai-flow-kit managed` header** — a hand-edited config is left in place. `.codex/` itself is removed only if nothing of the developer's remains in it. The same rule applies on write: if `.codex/config.toml` exists without our header, `ak init` leaves it untouched and saves the generated version to `.aiflow/reference/codex-config.toml` to merge manually.
- **`ak use`** next-steps output now lists Codex under both CLI and IDE, and warns that Codex has no session-start hook — a ticket loaded with `ak use` is only picked up by a **new** Codex session, otherwise run `/ak-coding` in the open one.
- **`.gitignore`** gains `AGENTS.md` and `.codex/` via `ensureAiflowGitignored()`.
- **`-e, --env`** help text now lists all five tools (`claude,cursor,gemini,copilot,codex`) in `bin/aiflow.js` and `ak guide --commands`.

### Fixed

- **Critical: `ak init` / `ak update` duplicated AI instruction file content on every run for multi-framework projects.** `setupFramework()` (`scripts/init.js`), when a project had 2+ frameworks selected (`state.frameworks.length > 1`), fell into a code path that blindly ran `fs.appendFile(targetPath, separator + frameworkContent)` on `CLAUDE.md` / `GEMINI.md` / `.cursorrules` / `.github/copilot-instructions.md` whenever the file already existed — with no marker or dedup check. Every `ak init`/`ak update` re-run re-appended each framework's conventions to the end of the file, so the file grew without bound run after run (confirmed via reproduction: 96,591 bytes → 112,699 bytes → unbounded across repeated runs). The same code path also silently **dropped the first selected framework's conventions entirely** (`if (!multi && frameworkContent)` excluded it whenever more than one framework was selected), so multi-framework projects never actually got that framework's rules written at all.
  - **Fix:** each framework now gets its own self-contained marker block per tool file — `<!-- aiflow-kit-start:<framework> --> ... <!-- aiflow-kit-end:<framework> -->` — instead of an unmarked append. On re-run, if that framework's block already exists it is replaced in place via regex instead of appended again, mirroring the idempotent single-framework update path. Removed the `!multi` condition that excluded framework content from multi-framework output.
  - No signature or call-site changes — `init.js`, `update.js`, and `bin/aiflow.js` all call `setupFramework()` the same way; only its internal multi-framework branch changed.
  - Single-framework projects were never affected — that path already fully overwrote the marker block (with a `.aiflow/bk/` backup) on every run.

- **Gate 4/5 of the TESTER workflow pointed at skill paths that do not exist in a scaffolded project.** `custom/templates/shared/gate-workflow.md` told the AI to read `custom/skills/test-skills/execute-flow/SKILL.md` and `custom/skills/test-skills/script-sync/SKILL.md` — both wrong twice over: `custom/` is the kit's own repo layout, not the project's, and neither skill lives under `test-skills/`. Corrected to `.claude/skills/execute-flow/SKILL.md` and `.claude/skills/script-sync/SKILL.md`, which is where `ak init` actually deploys them. This also unbreaks `tests/init-skill-paths.test.js`, which had been failing on exactly this.

- **`/coding` could not find the workflow under a pointer-layout instruction file.** `custom/templates/shared/coding-workflow.md` step 3 only looked for the `## [DEV] 5-Gate Development Workflow` heading inside the instruction file itself; under Codex that section lives in `.aiflow/instructions/gate-workflow.md`. It now checks that path first and falls back to the instruction file.

### Removed

- **`review-checklist.md` / `ml-review-checklist.md` / `java/review-checklist.md`** — the plain-prose "tick each item" checklist read at Gate 4 (`review-plan` skill and every Gate-4 template). Unlike the `gate-review` skill's `.aiflow/review/gate-N-*.md` checkbox files — which `ak review check` actually parses and hard-blocks `APPROVED` on (unchecked items or unresolved comments) — this checklist had no CLI verification at all; the AI was only told to "tick" it, so nothing enforced that it was ever genuinely checked. Deleted all 3 files under `custom/rules/`, and removed every "Tick `custom/rules/review-checklist.md`" step from the Gate 4 mandatory order: `custom/templates/shared/gate-workflow.md` (DEV), `custom/templates/shared/ml-gate-workflow.md` (ML), `custom/skills/review-plan/SKILL.md` (also dropped its "Review Checklist" table column, the fast-mode 3-item checklist, and the summary's `Review Checklist` section + `Checklist: [N/N]` line), `scripts/prompt.js` (bug-fix/feature/refactor templates), and root `CLAUDE.md`. Cleaned up remaining mentions in `custom/rules/project-conventions.md`, `custom/rules/ml-conventions.md`, `AIFLOW.md`, `docs/common/AIFLOW.md`, and `docs/internal/{IMPLEMENTATION_SUMMARY,architecture,developer-overview}.md`.
  - Gate 4 now ends with the AI creating the review/summary doc and the developer manually reading it before typing `APPROVED` or `BUG: ...` — no separate checklist artifact. The `gate-review` checkbox-enforcement mechanism itself is untouched and still runs at every gate of every workflow (DEV/TESTER/EXECUTE/BA/QA).
  - Historical mentions in `plan/ml-skill-set/` and `upgrade-plan/` were left as-is (accurate at time of writing).

---

## [0.1.7] - 2026-07-20

### Added

- **`/ak-ask "<question>"` slash command** — new `.claude/commands/ak-ask.md`, installed alongside `/create-spec`, `/create-testcase`, and `/coding` (via `scripts/init.js`'s `setupClaudeCommands`, also refreshed by `ak update`). Explicit, unambiguous trigger for the `aiflow-help` self-help skill: whatever follows `/ak-ask` is treated as a question about ai-flow-kit itself (install, roles, folder structure, CLI, memory workflow), not the developer's active ticket — no `AKQ:` prefix or keyword match needed. Reuses the same doc lookup as `aiflow-help`/`ak ask`: reads `docs/common/INDEX.md`, cites the file it answered from, and says plainly when a topic isn't documented instead of guessing.
- **`Docs-Management-Flow.md` promoted from `docs/internal/` to `docs/common/`** — the `AK-Docs`/`Shared-Docs` branch + Merge Request workflow doc (who can merge to `main`, which steps are self-review vs. PM-review) now ships to every project too, cross-linked from `INDEX.md`. Its own header still says `Trạng thái: Draft — chờ PM review`, so `ak-ask`/`aiflow-help` should flag that status rather than presenting it as finalized policy. Repointed `bin/aiflow.js`'s `docs` command and `scripts/docs-branch.js` from `docs/internal/...` to `docs/common/...`.
- **`Project-Structure.md`, `BA-Specs-Structure.md`, `Coding-Structure.md`, `Testing-Structure.md`, and `Memory-Architecture-v1.0.md` promoted from `docs/internal/` to `docs/common/`** — these now ship to every project (`.aiflow/docs/`, via `copyDocsToProject`) instead of staying npm-package-only, so `aiflow-help`/`ak ask`/`/ak-ask` can actually answer the "full `AK-Docs/` folder-structure reference" question that `docs/common/INDEX.md` previously listed as undocumented. `INDEX.md` gained a topic-map row for each file; all in-repo references (`README.md`, `custom/rules/project-conventions.md`, the DEV/BA/QA gate workflow templates, `review-plan`, the memory CLI/hook source comments, the `99.Memory/MEMORY.md` skeleton) were repointed from `docs/internal/...` to `docs/common/...`. `Memory-Architecture-v1.0.md` is a v1.1 architecture doc describing 4 operating flows end-to-end — only Phase 1 (`ak memory draft/list/submit/remove`) is actually implemented; the rest is roadmap, not shipped behavior, so `ak-ask`/`aiflow-help` must say so rather than imply the full doc is live. Historical release notes (`docs/internal/releases/`) and past changelog entries still say `docs/internal/...` and were intentionally left as-is (accurate at time of writing).
- **`99.Memory/` Project Brain — Phase 1** (`docs/internal/Memory-Architecture-v1.0.md`, v1.1). A git-based, human-approved team knowledge base living inside `AK-Docs/99.Memory/`, replacing the legacy `.aiflow/memory/` JSON store whose only "auto-load" function was dead code no hook ever called. AI now accumulates lessons/facts/decisions across tasks, scored and recalled automatically at session start.
  - **`scripts/memory-store.js`** — new engine: `99.Memory/` skeleton bootstrap; `mem-<functionId>-<slug>` id scheme with folder-per-functionId layout (`_global/` for cross-project facts, flat for `glossary`/`decisions`); hand-rolled frontmatter parse/serialize (no new YAML dependency); dedup-aware draft creation (a repeated slug in the same folder surfaces as a conflict instead of silently duplicating); the §5.2 scoring formula (folder/workflow/tag match, confidence, staleness decay, pending penalty); the Layer-2 relevant-set loader (top-N within a token budget); a local hit-count ledger. Deliberately **dependency-free** (no `fs-extra`/`chalk`) — this file is copied standalone into `.claude/lib/memory-store.js` in every project so the session-start hook can `require()` it without the kit's own `node_modules`.
  - **`scripts/memory.js`** — full rewrite: `ak memory draft|list|submit|remove`, replacing the old `save/get/list/search/delete/clear`. `submit`/`remove` reuse `scripts/docs-branch.js`'s existing branch-then-MR mechanism — same "AI drafts, human approves via Merge Request" model already used by `ak docs branch`/`ak docs submit`.
  - **`scripts/hooks/session-start.js`** — new step: injects Layer 1 (`MEMORY.md` index, always) + Layer 2 (top-N scored memories relevant to the active ticket's functionId/workflow/tags, budget-capped) into session context. Pulls `AK-Docs` with a short timeout first; a failed/offline pull only logs a warning and falls back to the local copy, never blocks the session.
  - **`scripts/init.js` / `scripts/update.js`** — auto-bootstrap the `99.Memory/` skeleton and gitignore its `_pending/` folder (local-only drafts) the first time `AK-Docs` is present. Both are committed locally on whatever branch is checked out but **never auto-pushed**, since `main` is a protected branch and pushing is left to a human.
  - **`custom/templates/memory/`** — `99.Memory/` skeleton tree, the memory-item frontmatter template, a GitLab MR template, a `CODEOWNERS` snippet, and reference `memory-lint`/`memory-finalize` CI job YAML (copyable snippets for a project admin to wire into a live pipeline — not auto-applied, no live GitLab project to attach them to from the kit itself).
  - **New "Retrospect + propose memory draft" step** added to all 4 Gate workflows — `review-plan` (Gate 4), `create-spec-workflow` (Gate 4), `create-testcase-workflow` (Gate 4), and `gate-workflow`'s gen-doc flow (Gate 2). Human review feedback (`BUG: ...`, `REVISION: ...`) is captured as a memory draft **immediately when given**, before the fix/update — not deferred to a generic end-of-gate retrospective where it could get lost or diluted.

### Changed

- `.aiflow/memory/` (JSON key/value store) and its `save/get/search/delete/clear` commands are retired outright — superseded by `99.Memory/`, no backward-compat shim (nothing else in the kit read that store).

## [0.1.6] - 2026-07-13

### Added

- **Mandatory Source & Docs sync at the start of every Gate — across DEV, TESTER, EXECUTE, BA, and QA workflows.** Previously, `git pull` for `AK-Docs`/`Shared-Docs` only ran via the `ak init` / `ak update` CLI commands (`scripts/docs-repo.js`), and the source repo itself was only synced once — inside the DEV workflow's Gate 1 pre-flight bullet. Now every Gate of every workflow syncs both the source repo and the docs repos before doing anything else:
  - **New shared procedure — "Pre-flight — Đồng bộ Source & Docs":** (1) `cd` into the source repo itself (not just the outer workspace) → `git status --porcelain`, then `git pull --ff-only` if the working tree is clean (skipped silently if dirty, diverged, or no remote tracking branch); (2) `cd` into `AK-Docs/` (sibling folder at workspace root) → `git pull`; (3) `cd` into `Shared-Docs/` (sibling folder at workspace root) → `git pull`; (4) `cd` back to the original working directory before continuing the gate.
  - **Failure handling:** if any `git pull` in the procedure fails (conflict, no remote, network, etc.), the AI does **not** block or stop the workflow — it shows a `⚠️ CẢNH BÁO` warning to the user and continues the gate with the current local data.
  - **`custom/templates/shared/gate-workflow.md`** — added the shared procedure once under the mandatory intro; wired a short pointer to it into every gate of all 3 workflows it defines: `[DEV]` 5-Gate (Gates 1–5), `[TESTER]` 4-Gate (Gate 1, Phases 2a/2b/2c/2d, Gates 3–4), and `[EXECUTE]` 4-Gate (Gates 1–4). The old DEV Gate 1 bullet that only synced the source repo now points at the shared procedure instead of duplicating a narrower version of it.
  - **`custom/templates/shared/create-spec-workflow.md`** (`[BA]` 4-Gate Spec Creation) — added the shared procedure near the top and a pointer to it at the start of Gates 1–4.
  - **`custom/templates/shared/create-testcase-workflow.md`** (`[QA]` 4-Gate TestCase Creation) — added the shared procedure near the top and a pointer to it at the start of Gates 1–4.
  - If `AK-Docs/` or `Shared-Docs/` doesn't exist at the workspace root, or isn't a git repo, that step is skipped silently (no warning) — the project may not use a separate docs repo.
- **New task type `gen-doc` — "Generate Document" 2-Gate flow** (`!34 feature/new_task_type`). A lighter flow for ad-hoc documentation tasks that don't need TDD/coding gates: Gate 1 (AI reads the request, plans the document — outline, scope, output format, sources) → APPROVED → Gate 2 runs immediately (generates the document, self-reviews, writes a task summary, then auto-closes the task — no Gate 3/4/5).
  - `scripts/detect.js` — new keyword set (`gen-doc`, `generate doc`, `tạo tài liệu`, `flow document`, …) so free-text task descriptions can auto-detect this type.
  - `scripts/use.js` — new picker entry "📝 Generate Doc 2 Gate" in the manual task-type selector.
  - `scripts/task.js` — `gen-doc` capped at `maxGate = 2`; gate labels ("Generate Document" / "Done") and gate-history summary generation updated accordingly.
  - `scripts/prompt.js` (`ak prompt gen-doc`) and `scripts/hooks/session-start.js` (auto-start + fast-mode messages) — new gen-doc-specific instructions.
  - `custom/templates/shared/gate-workflow.md` — new `## gen-doc Task Type — 2-Gate Flow` section; `custom/rules/project-conventions.md` — new gen-doc output-path table; `docs/common/AIFLOW.md` / `cli-reference.md` — documented the flow and the new `ak p gen-doc` prompt type.
  - Initial output paths were `plan/[ticket-id]/requirement.md` / `output.md` / `task-summary.md` — since relocated to `AK-Docs/04.Coding/`, see **Changed** below.
- **Figma design integrated into the DEV Gate workflow (Gate 1→4)** (`!32 feature/figma-gate-workflow`). UI tickets now get Figma wired in automatically, no manual skill invocation:
  - **Gate 1** (`read-study-requirement`) detects a Figma URL (ticket description / `supplementaryContext[]` / asks DEV once), fetches the design **exactly once** via Figma MCP, and caches the shared artifact `design/` (`design-context.md` with layout/tokens/component list/image map, `nodes.json` raw cache, `images/`, `figma-manifest.json`).
  - **Gate 2** (`generate-spec`) reads the cached `design-context.md` (no second MCP call) and folds the component tree, design-token mapping, and an image-copy task into the TDD plan.
  - **Gate 3** (`figma-to-component`, new **Gate mode**) reuses the cached `nodes.json`, copies images to `public/assets/figma/`, and generates the components — again without re-calling MCP.
  - **Gate 4** (`review-plan`) adds a **Design Conformance Check**: compares the built UI against `design-context.md` region-by-region, against the actual rendered reference image, not just a text checklist (no-fabricate / no-omit / layout / color / typography / every component and image present).
  - Refresh: typing "reload figma" re-fetches at Gate 1 and overwrites the cached `design/` artifact.
  - **New anti-429 guard** — `scripts/hooks/figma-rate-limit.js`, a `PreToolUse` hook (installed by `scripts/init.js`) that throttles every `mcp__figma__*` call to 6 REST-call-units/60s (tunable via `FIGMA_RATE_LIMIT_UNITS`; `download_figma_images` counts as 3 units). It **sleeps rather than fails**, so calls are delayed, never dropped — needed because Figma rate-limits `get_figma_data`/image renders by **seat tier**, and a View/Collab-seat token gets only ~6 Tier-1 calls/**month** (effectively unusable) vs 10–20/min for a Dev/Full seat.
  - `docs/common/workflows/figma.md` — documents the Gate-by-Gate table above, the shared `design/` artifact layout, and a new "Rate limits (429)" section (seat-tier budget table, `Retry-After` triage, troubleshooting entry for immediate 429s).
- **`ak docs branch` / `ak docs submit`** — new CLI commands (`scripts/docs-branch.js`) so the AI can help create a `feature/<functionId>/<taskId>` branch in `AK-Docs`/`Shared-Docs` from `main` (`ak docs branch`) and commit + push + open a Merge Request (`ak docs submit --title ... --description ...`), auto-detecting GitLab/GitHub via the remote URL to run `glab mr create` / `gh pr create`, or falling back to a pre-filled manual MR link if neither CLI is installed. Both commands print the full plan and only perform any git write action when passed `--yes` — which the AI may only add after the developer has explicitly confirmed the plan in chat (otherwise, or with no interactive TTY, it's a no-op dry run). This keeps the same "AI never commits/pushes unasked" guarantee as the existing `block-git-write` hook, extended to a capability that hook can't cover.
- **`docs/internal/Docs-Management-Flow.md`** — new internal doc formalizing the `AK-Docs` branch/MR workflow for every role: `main` is protected, PM-reviewed-and-merged only; every other role (BA/Dev/QA/TL) updates docs on a `feature/<functionId>/<taskId>` branch created from `main`; a step-by-step table makes explicit which steps are self-review (the authoring role) vs. the single mandatory PM-review-and-merge gate. Generalizes the branch/MR model `Memory-Architecture-v1.0.md` §5.1 designed for `99.Memory/` to all of `AK-Docs`.

### Fixed

- **`aiflow prompt <type>` still emitted `plan/[ticket-id]/...` paths** — The 0.1.5 migration to `04.Coding/` (see below) updated `gate-workflow.md`, the skills, all 5 tool templates, and `session-start.js`, but missed `scripts/prompt.js`. Its `PROMPT_TEMPLATES` (used by `aiflow prompt feature|bug-fix|refactor|investigation|impact-analysis|testing|documentation` to build the copy-paste prompt for Cursor/Gemini/manual use) still hard-coded `Output plan/[ticket-id]/requirement.md` / `plan.md` / `summary.md`, contradicting the `custom/rules/project-conventions.md` override appended later in the same prompt — this was the root cause of `/plan` still appearing at the project root even on 0.1.5-beta.1. All 11 occurrences now point at the current `04.Coding/<section>/[functionId]/[ticketId].md` convention.
- **`ak init` still gitignored `plan/`** — `ensureAiflowGitignored()` in `scripts/init.js` added `plan/` to `.gitignore` on every init, reinforcing the deprecated convention. Removed; `04.Coding/` output now lives in `AK-Docs/` (see below) and isn't part of the source repo's `.gitignore` concerns.

### Changed

- **`gen-doc` and ML workflow output relocated from `plan/[ticket-id]/` to `AK-Docs/04.Coding/`.** Both `gen-doc` (2-gate, added this version — see **Added** above) and the ML 5-gate workflow (`ml-gate-workflow.md`, pre-existing) still wrote to the legacy `plan/[ticket-id]/requirement.md` / `output.md` / `task-summary.md` / `ml-problem.md` / `experiment-plan.md` / `eval-report.md` paths that the 0.1.5 Dev-workflow migration deliberately left untouched. Per user decision, neither gets its own AK-Docs section — both now reuse the **same** `01.Requirements/02.Plans/03.TDD-Notes/04.Reviews` folders as the standard Dev workflow (gen-doc only ever populates the first two; ML uses all it needs through Gate 4, folding the model card into the Gate 4 review doc). Both workflows now also require the same mandatory `functionId` confirmation at Gate 1 that DEV/BA/QA already had, which neither had before. Updated: `custom/templates/shared/gate-workflow.md` (gen-doc section) and `ml-gate-workflow.md`, `custom/rules/project-conventions.md` and `ml-conventions.md` (output-path tables + legacy-path deprecation notice extended to cover these), `scripts/prompt.js` (gen-doc template) and `scripts/hooks/session-start.js` (gen-doc fast-mode text), and 4 ML skills (`design-experiment`, `evaluate-model`, `explore-data`, `frame-ml-problem`) whose completion checklists still hard-coded the old paths independent of the rules-file override.
- **Branch/MR hooks wired into every workflow that writes to `AK-Docs`.** `create-spec-workflow.md` (BA), `create-testcase-workflow.md` (QA), `gate-workflow.md` (DEV + gen-doc), and `ml-gate-workflow.md` (ML) each now: (a) confirm `functionId`/`taskId` and create/checkout the `AK-Docs` branch `feature/[functionId]/[taskId]` **before** writing the first gate output (new Bước 0.5, right after the existing functionId pre-flight), and (b) at the final gate, submit that branch via `ak docs submit` — with the commit/MR title+description shown and explicitly confirmed by the user first — instead of the previous vague "lưu tài liệu lên remote (GitLab)" instruction. Every step is explicit that PM reviews and merges the MR; the authoring role never merges it themselves.

- **DEV workflow output relocated to `AK-Docs/04.Coding/`** — Per `docs/internal/Project-Structure.md` / `Coding-Structure.md`, `04.Coding/` (and its BA/QA siblings `02.BA-Specs/`, `03.Testing/`, `00.Project-Overview/`) belong under the `AK-Docs/` docs repo (a sibling of the source repo, synced via `scripts/docs-repo.js`), not directly at the source repo root. Updated all references across `CLAUDE.md`, `custom/rules/project-conventions.md`, `custom/templates/shared/gate-workflow.md`, the 5 tool templates, the DEV skills (`read-study-requirement`, `generate-spec`, `review-plan`, `gate-review`), `docs/common/AIFLOW.md` / `ai-integration.md` / `workflows/{bug-fix,feature}.md`, `scripts/hooks/session-start.js`, and `scripts/prompt.js`. `scripts/task.js` now resolves the coding dir via `resolveDocsRepoPath(PROJECT_DIR, 'AK-Docs')` (from `docs-repo.js`) instead of hard-coding the path, so `findTaskDocs()` / `detectCurrentGate()` look under `AK-Docs/04.Coding/` first, with the legacy `plan/<taskId>/` folder (at the source repo root) still checked as a fallback.

## [0.1.5] - 2026-07-01

### Added

- **Brainstorming Skill Integration** — Injected `superpowers:brainstorming` into Gate 1 of the BA Create Spec workflow, allowing the AI to actively clarify and brainstorm raw requirements from the backlog.
- **Mandatory `functionId` Check** — Enforced mandatory `functionId` checks at Gate 1 of all BA and QA workflows (e.g., `create-spec-workflow.md`, `create-testcase-workflow.md`). If missing in the ticket or backlog description, the AI stops and prompts the user to input the ID.
- **`/coding` slash command** — New `.claude/commands/coding.md`, installed alongside `/create-spec` and `/create-testcase`. Manually loads `.aiflow/context/current.json` and starts (or resumes) the `[DEV] 5-Gate Development Workflow` for `bug-fix` / `feature` / `refactor` / `investigation` / `documentation` tickets. Fixes a gap where those task types had no slash-command fallback: they relied solely on the `SessionStart` hook's auto-start message, which does not re-fire if a ticket is loaded with `ak use` while a Claude Code chat session is already open — leaving phrases like `"start"` with no effect since the AI was never given the ticket context. `ak use`'s "Next Steps" hint and the `gate-workflow.md` / `session-start.js` auto-start tips now also mention `/coding` as the manual fallback.
- **DEV workflow `functionId` Pre-flight (Gate 1 — Bước 0)** — The `[DEV] 5-Gate Development Workflow` now runs the same mandatory Pre-flight as the BA/QA workflows before writing any output. `functionId` is project-defined with no enforced format (`F-001_User-Login`, `AD06`, `UC-LOGIN` are all valid) and is resolved in priority order: (1) `functionId`/`screenId` field in `.aiflow/context/current.json`; (2) **inferred from the input** — when the task input includes a BA-delivered UC Spec file, the AI reads its content or its containing folder path (e.g. `02.BA-Specs/04.UC-Specs/[functionId]/`) and can consult `04.Coding/00.Overview/_Index.md` / `00.Project-Overview/Function-List.md`, then asks the DEV to **confirm** the candidate ("functionId của task này có phải là [X] không?"); (3) only when nothing can be inferred does it ask the DEV to provide the ID directly. The workflow MUST NOT continue without a `functionId`.

### Changed

- **DEV 5-Gate output migration: `plan/[ticket-id]/` → `04.Coding/`** — All coding/documentation task outputs now follow the `Coding-Structure.md` convention: `04.Coding/<section>/[functionId]/[ticketId].md` (folder per feature, file per ticket — one feature spans multiple tickets). Gate mapping: Gate 1 → `01.Requirements/`, Gate 2 → `02.Plans/`, Gate 3 → `03.TDD-Notes/` (new artifact: test list written before code + implementation notes), Gate 4 → `04.Reviews/` (replaces `summary.md`), Gate 5 → `05.Pull-Requests/` (new artifact: PR description with links to UC Spec / Test Case / Dev Plan, pushed to remote before creating the PR). Each gate also updates the `04.Coding/00.Overview/_Index.md` tracker (`F-ID | Ticket | Dev | Gate | PR`). The legacy `plan/[ticket-id]/` convention is deprecated. Updated across: `gate-workflow.md` (DEV section), `custom/rules/project-conventions.md` (mandatory override table), skills (`read-study-requirement`, `generate-spec`, `review-plan`, `gate-review`), all 5 tool templates (`claude.md`, `cursor.md`, `copilot.md`, `gemini.md`, `generic.md`), and docs (`AIFLOW.md`, `ai-integration.md`, `workflows/bug-fix.md`, `workflows/feature.md`). ML workflows (`ml-gate-workflow.md`, `ml-conventions.md`) are intentionally NOT migrated yet.
- **SessionStart hook no longer injects legacy `plan/` paths** — `scripts/hooks/session-start.js` used to inject `Output plan/TASK-xxx/requirement.md` into every auto-start / resume message, overriding whatever the instruction file said (the root cause of outputs still landing in `plan/` even after template updates). The injected Gate 1 instructions (fast + full mode) now include the functionId Pre-flight step and point to `04.Coding/01.Requirements/[functionId]/<taskId>.md`; Gate 2/3 resume messages reference the new paths via the `04.Coding/00.Overview/_Index.md` tracker lookup.
- **CLI task commands follow the new doc layout** — `scripts/task.js`: new `findTaskDocs()` helper scans `04.Coding/*/*/<taskId>.md` (plus the legacy `plan/<taskId>/` folder) so `ak task reset` / `ak task remove` list and delete gate docs correctly; `detectCurrentGate()` now detects gate progress from the `04.Coding/` sections (with legacy fallback); `ak task next`'s cumulative `task-summary.md` moved from `plan/<taskId>/` to `.aiflow/tasks/<taskId>/` (it is internal task state, not a gate artifact).

- **Testing Skills Consolidation** — Consolidated all 11 testing/QA skills (previously at the root of `custom/skills/`) into the dedicated subfolder `custom/skills/test-skills/`. The skills moved are: `automation-testing`, `coverage-check`, `evidence-aggregation`, `execute-flow`, `generate-test-report`, `generate-testcase`, `log-bug`, `retest-orchestration`, `script-sync`, `test-analysis`, and `pr-impact-analysis`.
- **English Kebab-Case Naming Standard** — Standardized all skill filenames in `custom/skills/ba-skills/` and `custom/skills/test-skills/` to use English kebab-case naming conventions.
- **Output Directory Structure Migration** — Standardized output file templates, specs, and generated artifacts to use the new numbered directory architecture: `02.BA-Specs/`, `03.Testing/`, and `04.Coding/`.
- **Removed Generic Testing Task Type** — Deprecated and removed the generic "Testing" task type from the CLI task selector (`scripts/use.js`) to enforce usage of the more specialized `testcase` and `execute` workflows.
- **Reference Resolution** — Updated all hardcoded paths referencing relocated skills and output directories across `AIFLOW.md`, `CHANGELOG.md`, release notes, implementation plans, and gate workflow templates (`custom/templates/shared/gate-workflow.md`).
- **Test Alignment** — Updated mock directory paths in the Jest test suite (`tests/review.test.js`) to align with the new `02.BA-Specs` directory structure.

---

## [0.1.4] - 2026-06-29

### Added

- **`spec` task type — 4-Gate BA Workflow (Create Spec)** — New end-to-end spec creation workflow for Business Analysts. Activated when `taskType: "spec"` in context. Orchestrated by the `create-spec` skill across 4 gates:
  - **Gate 1 — Phân tích Yêu cầu Ban đầu**: AI reads ticket, classifies Facts vs Assumptions, identifies Gaps, generates a Q&A list for clarification. BA reviews → `APPROVED`.
  - **Gate 2 — Q&A Loop & Confirm**: AI iterates through each Q&A answer, updates analysis until all items are Confirmed. BA approves full Q&A → `APPROVED`.
  - **Gate 3 — Prototype Design**: AI generates HTML/CSS prototype for the main screens. BA reviews UI flow → `APPROVED`.
  - **Gate 4 — UC Spec hoàn chỉnh**: AI produces a complete UC Spec document (flows, business rules, validations, edge cases). BA reviews → `APPROVED`.

- **`testcase` task type — 4-Gate QA Workflow (Create Testcase)** — New structured test case creation workflow for QA engineers. Activated when `taskType: "testcase"` in context. Orchestrated by the `create-testcase` skill across 4 gates:
  - **Gate 1 — Phân tích Yêu cầu & Rủi ro**: AI reads ticket/spec, analyzes scope and risk, reads source code to discover hidden validation rules and business logic. QA reviews → `APPROVED`.
  - **Gate 2 — Xây dựng Scenarios & Checklist**: AI generates checklist grouped by Functional, Non-functional, Data & Integration, Regression. Checks Dev Artifacts (PR diff) via `pr-impact-analysis` skill to add regression TCs. Output: `test-plan/checklist.md`. QA reviews → `APPROVED`.
  - **Gate 3 — Thiết kế Test Case chi tiết**: AI generates full TC table (TC_ID, Steps, Expected Result) using BVA, Equivalence Partitioning, Decision Table, State Transition techniques. Output: `test-plan/test-cases/`. QA reviews → `APPROVED`.
  - **Gate 4 — Review & Tối ưu**: AI reviews coverage, removes duplicates, adds missing edge cases, exports final set to `test-plan/test-cases/final-testcases.md`. QA reviews → `APPROVED`.

- **BA Skills Library** (`custom/skills/ba-skills/`) — New collection of BA-specific sub-skills:
  - `skill-ba-phan-tich-ban-dau-v1` — Initial requirement analysis (Facts vs Assumptions, Gap Analysis)
  - `skill-ba-qa-v1` — Q&A generation and confirmation loop
  - `skill-ba-viet-spec-uc-v1` — UC Spec writing with flows, business rules, validations
  - `skill-ba-prototype-v1` — HTML/CSS prototype generation for UI screens
  - `skill-ba-ve-luong-mermaid-v1` — Mermaid flow diagram generation
  - `skill-ba-xay-dung-business-rules-v1` — Business rules extraction and structuring

- **Test Skills Library** (`custom/skills/test-skills/`) — New collection of 20+ QA sub-skills organized by category:
  - **Core**: `requirement-analysis`, `risk-analysis`, `test-scenario-builder`, `testcase-review`
  - **Test Design**: `boundary-value-analysis`, `equivalence-partitioning`, `decision-table`, `state-transition`, `pairwise`, `error-guessing`
  - **UI Testing**: `UI-layout`, `form-validation`, `navigation`, `localization`, `accessibility`
  - **Business Testing**: `CRUD-testing`, `workflow-testing`, `permission-testing`, `dependency-validation`, `notification-testing`, `calculation-testing`
  - **Data Testing**: `database-testing`, `import-export-testing`, `data-mapping`, `duplicate-handling`, `migration`
  - **Integration**: `API-testing`, `third-party-integration`, `batch-processing`, `file-upload-download`
  - **Domain Skills**: `CMS`, `Ecommerce`
  - **Review**: `coverage-review`, `knowledge-learning`, `repository-update`, `change-history`

- **`gate-review` skill** (`custom/skills/gate-review/SKILL.md`) — New gate review orchestration skill that enforces explicit `APPROVED` at each gate boundary across all workflow types (coding, execute, spec, testcase). Prevents silent gate advancement without QA/BA/DEV sign-off.

- **Gate review protocol in Execute Test Flow** — Gates 1, 3, and 4 of the execute-flow now explicitly require QA `APPROVED` before advancing. Gate 2 (Script Sync) is AI-only and advances automatically after sync completes.

- **`spec` and `testcase` options in `ak use` type selector** — Both the `promptForTaskType()` shared function and the `manualContext()` flow now include `spec` and `testcase` as selectable types, routing AI to the correct 4-gate workflow.

### Changed

- **`aiflow` CLI alias fully deprecated → use `ak`** — All documentation, README, QUICK_START, cli-reference, and guide output updated to use `ak` as the primary command. The `aiflow` command still works but shows a deprecation warning on every invocation.
- **README restructured** — "Overview Flow" section renamed to "Coding Flow"; Execute Test Flow merged into a single diagram (removed duplicate Vietnamese section); Create Spec Flow and Create Testcase Flow diagrams added.

---

## [0.1.3] - 2026-06-18

### Added

- **`execute` task type — 4-Gate Executing Flow** — New end-to-end test execution workflow for QA testers. Activated when `taskType: "execute"` in context. Orchestrated by the new `execute-flow` skill across 4 gates:
  - **Gate 1 — Pre-flight & Work Plan**: Validates TC file, `ak-test/{repo}/` directory, `BASE_URL` env var, and `playwright.config.ts` before any scripts are touched.
  - **Gate 2 — Script Sync**: Hash-based TC↔script sync via the new `script-sync` skill. Each TC is hashed as `SHA1(TC_ID + "|" + Steps + "|" + Expected Result)[:8]` and compared against the `@tc-hash` comment in the spec file. New TCs get scripts generated via MCP browser tools; changed TCs update their existing block; unchanged TCs are skipped entirely.
  - **Gate 3 — Execute & Evidence**: Runs `npx playwright test` and organizes evidence into `ak-test/{repo}/results/{screenId}/run-{N}/` with per-TC folders (screenshots, trace.zip, result.md). Auto-drafts bug files for failed TCs. Supports `RETEST: [TC_ID]` loop.
  - **Gate 4 — Report & Bug Logging**: Generates `testreport.md` with Go/No-Go decision; logs each failed TC to Jira/Backlog one-by-one with interactive confirm per bug.

- **`execute-flow` skill** (`custom/skills/test-skills/execute-flow/SKILL.md`) — 4-gate execute flow orchestrator. Handles 3 entry points: `ak execute TICKET-ID` (ticket with `taskType: "execute"`), `ak execute ./path/to/testcases.md` (direct TC file), and `ak execute` (manual — AI asks for TC file). Output structure: `ak-test/{repo}/scripts/{screenId}/{ScreenID}.spec.ts` for scripts; `ak-test/{repo}/results/{screenId}/run-{N}/` for evidence.

- **`script-sync` skill** (`custom/skills/test-skills/script-sync/SKILL.md`) — Hash-based TC↔Playwright script sync engine. Called from execute-flow Gate 2. Never fabricates selectors — uses MCP browser tools (`browser_navigate` → `browser_snapshot` → `browser_generate_locator`) for any new/changed TC. Produces one `.spec.ts` per screen with all TCs inside, using `screenId` (lowercase) for directory paths and `{ScreenID}.spec.ts` (uppercase) for the filename.

- **`playwright.config.ts` template** for execute-flow (`custom/skills/test-skills/execute-flow/templates/playwright.config.ts`) — Default config for each `ak-test/{repo}` repo with HTML + JSON reporters, screenshot-on-failure, and trace-on-failure. AI offers to scaffold this file during Gate 1 pre-flight if it doesn't exist.

- **`execute` entry in `gate-workflow.md` Workflow Selection table** — `gate-workflow.md` (single source of truth for all AI agent instruction files) now routes `taskType: "execute"` to the `[EXECUTE] Executing Flow` section. Distributed to all agents (Claude, Gemini, Cursor, Copilot) via `ak init` / `ak up`.

- **`▶️ Execute Test` option in `ak use` type selector** — Both the `promptForTaskType()` shared function (Backlog/Jira loaders) and the `manualContext()` manual entry flow now include `execute` as a selectable type. Users can run `ak use --manual` or `ak use TICKET-ID` and choose "Execute Test" to route the AI to the execute-flow.

- **`ak execute` command** (`ak ex` alias) — New top-level CLI entry point that bypasses `ak use`. Accepts a ticket ID, a TC file path, or no argument (AI asks interactively). Documented in README, QUICK_START, cli-reference, and `ak guide --commands`.

- **`test-analysis` skill** (`custom/skills/test-skills/test-analysis/SKILL.md`) — Gate 1 analysis skill for the [TESTER] workflow. Reads ticket context, fetches linked docs, analyzes scope and risk, asks clarifying questions one at a time, and writes `test-plan/test-analysis.md`.

- **`coverage-check` skill** (`custom/skills/test-skills/coverage-check/SKILL.md`) — Gate 2d skill that applies review action items, generates a requirement→TC coverage matrix, exports the final test case set to `test-plan/test-cases/final-testcases.md`, and invokes `automation-testing` to generate Playwright scripts.

- **`evidence-aggregation` skill** (`custom/skills/test-skills/evidence-aggregation/SKILL.md`) — Parses `test-results/results.json`, organizes screenshots and traces into `evidence/TC_[ID]-[scenario]/` folders, generates per-TC `result.md`, and auto-drafts `bugs/BUG-NNN-*.md` for failed TCs.

- **`retest-orchestration` skill** (`custom/skills/test-skills/retest-orchestration/SKILL.md`) — Handles the `RETEST: [TC_ID]` loop in Gate 3. Re-runs dev artifacts check (detect new commits), re-executes only specified TCs, creates `run-N/` subfolders (never deletes prior evidence), and updates bug status.

- **`pr-impact-analysis` skill** (`custom/skills/test-skills/pr-impact-analysis/SKILL.md`) — Checks for new commits/PRs between gates to ensure TC coverage stays current with dev changes.

- **`log-bug` skill** (`custom/skills/test-skills/log-bug/SKILL.md`) — Logs a failed TC as a bug ticket in Jira/Backlog with structured fields (severity, steps, expected/actual, evidence link).

- **Playwright harness scaffold** — `ak scaffold playwright` (via `scripts/scaffold-playwright.js`) creates the `ak-test/{repo}/` directory structure with `playwright.config.ts`, `tests/e2e/fixtures/test.ts`, `tests/e2e/pages/BasePage.ts`, `tests/e2e/support/auth.ts`, and `.env.example`. Covered by 90-line Jest test suite in `tests/scaffold-playwright.test.js`.

- **Playwright MCP preset** (`custom/mcp-presets/playwright.json`) — MCP configuration preset for browser automation tools used by `script-sync` during TC→script generation.

- **`test-patterns.md` rules file** (`custom/rules/test-patterns.md`) — Team-level Playwright patterns and conventions referenced by `automation-testing` and `script-sync` skills.

- **`generate-testcase` skill — Phase 2a/2b/2c structure** — Skill rewritten with explicit phased execution: Phase 2a (scenarios & checklist), Phase 2b (generate detailed TC table), Phase 2c (review & optimize). TC_ID format: `TC_[Module]_[NNN]`. Gate pauses after each phase.

- **`automation-testing` skill — MCP browser integration** — Updated to document MCP tool sequence (`browser_navigate` → `browser_snapshot` → `browser_generate_locator`) for generating reliable Playwright locators without fabricating selectors.

### Fixed

- **`execute-flow` Gate 1 pre-flight missing `playwright.config.ts` check** — Original Gate 1 had 3 checks; spec required 4. Added explicit check for `ak-test/{repo}/playwright.config.ts` with offer to scaffold from template.
- **`screenId` casing ambiguity in execute-flow/script-sync** — Directory paths use lowercase `screenId` (e.g. `ad10`); spec file names remain uppercase `{ScreenID}.spec.ts` (e.g. `AD10.spec.ts`). Both skills now explicitly document this distinction with examples to prevent AI from using wrong case.
- **`--reporter` CLI flag overriding config reporters** — Gate 3 run command previously included `--reporter=json,html` which overrides (not appends) reporters defined in `playwright.config.ts`, causing the HTML report to be replaced entirely. Removed the flag; reporters are now defined solely in `playwright.config.ts`.

---

## [0.1.2] - 2026-06-13

### Added

- **`python-ml` framework type** — New framework option for Python ML projects (scikit-learn / PyTorch / TensorFlow / Keras / MLflow / Wandb). Auto-detected from `requirements.txt` or `pyproject.toml` when any of the following dependencies are found: `torch`, `scikit-learn`, `sklearn`, `tensorflow`, `keras`, `mlflow`, `wandb`. Uses a dedicated gate workflow (`ml-gate-workflow.md`) tailored for ML iteration cycles (experiment → evaluate → iterate) instead of the standard software-development gate workflow. Select via `ak init` checkbox or `ak init -f python-ml`.
- **Task type selector in `ak use`** — After loading a ticket from Backlog, Jira, a local file, or manual entry, `ak use` now prompts the developer to confirm or change the task type via an interactive list (Bug Fix, Feature, Investigation, Refactor, Impact Analysis, Documentation). The type is auto-detected from the ticket title/issue type first and pre-selected as the default. The chosen value is saved to `.aiflow/context/current.json` as `taskType` and is available to the gate workflow throughout the session.
- **Telemetry warning on `ak use`** — If telemetry logging is not yet enabled, `ak use` now prints a yellow warning at startup so developers know their activity is not being tracked:
  ```
  ⚠  Telemetry logging is not enabled. Developer activity will not be tracked.
     Run: ak telemetry enable  to set up team productivity tracking.
  ```
  The check is wrapped in try/catch and never blocks the command. Silently skipped when telemetry is already enabled.
- **Backup before overwrite (`aiflow update` / `aiflow init`)** — Before overwriting any AI instruction file (CLAUDE.md, GEMINI.md, `.cursorrules`, `.github/copilot-instructions.md`), the current file is now backed up to `.aiflow/bk/YYYY-MM-DD_HH-MM_<filename>`. Multiple backups accumulate across runs, providing a full history to roll back to.
- **Single upfront confirm on update** — Instead of asking per-file, `aiflow update` and `aiflow init` now show a single summary of all files that will be overwritten, then ask for one confirmation before proceeding. This replaces the per-file prompt sequence that was easy to accidentally skip.

### Changed

- **Framework conventions included in single-framework CLAUDE.md** — Previously, the framework template (e.g. Spring Boot coding standards, architecture rules) was only appended to CLAUDE.md in multi-framework projects. Single-framework projects got only the tool header + skill registry + gate workflow, losing all stack-specific conventions. The framework template is now always embedded for single-framework setups.
- **`aiflow update` no longer wipes `.claude/` directory** — Previously `update` called `fs.emptyDir('.claude/')` which deleted `.claude/settings.json`, destroying the SessionStart/SessionEnd/PreToolUse hooks configuration. Update now empties only `.claude/skills/` and re-copies skills there, leaving `settings.json` and other files untouched.

### Fixed

- **Critical: `aiflow update` / `aiflow init` did not update CLAUDE.md or GEMINI.md** — Three compounding root causes:
  1. Old `state.json` wrote `framework: "spring-boot"` (singular string). New code read `state.frameworks` (plural array), got `undefined`, fell back to `[]`, and never called `setupFramework` — so no AI instruction file was ever written or updated.
  2. `aiflow init` called `setupFramework` without `force: true`, triggering per-file interactive prompts. Users who pressed No (or were surprised by the overwrite prompt) silently skipped the update.
  3. `aiflow update`'s old per-file confirm dialogs caused the same silent skip.
  All three are fixed: singular→plural fallback added everywhere `state.frameworks` is read; both `init` and `update` now use `force: true`; the update path is backup-then-overwrite.
- **Stale skill registry paths in CLAUDE.md** — After upgrading the package, CLAUDE.md still referenced `.aiflow/versions/0.1.1/skills/...` instead of the current `.claude/skills/...` paths. This caused Claude to fail when trying to load skills. Fixed as part of the forced-overwrite update flow above.
- **`state.framework` (singular) not recognized after upgrade** — `aiflow update`, `aiflow init` re-run, and `ak sync-skills` all read `state.frameworks` (plural). Projects initialized before the plural key was introduced had only `framework: "spring-boot"` in state.json, causing the framework to be silently dropped and `setupFramework` to never run. Fixed with a fallback: `state.frameworks || (state.framework ? [state.framework] : [])` in `update.js`, `init.js`, and `aiflow.js`.

---

## [0.1.1] - 2026-06-08

### Added

- **Ubuntu / Linux clipboard support in `ak prompt`** — `ak prompt` now copies to the clipboard on native Linux. It auto-detects the display server (Wayland → `wl-copy`, X11 → `xclip` → `xsel`) and the package manager (`apt-get` / `dnf` / `pacman` / `zypper`). When no clipboard tool is installed it prints a clear warning (`⚠ Clipboard tool not found (need: xclip)`), shows the exact install command, and offers to install it via `sudo` then retries the copy. If the user declines or no package manager is found, it falls back to printing the full prompt for manual copy. Previously the command silently failed on Ubuntu when neither `xclip` nor `xsel` was present.
- **`figma-to-component`: image detection & export** — The skill now scans the Figma node tree for image nodes (`fills[].type === "IMAGE"`, `VECTOR`/`BOOLEAN_OPERATION`, complex non-CSS groups), exports them via `download_figma_images` into `public/assets/figma/`, and records an `imageMap`. Generated components render those nodes with `<Image>` (Next.js) / `<img>` (React/Vue) instead of CSS `background-image`.
- **`figma-to-component`: MCP availability pre-check (Step 0)** — The skill now verifies `mcp__figma__get_figma_data` / `mcp__figma__download_figma_images` are connected before running, and stops with setup instructions (`aiflow init -a figma` / `-a figma-desktop`) instead of guessing design values from the URL.
- **`figma-to-component`: CSS tooling detection + design tokens** — Detection now branches on the project's styling approach (Tailwind / CSS Modules / styled-components / vanilla CSS) instead of hardcoding Tailwind, and prefers mapping Figma Styles/Variables to existing project tokens (Tailwind theme keys or CSS custom properties), falling back to arbitrary values only when no token matches.
- **`figma-to-component`: troubleshooting table** — Added a troubleshooting section covering MCP-not-connected, `403`/token rejected, request timeout (lower `depth`), `404` node-id, empty fills, and unsupported `download_figma_images`.

### Fixed

- **Critical: `figma-to-component` source/installed divergence** — The source skill (`custom/skills/figma-to-component/SKILL.md`) still referenced the non-existent tool names `figma_get_file_nodes` / `figma_get_file_styles` / `figma_get_image` and only had 2-tier framework detection, while the installed `.claude/` copy had been fixed in 0.0.9. The next `aiflow init` / `sync-skills` would have overwritten the working copy with the broken source — re-introducing the 0.0.9 bug. Both copies are now synced to a single canonical version: correct tool names (`get_figma_data` / `download_figma_images`), 4-tier framework detection (App Router / React / Vue / Angular), and the image-export step.

---

## [0.1.0] - 2026-05-28

### Added

- **Multi-target `ak use`** — `ak use` now accepts variadic targets so multiple sources can be loaded in a single call. The first target becomes the primary context (drives Gate 1); the rest are appended to `current.json` as `supplementaryContext[]`. Targets can be ticket IDs, Backlog/Jira URLs, or local files.
  ```bash
  ak use PROJ-33 PROJ-10 docs/arch.md
  # PROJ-33 = primary, PROJ-10 + docs/arch.md = supplementary
  ```
  Backward compatible: `ak use PROJ-33` (single target) behaves exactly as before.
- **Auto link resolution** — When the primary ticket's description contains Backlog/Jira URLs, `ak use` now auto-fetches them and appends to `supplementaryContext[]`. AI no longer misses linked context. Capped at **5 auto-resolved links per `use`** to keep loads fast; per-link errors are caught and logged without aborting the command.
- **Comment-aware link resolution** — Comment URLs are resolved to that **single comment** instead of fetching the whole ticket. Recognised patterns:
  - Backlog: `https://*.backlog.com/view/PROJ-10#comment-456`
  - Jira: `https://*.atlassian.net/browse/PROJ-10?focusedCommentId=456`
- **`ak fetch-links <url>` command** — Standalone command that fetches a single Backlog/Jira URL and prints a `SupplementaryContext` JSON object to stdout. Used by the `read-study-requirement` skill at runtime when AI encounters a link in the ticket description that wasn't already resolved at `use` time.
  ```bash
  ak fetch-links "https://company.backlog.com/view/PROJ-10#comment-456"
  ```
- **`supplementaryContext[]` schema in `current.json`** — New top-level array; each item has shape `{ sourceType: 'ticket'|'comment'|'file'|'text', sourceUrl?, sourcePath?, ticketId?, commentId?, title?, description?, content?, author?, date? }`. Persisted across sessions and consumed by the SessionStart hook.
- **SessionStart hook renders supplementary block** — `scripts/hooks/session-start.js` now emits a `**Supplementary Context (N source(s)):**` section in the AI context prompt, one line per item, content truncated at 1000 chars to keep token cost bounded.
- **`read-study-requirement` skill integrates supplementary context** — Gate 1 instruction file (custom + installed `.claude/skills/`) now has an explicit step to read `supplementaryContext[]` and use `ak fetch-links` for any unresolved links found while analysing the ticket.
- **`scripts/link-resolver.js` module** — New CommonJS module that owns all URL classification and HTTPS fetching for Backlog/Jira. Exports: `classifyLink`, `scanLinks`, `fetchBacklogTicket`, `fetchBacklogComment`, `fetchJiraTicket`, `fetchJiraComment`, `fetchLink`, `resolveLinks`. Accepts credentials as parameters to keep `use.js` free of circular imports.
- **Jest test suite** — Added Jest 30 as a dev dependency with `testMatch: ["<rootDir>/tests/**/*.test.js"]` to scope discovery to project tests (skips `upstream/tests/`). Suite includes `tests/smoke.test.js` and 20 unit tests in `tests/link-resolver.test.js` covering URL classification, scan, dedup, per-adapter fetch paths, and `resolveLinks` error isolation.

### Changed

- **`use.js` exports as named const** — `module.exports` shifted from anonymous function to `useCommand` with a `loadCredentials` property attached, so other modules (CLI `fetch-links` handler) can reuse credential loading without re-implementing it. External call shape (`useCommand(targets, options)`) unchanged for backward compatibility.

---

## [0.0.9] - 2026-05-25

### Added

- **`figma-desktop` adapter** — New MCP preset using the official `@figma/mcp-server` package (Figma Inc.). Requires Figma Desktop app installed and open. No API token needed — authenticates via Desktop session. Run `ak init -a figma-desktop` to set up. See [`custom/mcp-presets/figma-desktop.json`](../../custom/mcp-presets/figma-desktop.json).
- **Next.js App Router support in `figma-to-component` skill** — Detects App Router projects (via `nextjs-app-router` in `CLAUDE.md` or presence of `app/` directory). Defaults to Server Component (`export default async function`); adds `'use client'` directive only when the design has interactive states (hover, click handlers, form inputs).
- **Angular support in `figma-to-component` skill** — Detects Angular projects (via `angular` in `CLAUDE.md` or presence of `angular.json`). Generates standalone `@Component` class with `@Input() className` and computed `hostClasses` getter. Uses Tailwind if `tailwind.config.*` exists, otherwise CSS-in-component.
- **4-tier framework detection in `figma-to-component` skill** — Detection order: (1) `CLAUDE.md` identifier → (2) project file scan (`app/` dir, `angular.json`, `nuxt.config.*`) → (3) fallback to Next.js/React. Previously only supported React and Vue.
- **Figma workflow guide** — New developer guide at [`docs/common/workflows/figma.md`](figma.md) covering prerequisites (REST API vs Desktop), how to get node URLs, trigger commands, expected output format, review checklist, and troubleshooting table.
- **MCP presets documentation** — Added full Figma REST API and Figma Desktop sections to [`custom/mcp-presets/README.md`](../../custom/mcp-presets/README.md), including a side-by-side comparison table.
- **`ak gate N start|approved` auto-syncs task state** — Calling `ak gate 1 start --ticket PROJ-33` now automatically advances `currentGate` in `task-state.json`, removing the need to always call `ak task next` for gate tracking. `approved` records the approval timestamp and advances to the next gate. Uses `Math.max()` guard to never regress gate progress.
- **Session telemetry enrichment** — `session.start` now captures the active AI model name and user email from config. `session.stop` records model, input/output token counts, and a prompt summary extracted from the session transcript (`transcript_path` in hookData).
- **`project-conventions.md`** — New mandatory override file at `custom/rules/project-conventions.md`. Enforces that Gate 2 plans are always saved to `plan/[ticket-id]/plan.md` (overriding the skill default `docs/superpowers/plans/`). Includes a checklist and path table for all Gate outputs.
- **Gate workflow: explicit plan output path** — Gate 2 instruction in `gate-workflow.md` now explicitly states that the plan must be saved to `plan/[ticket-id]/plan.md`, with a note that the `writing-plans` skill default path is overridden.
- **WSL clipboard support in `ak prompt`** — `ak prompt` now correctly copies output to the Windows clipboard when running inside WSL using `powershell.exe Set-Clipboard`. Previously fell through to `xclip`/`xsel` which are unavailable on WSL without extra setup.
- **`appscript.js`** — Google Apps Script source for the self-hosted telemetry backend. Receives HMAC-signed events from the `ak` CLI, validates them, and appends rows to Google Sheets.
- **Telemetry `record()` returns result object** — `record()` now returns `{ok: true}` on success or `{ok: false, reason, error}` on failure, enabling `ak gate` and `ak telemetry log` to display ✓ / ⚠ feedback per event.
- **`ak init` remembers previous framework selection** — Re-running `ak init` in an already-configured project now pre-selects the previously chosen frameworks (read from `.aiflow/state.json`) instead of falling back to auto-detection. A "Previously selected: ..." hint is shown above the checkbox list.

### Fixed

- **Critical: `figma-to-component` skill used non-existent tool names** — The skill referenced `figma_get_file_nodes`, `figma_get_file_styles`, `figma_get_file_components`, and `figma_get_image` — none of which exist in `figma-developer-mcp` or any other MCP package, causing the skill to silently fail on every run. Replaced with the correct tools: `get_figma_data(fileKey, nodeId, depth=2)` and `download_figma_images(fileKey, nodes, localPath)`.
- **Figma API token verification using wrong auth header** — `verifyFigma()` in `scripts/init.js` was sending `Authorization: Bearer <token>`, which is only valid for OAuth tokens. Figma Personal Access Tokens (`figd_...`) require `X-Figma-Token: <token>`. This caused every PAT to be rejected as invalid during `ak init -a figma` even when the token was correct.
- **Critical: `currentGate` not advancing after gate transitions** — `task-state.json` was not updating `currentGate` when the AI called `ak gate N start`, so resuming a task always restarted from the wrong gate. Added dedicated `updateTaskGateState()` and fixed `createOrActivateTaskState()` to use `Math.max()`.
- **Duplicate `session.start` telemetry event** — `session-start.js` was calling `record()` before reading stdin, causing the event to fire twice in some hook configurations. Fixed by moving `record()` inside the `stdin.on('end')` handler.
- **Short command aliases not resolving for telemetry** — `task` and `memory` subcommand short aliases (`t st`, `t ls`, `mem s`, etc.) were not being resolved before telemetry pre-processing, causing `unknown` in the command column. Fixed alias resolution in the pre-hook telemetry mapping.
- **`ak telemetry log` silent on failure** — `ak telemetry log --event X` previously swallowed all errors silently (no output). Now shows ✓ on success and ⚠ with reason (`disabled`, `opted-out`, `no-url`) on skip/failure.
- **Gate telemetry blocked by bash redirect error** — AI was appending `2>$null` (PowerShell syntax) to `ak gate` commands when following "run silently" instructions, causing bash to fail with `/usr/bin/bash: $null: ambiguous redirect`. Added explicit "do NOT append shell redirects" instruction to `gate-workflow.md` for all gate telemetry commands.

---

## [0.0.8-beta.1] - 2026-05-14

### Fixed

- **Auto-commit bug — actually fixed this time.** v0.0.7 claimed to remove "all automatic `git commit` and `git add` instructions from key AI skills" but the commit (`d490dab`) only added documentation/warning lines and left the active instructions in place. This release does the real work:
  - Removed `4. Commit your work` from [.claude/skills/subagent-driven-development/implementer-prompt.md](.claude/skills/subagent-driven-development/implementer-prompt.md) (synced from upstream which had already been fixed).
  - Removed the `### Commit Strategy` section, `Estimated commits: [N]` line, and `MUST plan small, focused commits` rule from [custom/skills/generate-spec/SKILL.md](custom/skills/generate-spec/SKILL.md) — these were active in Gate 2 every run.
  - Removed `Commit the design document to git` and "and commit"/"committed to" wording from [upstream/skills/brainstorming/SKILL.md](upstream/skills/brainstorming/SKILL.md).
- **Hard guarantee via PreToolUse hook.** Added [scripts/hooks/block-git-write.js](scripts/hooks/block-git-write.js) that intercepts every Bash tool call and blocks `git commit`, `git add`, `git push`, `git tag`, `git reset`, `git rebase`, `git revert`, `git cherry-pick`, `git am`, and `git merge`. Read operations (`git status`, `git rev-parse`, `git log`, `git diff`) and worktree operations (`git worktree add/list/remove`) remain allowed. `aiflow init`/`update` auto-installs the hook into `.claude/settings.json`. Override with `AIFLOW_ALLOW_GIT_WRITE=1` for kit maintenance scripts. Defense-in-depth: even if a future skill smuggles a commit instruction, the harness blocks it before it reaches git.

## [0.0.8] - 2026-05-14

### Added

- **Short-hand CLI Command `ak`** — Added `ak` as an ultra-short alias for `aiflow` for faster developer workflow.
- **Command Aliases** — All major commands now have short aliases to reduce keystrokes:
  - `init` → `i` · `use` → `u` · `prompt` → `p` · `detect` → `d` · `task` → `t` · `context` → `ctx`
  - `checkpoint` → `cp` · `validate` → `vl` · `memory` → `mem` · `guide` → `g`
  - `remove` → `rm` · `update` → `up` · `sync-skills` → `sync` · `doctor` → `dr` · `telemetry` → `tel`
- **`task` sub-command aliases**: `status` → `st` · `list` → `ls` · `pause` → `p` · `switch` → `sw` · `resume` → `r` · `reset` → `rst` · `remove` → `rm` · `next` → `n`
- **`memory` sub-command aliases**: `save` → `s` · `get` → `g` · `list` → `ls` · `search` → `sr` · `delete` → `d` · `clear` → `cl`
- **New short options**:
  - `-v` short flag for `--version` at root (works alongside legacy `-V`)
  - `init --fw <types>` — long alias for `--framework`
  - `use -F/--fast`, `-U/--full`
  - `prompt -L/--lang`, `-d/--detail`
  - `validate -x/--fix`
  - `context -l/--load`
  - `checkpoint -g/--gate`, `-s/--step`, `-n/--tokens`
  - `guide -f/--flow`, `-c/--commands`
  - `remove -g/--global`
  - `update -f/--force`
- **Enhanced Comment Loading Options** — Added granular control for fetching ticket comments in `ak use`:
  - `-c` or `--coms` — Quick alias to load all comments.
  - `--cid <id>` — Load a specific comment by its ID.
  - `--clast <n>` — Load only the last N comments.
  - `--cfrom <id>` — Load comments starting from a specific ID.
  - `--cto <id>` — Load comments up to a specific ID.
- **Deprecation Warning** — Added a friendly suggestion to use `ak` when the legacy `aiflow` command is invoked, preparing for future deprecation.

### Fixed

- **Backlog Comment Pagination** — Fixed a critical bug where comments were not loading due to an invalid `offset` parameter in the Backlog API. Switched to `minId`-based pagination to ensure reliable and complete comment fetching.
- **Robust Comment Filtering** — Centralized comment filtering logic to effectively exclude metadata-only comments (changelogs) and focus on actual discussions.

### Changed

- **CLI Consistency** — Updated all command-line help descriptions and internal mappings to support the new shortened flags while maintaining backward compatibility with legacy long-form options.
- **Documentation Alignment** — Updated all guides (QUICK_START, cli-reference) to reflect `ak` command and new short aliases.

---

## [0.0.7] - 2026-05-08

### Added

- **`aiflow use --file` enhancements**:
  - Automatic `taskId` generation from filename (up to 5 words).
  - Full filename used as task `title`.
  - Interactive `taskType` selection prompt during file loading for better context.
- **`documentation` task type** — Added support for documentation-specific tasks in `aiflow use` and task detection.
- **Automatic `task-summary.md` generation** — `aiflow task next` now generates a cumulative progress report in `plan/[ticket-id]/task-summary.md` at each gate finish.
- **Session Continuity Instructions** — Added explicit instructions on how to switch to a fresh chat session and resume tasks (including Gate 3 sub-tasks) to both CLI output and AI skill prompts.
- **NestJS framework support** — Added `nestjs` to the framework selector (`aiflow init`), language rule mapping (`javascript`), and AI instruction template (`custom/templates/nestjs.md`).
- **PHP Plain (no framework) support** — Added `php-plain` as a new framework option with a dedicated AI system prompt template covering strict types, PSR-12, PDO prepared statements, security best practices, Repository/Service/Controller layering, and PHPUnit testing.
- **`investigate-bug` skill: NestJS and PHP plain data flows** — Added framework-specific data flow traces for NestJS (`Controller → Service → Repository → DB`) and PHP Plain (`index.php → Controller → Service → Repository/PDO → DB`).
- **Intelligent AI Instruction Synchronization** — Marker-based (`<!-- aiflow-kit-start -->`) block updates for `CLAUDE.md`, `GEMINI.md`, and `.cursorrules`.
- **Interactive Instruction Safety** — Granular confirmation prompts for all instruction file modifications (update block, overwrite, or create new).
- **Automated Repository Hygiene** — Generated files and folders (`.aiflow/`, `plan/`, `.claude/`, `.rules/`, `.mcp.json`, and instruction files) are now automatically managed in `.gitignore`.
- **`aiflow sync-skills` command** — Lightweight command to synchronize Skill Registry and Instruction files without a full version upgrade.
- **Enhanced `aiflow guide --flow`** — Now dynamically displays the `## Workflow Overview` section directly from `AIFLOW.md` for up-to-date documentation.
- **Token savings dashboard in `aiflow doctor`** — new "Token savings" section shows RTK status and estimated 60–90% reduction on bash outputs.

### Changed

- **Robust Gate Detection** — Refactored `detectCurrentGate` to prioritize `task-state.json` as the source of truth for task progress.
- **`aiflow gate approved` CLI output** — Now prints a session-refresh tip to help users maintain clean AI contexts.
- **`aiflow update` efficiency** — Now automatically performs skill and instruction synchronization even if the version is unchanged (removes the need for `--force`).
- **Safety First Development** — Removed all automatic `git commit` and `git add` instructions from key AI skills (`subagent-driven-development`, `using-git-worktrees`, `writing-plans`, `generate-spec`) to ensure developer-led commit management.
- **Localized CLI** — All interactive prompts and confirmation messages translated to English for consistency.
- **`aiflow init` RTK entry** — flag description updated to clarify RTK saves bash output tokens (60–90%).
- **`aiflow doctor`** — RTK section merged into new "Token savings" section.
- **README.md / QUICK_START.md / AIFLOW.md** — Updated to reflect session continuity workflow, `sync-skills` command, and improved update flow.

### Fixed

- **Automatic Git Commits Removed** — Fully disabled automated version control actions across the entire Skill Registry. Developers now have full manual control over staging and commits, preventing unintended history pollution during AI implementation.
- **NestJS auto-detection** — `@nestjs/core` in `package.json` was incorrectly detected as `nodejs-express`; now correctly resolves to `nestjs`.
- **PHP project auto-detection** — Projects with `composer.json` but no Laravel dependency now correctly auto-detect as `php-plain` instead of being skipped.
- **Instruction Safety** — Fixed `.github/copilot-instructions.md` not being included in automated `.gitignore` rules.

---

## [0.0.6] - 2026-04-29

### Added

- **Global Fast Mode (Default)** — Optimize AI efficiency by prioritizing speed and minimizing token usage.
  - Gate 1: Fast track scan with max 1 clarifying question.
  - Gate 3: Disable subagents by default; implement all tasks in a single session.
  - Gate 4: Quick scan impact analysis based on git diffs; simplified review checklist.
- **Improved `--file` loader** — `aiflow use --file` now supports plain-text files (JSON no longer required).
  - Auto-detects Ticket ID and Title from the text content.
- **Gate-aware Injection** — Enhanced `session-start.js` hook to inject gate-appropriate "Fast Track" instructions during task resumption.
- **Full Mode flag** — Added `--full` flag to bypass Fast mode optimizations for complex tasks.
- **`aiflow task` command group** — Manage multiple tasks in the same repository without losing progress.
  - `aiflow task status`, `list`, `pause`, `switch`, `resume`.
- **RTK token compression integration** — `aiflow init` automatically configures the RTK hook for 60–90% token savings on shell commands.
- **`aiflow use --fast` / `--full` flags** — Control Gate 1 analysis depth per ticket.
- **Spring Boot code examples extracted** — Java code examples moved to separate files to reduce `CLAUDE.md` size.

### Changed

- **Default mode** for all new tasks is now `fast` instead of `auto`.
- **`aiflow init` improvements** — Supports multi-select framework and protects existing instruction files from being overwritten.
- **CLAUDE.md Optimization** — Reduced Spring Boot template size by ~70%, saving ~3-5k tokens per session.
- **Documentation Synchronization** — Fixed all documentation links on npmjs.com and updated Overview Flow in README.
- **Automatic Task Pausing** — When loading a new ticket, the current task is automatically paused and its state is saved.

### Fixed

- Broken 404 documentation links on the npmjs.com page.

---

## [0.0.4-beta.5] - 2026-04-21

### Added

- Created a dedicated `docs/` folder to house all developer-facing documentation.
- Integrated AI Skill Registry into all tool templates (Claude, Cursor, Gemini, Copilot) for better skill discovery.

### Changed

- Moved `README.md`, `QUICK_START.md`, `AIFLOW.md`, `CHANGELOG.md`, and `IMPLEMENTATION_SUMMARY.md` into the `docs/` directory.
- Updated `package.json` to exclude internal-only files (`CONTRIBUTING.md`, `plan.md`) from the NPM package distribution.
- Updated `scripts/init.js` to source documentation from the new `docs/` location.
- Updated all internal documentation links to reflect the new directory structure.

---

## [0.0.5-beta.0] - 2026-04-23

### Added

- **`aiflow gate <n> <action>` command** — Called automatically by AI during gate transitions. Supports `start` and `approved` actions for gates 1-5. Options: `--ticket <id>`, `--ai-tool <tool>`.
- **Telemetry gate logging** — Gate workflow templates now emit `aiflow gate N start/approved --ticket [id]` telemetry calls at each gate transition for usage metrics.
- **`aiflow telemetry flush` command** — Force-sends buffered telemetry events immediately.

### Changed

- **`aiflow init` safe overwrite flow** — When a project already has `CLAUDE.md`, `GEMINI.md`, `.cursorrules`, etc., `aiflow init` now prompts before overwriting:
  - **No (default):** keeps existing file untouched; saves the aiflow template to `.aiflow/reference/<file>` for manual comparison/merge.
  - **Yes:** backs up the existing file to `.aiflow/backup/<file>` before overwriting — nothing is permanently lost.
- **`aiflow use --manual` pre-fill (Edit mode)** — Re-running `aiflow use --manual` when context already exists now pre-fills all fields (Ticket ID, Title, Description, Task type) with the current values; press Enter on any field to keep it unchanged.
- **Fix TEAM_SECRET input** — Replaced `password()` prompt with `input()` using a masked hint `[Reli***!@#]`; pressing Enter retains the existing value.
- **Fix Apps Script URL input** — Same pattern as TEAM_SECRET: masked hint `[https://script.google.com/macros/s/AKfy***xxxx/exec]`; pressing Enter retains the existing value.
- **Downgrade dependencies for Node >=16 compatibility** — `@inquirer/prompts` downgraded from `^8.3.2` to `^3.0.0`; `commander` downgraded from `^14.0.3` to `^11.0.0`.
- **`engines.node`** updated from `>=14.0.0` to `>=16.0.0`.

---

## [0.0.5] - 2026-04-23

### Added

- **Telemetry System (MVP)**: Added anonymous usage tracking to measure command metrics and user adoption.
  - `aiflow telemetry enable/disable/status` commands to easily opt-in or opt-out.
  - Automatically captures environment metadata and Git email via `git config --global user.email`.
  - Secure payload signing natively using Node `crypto` HMAC-SHA256 to ensure data authenticity.
  - Asynchronous payload flusher to ensure zero impact on command execution time (`< 5ms` overhead).
- Support tracking for multiple AI platforms including Cursor and Gemini via Command Execution events and the new Telemetry SDK.

### Security

- **Strict Privacy**: Explicitly removed all prompt content and chat history tracking to ensure 100% confidentiality of company code and PII.

---

## [Unreleased]

## [0.0.3-beta.0] - 2026-04-13

### Security

- Removed internal GitLab repository links and tracking information.
- Cleaned `.npmrc` configuration.
- Added helper scripts for beta and stable releases.

## [0.0.2] - 2026-04-13

### Changed

- Updated package name in documentation and configuration.
- Fixed installation guides in README and QUICK_START.

## [0.0.1] - 2026-04-13 — Initial Release

### Added

#### CLI (`aiflow`)

- `aiflow init` — scaffold AI workflow config into any project
  (supports `--framework` spring-boot/reactjs, `--adapter` jira/backlog)
- `aiflow use <skill>` — activate a custom skill in the current project
- `aiflow remove` — cleanly remove `ai-flow-kit` scaffolding from a project
- `aiflow guide` — interactive onboarding guide
- `aiflow update` — sync upstream skill/hook updates
- `aiflow doctor` — validate config, detect missing keys, report issues
- `aiflow --version` — print installed version

#### 5-Gate AI Workflow

- **Gate 1 — AI Analyze Requirement**: Auto-starts when a ticket context exists
  in `.aiflow/context/current.json`; outputs `plan/[ticket-id]/requirement.md`
- **Gate 2 — Implementation Plan**: TDD plan generation, gated by `APPROVED`
- **Gate 3 — Code Generation**: TDD-only, test-first discipline enforced
- **Gate 4 — AI Self-Review**: Verification + impact analysis + checklist, gated by `APPROVED`
- **Gate 5 — Peer Review & PR**: Guided PR creation via `requesting-code-review` skill

#### Custom Skills (7 skills)

- `read-study-requirement` — Gate 1 requirement analysis with clarifying Q&A loop
- `generate-spec` — Gate 2 TDD implementation spec generator
- `impact-analysis` — breaking-change and dependency impact assessment
- `investigate-bug` — systematic bug investigation (reproduce → root cause → fix)
- `report-customer` — customer-facing incident report generator
- `review-plan` — Gate 4 self-review orchestrator
- `figma-to-component` — Figma design → UI component code generator

#### Multi-AI Support

- **Claude Code** integration via `CLAUDE.md` + `.claude/` directory structure
- **Gemini CLI** integration via `GEMINI.md`
- **GitHub Copilot** integration via agents config
- Superpowers skill library bundled as `upstream/` (pinned to v5.0.5)

#### Project Templates

- `AIFLOW.md` — team workflow reference document
- `QUICK_START.md` — 5-minute setup guide
- `.aiflowrc.json.example` — configuration file reference

### Architecture Notes

- Stateless per-ticket design — no persistent memory across sessions (planned: v0.1.x)
- Manual skill sync model via `aiflow use` (managed `aiflow skill` CLI planned: v0.1.x)
- Spring Boot (Java 17+) used as the reference framework in `CLAUDE.md` coding rules

---

## How to upgrade

```bash
npm install -g @relipa/ai-flow-kit@latest
aiflow --version
```

After upgrading, run `aiflow update` inside your project to sync the latest skills and hooks:

```bash
cd your-project
aiflow update
```
