/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { versionedContent } from './shared.js';
/** Default playbook directory, relative to project root. */
export const PLAYBOOKS_DIR = '.setup-agents/playbooks';
const PLAYBOOK_DEFINITIONS = {
    // ─── PM ────────────────────────────────────────────────────────────────────
    'sprint-plan.md': {
        title: 'Sprint Plan',
        body: `## Goal
Review the backlog and define the sprint goal, scope, and capacity.

## Steps
1. Read open backlog items from \`.setup-agents/state/\` or the linked Jira board.
2. Confirm scope with the team: which stories fit in this sprint?
3. Write the sprint goal in one sentence.
4. List selected stories with estimated effort (S/M/L).
5. Record risks or blockers in a \`risk-register.md\` note.
6. Record evidence: \`sa-fast evidence add --task <id> --role pm --type file --summary "Sprint plan written"\`
`,
    },
    'status-report.md': {
        title: 'Status Report',
        body: `## Goal
Produce a concise status update for stakeholders.

## Steps
1. List completed stories since last report.
2. List in-progress stories with current blockers.
3. Summarize risks and next steps.
4. Record evidence: \`sa-fast evidence add --task <id> --role pm --type file --summary "Status report written"\`
`,
    },
    'risk-register.md': {
        title: 'Risk Register',
        body: `## Goal
Document known risks and their mitigations.

## Format
| Risk | Probability | Impact | Mitigation |
|------|-------------|--------|------------|
| ...  | High/Med/Low | High/Med/Low | ... |

## Steps
1. Identify risks from backlog items, dependencies, and team input.
2. Fill in the table above.
3. Record evidence: \`sa-fast evidence add --task <id> --role pm --type file --summary "Risk register updated"\`
`,
    },
    'delivery-metrics.md': {
        title: 'Delivery Metrics',
        body: `## Goal
Track velocity, cycle time, and completion rate for the sprint.

## Steps
1. Count stories completed vs. planned.
2. Calculate average cycle time (days from start to done).
3. Note blockers that caused delay.
4. Record evidence: \`sa-fast evidence add --task <id> --role pm --type file --summary "Delivery metrics recorded"\`
`,
    },
    // ─── BA ────────────────────────────────────────────────────────────────────
    'refine-stories.md': {
        title: 'Refine Stories',
        body: `## Goal
Ensure stories have clear acceptance criteria before entering development.

## Steps
1. Read each story in scope.
2. Verify: title, description, acceptance criteria, and out-of-scope section are present.
3. Add missing acceptance criteria using Gherkin: \`Given / When / Then\`.
4. Flag stories that need Product Owner clarification.
5. Record evidence: \`sa-fast evidence add --task <id> --role ba --type file --summary "Stories refined"\`
`,
    },
    'groom-backlog.md': {
        title: 'Groom Backlog',
        body: `## Goal
Order and prioritize backlog items by business value and technical dependency.

## Steps
1. List all open backlog items.
2. Sort by: business priority > technical dependency > effort.
3. Remove duplicates and merge overlapping stories.
4. Record evidence: \`sa-fast evidence add --task <id> --role ba --type file --summary "Backlog groomed"\`
`,
    },
    'update-jira-ticket.md': {
        title: 'Update Jira Ticket',
        body: `## Goal
Keep the Jira ticket synchronized with the current state of the story.

## Steps
1. Read the story context from \`.setup-agents/state/\`.
2. Update the Jira ticket: status, assignee, description, and acceptance criteria.
3. Add a comment summarizing what was done in this phase.
4. Record evidence: \`sa-fast evidence add --task <id> --role <profile> --type command --summary "Jira ticket updated"\`
`,
    },
    // ─── Architect ─────────────────────────────────────────────────────────────
    'adr.md': {
        title: 'Architecture Decision Record (ADR)',
        body: `## Goal
Document a significant architectural decision.

## ADR Template
\`\`\`markdown
# ADR-NNN: <Title>

## Status
Proposed | Accepted | Deprecated

## Context
<What is the issue motivating this decision?>

## Decision
<What is the change being made?>

## Consequences
<What are the trade-offs and downstream impacts?>
\`\`\`

## Steps
1. Identify the decision to record.
2. Fill in the ADR template above.
3. Write to \`docs/adr/ADR-NNN-<slug>.md\`.
4. Record evidence: \`sa-fast evidence add --task <id> --role architect --type file --summary "ADR written: docs/adr/ADR-NNN.md"\`
`,
    },
    'architecture-review.md': {
        title: 'Architecture Review',
        body: `## Goal
Validate that the proposed solution meets non-functional requirements and delegate implementation to the correct domain profile.

## Step 0 — Identify the implementor profile (CRITICAL)
Before closing this phase, read \`.setup-agents/config.json\` and identify which profile owns implementation:
\`\`\`bash
cat .setup-agents/config.json | grep -A20 '"profiles"'
\`\`\`
The implementor is the first active profile that is NOT \`pm\`, \`ba\`, \`architect\`, \`qa\`, or \`devops\`.
Common values: \`cgcloud\`, \`admin\`, \`service\`, \`commerce\`, \`crma\`, \`developer\`, etc.
Include the resolved profile in the handoff summary so the pipeline creates the task with the correct role.

## Checklist
- [ ] Scope assessment: run \`scope-assessment.md\` playbook (REQUIRED for tasks ≥ m)
- [ ] Scalability: handles expected load (1 to N records)
- [ ] Security: sharing model correct, no hardcoded credentials
- [ ] Maintainability: follows existing patterns, no mega-classes
- [ ] Testability: >90% coverage achievable
- [ ] Integration: no tight coupling to external systems
- [ ] Implementor profile identified and declared in handoff

## Steps
1. Read the story and proposed design.
2. Identify the implementor profile (Step 0 above).
3. Walk through the checklist.
4. List any blockers or required changes.
5. Declare delivery estimate (Step 6 below).
6. Record evidence: \`sa-fast evidence add --task <id> --role architect --type report --summary "Architecture review complete — implementor: <profile>"\`

## Step 6 — Declare T-Shirt Estimate (REQUIRED before handoff)
Before closing this phase, declare a delivery estimate so benchmarks can track actual vs. baseline:

\`\`\`bash
# Check if an estimate already exists (idempotent — skip if found)
sf setup-agents workflow benchmark --story <storyId>

# If no estimate exists, declare one:
sf setup-agents workflow estimate \\
  --story <storyId> \\
  --sizing <xs|s|m|l|xl> \\
  --solo-days <n> \\
  --ai-unguided-days <n> \\
  --ai-guided-days <n> \\
  --confidence <low|medium|high> \\
  --declared-by architect
\`\`\`

**Sizing scale:**
| Label | Solo effort |
|-------|------------|
| xs    | ≤ 0.5 days |
| s     | ≤ 1 day    |
| m     | ≤ 3 days   |
| l     | ≤ 5 days   |
| xl    | > 5 days   |

- \`--solo-days\`: how long a solo developer would take without AI assistance.
- \`--ai-unguided-days\`: how long with a generic AI assistant (no agent workflow).
- \`--ai-guided-days\`: how long expected with setup-agents guided workflow (profiles + orchestration). This is the ROI baseline — it becomes the denominator for \`vsAiGuidedPct\` in the benchmark.
- \`--confidence\`: your confidence in the estimate (low/medium/high).

> **Backfill:** if the estimate was already recorded without \`--ai-guided-days\`, re-run the command with only \`--story\`, \`--sizing\`, \`--solo-days\`, \`--ai-unguided-days\`, and \`--ai-guided-days\` to add the guided baseline. The log is append-only and the last record wins.
`,
    },
    'scope-assessment.md': {
        title: 'Scope Assessment & Split Decision',
        body: `## Goal
Evaluate task scope and complexity before developer handoff. Flag oversized or cross-cutting tasks for split.

## When to Run
REQUIRED before every architect→developer handoff. This ensures cross-cutting work is identified early.

## Step 1 — Measure Scope
Count the affected boundaries:
- How many directories/packages are touched?
- How many object types (Apex, LWC, Flow, metadata, config)?
- Does it cross module boundaries (e.g. force-app + scripts + CI)?

## Step 2 — Complexity Signals
Check for these red flags:
- [ ] Touches 3+ top-level directories → likely cross-cutting
- [ ] Requires changes to both backend (Apex) and frontend (LWC/Aura)
- [ ] Involves both schema changes and code changes
- [ ] Estimated > 3 days solo effort (sizing m or above)
- [ ] Multiple integration points or external system changes

## Step 3 — Split Decision
Based on scope:

**If 2+ red flags are present:**
1. Recommend splitting into child stories.
2. List proposed child tasks with clear boundaries.
3. Record decision: \\\`sf setup-agents decision add --task <id> --owner architect --title "Split: <reason>" --decision "Split into N child stories" --context "<scope details>" --consequences "Parallel delivery possible" --status accepted\\\`

**If scope is acceptable (0-1 red flags):**
1. Explicitly document: "Scope assessed — single story acceptable."
2. Record decision: \\\`sf setup-agents decision add --task <id> --owner architect --title "Scope assessment" --decision "No split needed" --context "<brief justification>" --consequences "Proceed as single story" --status accepted\\\`

## Step 4 — Record Evidence
\\\`\\\`\\\`bash
sa-fast evidence add --task <id> --role architect --type report \\\\
  --summary "Scope assessment: <N> boundaries, <N> red flags, decision: <split|no-split>"
\\\`\\\`\\\`

## Anti-patterns (DO NOT)
- Do NOT handoff with "gaps: none, risks: none" without running this assessment
- Do NOT skip this for tasks estimated ≥ m (3+ days)
- Do NOT use generic text — always include specific boundary count and decision
`,
    },
    'data-model-design.md': {
        title: 'Data Model Design',
        body: `## Goal
Design or review the data model changes required by this story.

## Steps
1. Read \`sfdx-project.json\` for \`sourceApiVersion\`.
2. Identify objects and fields to create or modify.
3. Document: object API name, field API names, types, relationships.
4. Check for existing custom objects before proposing new ones.
5. Include a Mermaid ERD for changes affecting 2+ objects.
6. Record evidence: \`sa-fast evidence add --task <id> --role architect --type file --summary "Data model design documented"\`
`,
    },
    // ─── Developer ─────────────────────────────────────────────────────────────
    'create-apex-class.md': {
        title: 'Create Apex Class',
        body: `## Goal
Implement the Apex class(es) required by this story.

## Pre-flight
1. Read \`sfdx-project.json\` → \`sourceApiVersion\`.
2. Grep for existing utility classes before writing new ones.
3. Check \`.setup-agents/state/evidence.jsonl\` for lessons learned on this topic.

## Steps
1. Follow existing naming conventions (infer from \`force-app/main/default/classes/\`).
2. Default \`with sharing\`. Exception: \`@RestResource\` → \`without sharing\`.
3. No SOQL or DML inside loops. Bulkify all methods.
4. Write the test class (\`<ClassName>_Test\`) with ≥90% coverage.
5. Deploy and validate:
   \`\`\`bash
   sf project deploy validate -d force-app --target-org <alias>
   \`\`\`
6. Record evidence: \`sa-fast evidence add --task <id> --role developer --type file --summary "Apex class created: <ClassName>"\`
`,
    },
    'create-trigger.md': {
        title: 'Create Apex Trigger',
        body: `## Goal
Implement an Apex trigger following the one-trigger-per-object pattern.

## Pre-flight
1. Check \`force-app/main/default/triggers/\` — if a trigger exists for this object, extend it; never create a second one.
2. Check for existing trigger handler (\`<Object>TriggerHandler.cls\`).

## Steps
1. Create or update the trigger (zero logic — delegate to handler).
2. Create or update \`<Object>TriggerHandler.cls\` with the business logic.
3. Write test class with ≥90% coverage.
4. Deploy and validate.
5. Record evidence: \`sa-fast evidence add --task <id> --role developer --type file --summary "Trigger created/updated: <Object>"\`
`,
    },
    'create-lwc.md': {
        title: 'Create Lightning Web Component',
        body: `## Goal
Implement the LWC required by this story.

## Pre-flight
1. Read \`sfdx-project.json\` → \`sourceApiVersion\`.
2. Check \`force-app/main/default/lwc/\` for an existing component to extend.

## Steps
1. Prioritize SLDS Styling Hooks over custom CSS.
2. Use Lightning Data Service / LDS 2 where possible.
3. User feedback: Toasts with Custom Labels — never hardcode strings.
4. UX gate: contrast (4.5:1), empty states, loading spinners, touch targets (44×44px).
5. Write Jest tests in \`__tests__/\`.
6. Record evidence: \`sa-fast evidence add --task <id> --role developer --type file --summary "LWC created: <componentName>"\`
`,
    },
    'declare-story-points.md': {
        title: 'Declare Story Points',
        body: `## Goal
Record the actual effort for this implementation phase so delivery benchmarks stay accurate.

## When to run
At the end of your implementation phase, before closing the task — after the work is done
and you have a clear picture of actual complexity.

## Steps
1. Assess the actual effort spent on this story:
   \`\`\`
   1 — trivial (< 1 hour, no surprises)
   2 — small   (half a day, straightforward)
   3 — medium  (1 day, some complexity)
   5 — large   (2–3 days, significant work)
   8 — very large (> 3 days — consider splitting next time)
   \`\`\`
2. Record via evidence:
   \`\`\`bash
   sa-fast evidence add \\
     --task <id> \\
     --role developer \\
     --type validation \\
     --summary "story-points: <n>"
   \`\`\`
3. If the story took significantly more or less than the architect's t-shirt estimate,
   add a note explaining the delta:
   \`\`\`bash
   sa-fast evidence add \\
     --task <id> \\
     --role developer \\
     --type validation \\
     --summary "story-points: <n> — delta: <reason>"
   \`\`\`
`,
    },
    // ─── UX ────────────────────────────────────────────────────────────────────
    'design-review.md': {
        title: 'Design Review',
        body: `## Goal
Validate wireframe/mockup fidelity against SLDS standards and Salesforce UX patterns before development begins.

## Steps
1. Gather the wireframe or mockup (file path, Figma link, or description).
2. Review against:
   - **SLDS Components:** Are standard SLDS components used instead of custom HTML?
   - **Styling Hooks:** Are SLDS Styling Hooks used for colors, spacing, and typography?
   - **Component Reuse:** Are existing LWC components reused before proposing new ones?
   - **Accessibility Baseline:** Does the design specify contrast ratios (4.5:1), touch targets (44×44px), and keyboard navigation paths?
3. List deviations with severity (Critical / High / Medium / Low).
4. Approve for development or return with required changes.
5. Record evidence: \`sa-fast evidence add --task <id> --role ux --type report --summary "Design review complete: <status>"\`
`,
    },
    'wireframe.md': {
        title: 'Wireframe',
        body: `## Goal
Produce a lo-fi then hi-fi wireframe that captures component inventory, responsive breakpoints, and interaction states.

## Steps
1. Clarify: What is the user goal for this screen/flow?
2. Lo-fi wireframe:
   - Sketch the layout: header, sidebar, main content, footer.
   - List all interactive elements: buttons, inputs, dropdowns, modals.
   - Note empty states, loading states, and error states.
3. Hi-fi wireframe:
   - Map lo-fi elements to SLDS components (lightning-button, lightning-input, etc.).
   - Define responsive breakpoints: mobile (320px), tablet (768px), desktop (1280px).
   - Confirm component inventory — no net-new LWC without justification.
4. Share with team for feedback before implementation handoff.
5. Record evidence: \`sa-fast evidence add --task <id> --role ux --type file --summary "Wireframe complete: <screenName>"\`
`,
    },
    'a11y-audit.md': {
        title: 'Accessibility Audit (a11y)',
        body: `## Goal
Verify the component or page meets WCAG 2.1 AA standards before QA sign-off.

## Checklist

### Visual
- [ ] Text contrast ratio: ≥ 4.5:1 (normal text), ≥ 3:1 (large text / UI components)
- [ ] No information conveyed by color alone
- [ ] Focus indicators visible for all interactive elements

### Keyboard Navigation
- [ ] All interactive elements reachable via Tab / Shift+Tab
- [ ] Enter / Space activates buttons and links
- [ ] Escape closes modals and dropdowns
- [ ] No keyboard traps

### Screen Reader
- [ ] All images have \`alt\` text or \`aria-hidden\`
- [ ] Form fields have associated \`<label>\` or \`aria-labelledby\`
- [ ] Dynamic updates announce via \`aria-live\` regions

### Touch / Mobile
- [ ] Touch targets ≥ 44×44px
- [ ] No hover-only interactions

## Steps
1. Run automated audit (Axe DevTools, WAVE, or equivalent).
2. Manual keyboard-only walkthrough of all interactive flows.
3. Screen reader walkthrough (NVDA, JAWS, or VoiceOver).
4. Document findings with severity and remediation steps.
5. Record evidence: \`sa-fast evidence add --task <id> --role ux --type report --summary "a11y audit: <pass|fail> — <n> issues"\`
`,
    },
    // ─── QA ────────────────────────────────────────────────────────────────────
    'qa-plan.md': {
        title: 'QA Plan — Story Definition Gate',
        body: `## Goal
Define the QA strategy for this story during BA/Definition phase.
A QA Plan must be approved by the QA role before the story can move to the Developer phase.

## Instructions
Fill in each section for the story in scope. Submit for QA review when complete.

---

## Story Reference
- **Story ID:** <!-- e.g., PROJ-123 -->
- **Story Title:** <!-- one-line summary -->
- **Acceptance Criteria count:** <!-- how many ACs -->

## Scope

### What is being built / changed?
<!-- Describe the feature, change, or fix in plain language. -->

### In scope for this QA cycle
<!-- List components, objects, flows, APIs, or UI surfaces to test. -->

### Out of scope / deferred
<!-- List what will NOT be tested now, and why. Document owner for deferred items. -->

## Test Strategy

### Test types required
- [ ] Unit tests (Apex) — required for all Apex changes
- [ ] E2E / Playwright — required for UI changes
- [ ] API tests — required for REST endpoint changes
- [ ] Agentforce DML validation — required if agent performs DML
- [ ] Manual exploratory — required for complex UX flows

### Environments
- **Dev / Sandbox:** <!-- org alias -->
- **UAT / Staging:** <!-- org alias if applicable -->

### Test Data & Fixtures
<!-- Describe data setup: persona, records, Permission Set Groups needed. -->

## Observable Assertions Plan
<!-- For each test type in scope, describe what observable outcome will be asserted. -->
<!-- Reference: .setup-agents/playbooks/observable-assertions.md -->

| Test Type | What will be asserted |
|-----------|----------------------|
| Unit | |
| E2E | |
| API | |

## Risks & Gaps
| Risk | Impact | Mitigation |
|------|--------|------------|
| | | |

## Deferred Validation
| What | Why deferred | Owner | Follow-up by |
|------|--------------|-------|--------------|
| | | | |

## Sign-off
- **QA Author:** <!-- name or role -->
- **Reviewer (QA role):** <!-- must be approved before developer phase -->

## Commands
Record QA Plan approval:
\`\`\`bash
sf setup-agents review --task <id> --role qa --result approve --findings "QA Plan reviewed and approved" --recommendation "Proceed to Developer phase"
\`\`\`

Block if plan is incomplete:
\`\`\`bash
sf setup-agents review --task <id> --role qa --result changes --findings "<what is missing>" --recommendation "Complete QA Plan before proceeding"
\`\`\`
`,
    },
    'qa-checklist.md': {
        title: 'QA Checklist — Definition of Done',
        body: `## Goal
Confirm every acceptance criterion is met before approving the QA gate.

## Definition of Done

### Code Quality
- [ ] No linter errors or suppressed warnings
- [ ] All new code covered by tests (target ≥ 90%)
- [ ] No SOQL or DML inside loops
- [ ] No hardcoded strings (Custom Labels used for UI text)

### Testing
- [ ] Apex test classes run without failures:
   \`\`\`bash
   sf apex test run --target-org <alias> --code-coverage --result-format human
   \`\`\`
- [ ] Code coverage ≥ 90% for all new/modified classes
- [ ] Playwright E2E tests pass (if applicable)

### Observable Assertions (CRITICAL — see observable-assertions.md)
- [ ] Every test validates an observable outcome, not just that the script ran
- [ ] Web tests assert rendered text, control states, or navigation — not just element existence
- [ ] API tests assert response body, persistence, and error shape — not just status 200
- [ ] Agentforce DML tests assert both conversational output AND persisted Salesforce records
- [ ] CLI tests assert exit code, stdout content, and generated file contents
- [ ] Evidence gaps and deferred validations are documented with owner and deadline

### Acceptance Criteria
- [ ] Every AC from the story is verified with evidence
- [ ] Edge cases tested: empty data, large data sets, invalid input
- [ ] No open blockers in \`.setup-agents/state/\`

### Handoff Readiness
- [ ] Deployment validation passed (\`sf project deploy validate\`)
- [ ] Validation job ID recorded for quick deploy

## Steps
1. Work through each checklist item above.
2. For any observable assertion gap: document it before proceeding, do not skip.
3. For each failure: create a defect task and block the QA gate.
4. When all items pass: record evidence and approve.
5. Record evidence: \`sa-fast evidence add --task <id> --role qa --type report --summary "QA checklist complete: all ACs + observable assertions verified"\`
`,
    },
    'observable-assertions.md': {
        title: 'Observable Assertions — QA Evidence Guide',
        body: `## Goal
Ensure every automated test validates an observable outcome, not just that a script ran to completion without errors.

## Rule
**A test that finishes without throwing is not evidence of correctness.**
Every test must assert at least one user-facing or system-state outcome.

## Patterns by Test Type

### Web / Playwright
\`\`\`typescript
// ❌ Wrong — asserts element exists, not what the user sees
await expect(page.locator('.success-msg')).toBeVisible();

// ✅ Correct — asserts the actual content shown to the user
await expect(page.locator('.success-msg')).toHaveText('Record saved successfully');
\`\`\`
- After a form submit: assert the confirmation message text or navigation URL.
- After a button click: assert the resulting page state, not just that the click succeeded.
- On error paths: assert the error message text shown to the user.
- Screenshot on failure is required evidence for visual assertions.

### API Tests
\`\`\`typescript
// ❌ Wrong — asserts only status
expect(response.status).toBe(200);

// ✅ Correct — asserts body content and persistence
expect(response.body.name).toBe('Test Account');
const record = await sfClient.query(\`SELECT Name FROM Account WHERE Id = '\${response.body.id}'\`);
expect(record[0].name).toBe('Test Account');
\`\`\`
- Always re-query after POST/PATCH to confirm persistence.
- Assert 403/401 for unauthorized requests — do not skip permission tests.

### Agentforce DML
\`\`\`typescript
// ❌ Wrong — asserts only the chat response
expect(chatResponse).toContain('I created the case');

// ✅ Correct — asserts both conversational output AND database state
expect(chatResponse).toContain('I created the case');
const cases = await sfClient.query(\`SELECT Subject FROM Case WHERE Subject = 'Test Case'\`);
expect(cases).toHaveLength(1); // @agent-dml
\`\`\`
- Tag the test with \`@agent-dml\` in the test title.
- Poll for async DML: max 10 s, 500 ms interval.
- Save \`sf data query\` JSON output to \`test-results/<spec>-<test>-dml.json\`.

### CLI Tests
\`\`\`bash
# ❌ Wrong — asserts only exit code
sf setup-agents local --rules cursor && echo "OK"

# ✅ Correct — asserts exit code + generated files + content
sf setup-agents local --rules cursor --profile developer
test -f .cursor/rules/developer-standards.mdc || exit 1
grep "alwaysApply" .cursor/rules/developer-standards.mdc || exit 1
\`\`\`

### Documenting Gaps
If observable assertion is not possible today:
\`\`\`
// DEFERRED VALIDATION: Cannot assert X because <reason>.
// Owner: <name>. Follow-up by: <date>.
\`\`\`

## Steps
1. For each test in scope, identify the observable outcome it should verify.
2. Apply the pattern for that test type above.
3. For any gap: add the deferred validation comment with owner and date.
4. Record evidence: \`sa-fast evidence add --task <id> --role qa --type test --summary "Observable assertions verified for <feature>"\`
`,
    },
    'regression.md': {
        title: 'Regression Protocol',
        body: `## Goal
Identify and execute the minimum regression test set to confirm no existing functionality was broken.

## Scope Identification
1. List all files/metadata changed in this story.
2. Identify impacted objects, processes, and integrations:
   - Apex class changes → run related test classes
   - Trigger changes → run all trigger test classes for that object
   - LWC changes → run Jest tests + Playwright flows for that component
   - Flow changes → test all entry paths for that flow
   - Schema changes → test all pages/components that reference those fields

## Execution Order
1. Unit tests first (Apex, Jest)
2. Integration tests (trigger → flow → output)
3. E2E tests (Playwright — critical user paths only)
4. Manual exploratory for high-risk areas

## Pass/Fail Criteria
- **Pass:** all existing tests pass, no new failures introduced
- **Fail:** any test that passed before this change now fails
- **Acceptable:** pre-existing failures that are documented in a known-issues log

## Escalation
If a regression is found:
1. Block the QA gate immediately.
2. Create a defect task with: what broke, when it broke (commit reference), severity.
3. Notify the developer for fix.

## Steps
1. Run full Apex test suite for changed objects:
   \`\`\`bash
   sf apex test run --target-org <alias> --code-coverage --result-format human
   \`\`\`
2. Run Playwright (if applicable).
3. Document results.
4. Record evidence: \`sa-fast evidence add --task <id> --role qa --type report --summary "Regression: <pass|fail> — <n> tests run"\`
`,
    },
    'smoke-test.md': {
        title: 'Post-Deploy Smoke Test',
        body: `## Goal
Validate critical paths in the target environment immediately after deployment to confirm the release is stable.

## Critical Path Scenarios
1. **Login:** Can users log in to the org?
2. **Core records:** Can users view, create, and edit the key object(s) modified by this story?
3. **Key flows:** Do the primary business processes (Flows, Apex triggers, LWC components) execute without errors?
4. **Permissions:** Do all relevant Permission Sets / Profiles still grant correct access?

## Environment Validation
- [ ] Check Salesforce debug logs for errors (last 15 minutes post-deploy)
- [ ] Check email alerts or outbound message queues for unexpected failures
- [ ] Verify integration endpoints are still responding (if applicable)

## Rollback Trigger Conditions
If any of the following are true, escalate to rollback immediately:
- Core record creation/edit is broken
- Login or authentication failures
- Data corruption detected
- Error rate > 5% in debug logs

## Steps
1. Execute critical path scenarios above in the target org.
2. Check debug logs and monitoring.
3. Document results: scenario → pass/fail → notes.
4. If pass: record evidence and clear for release.
5. If fail: block release gate and escalate.
6. Record evidence: \`sa-fast evidence add --task <id> --role qa --type report --summary "Smoke test: <pass|fail> — <n> scenarios verified"\`
`,
    },
    'run-playwright.md': {
        title: 'Run Playwright Tests',
        body: `## Goal
Execute the Playwright E2E suite and report results.

## Steps
1. Start the target org / sandbox environment.
2. Run:
   \`\`\`bash
   npx playwright test
   \`\`\`
3. Wait for all tests to complete.
4. Report: pass/fail count, failed test names, screenshots for failures.
5. If failures exist, diagnose and fix before marking QA done.
6. Record evidence: \`sa-fast evidence add --task <id> --role qa --type report --summary "Playwright: X/Y passed"\`
`,
    },
    'generate-test-report.md': {
        title: 'Generate Test Report',
        body: `## Goal
Produce a QA sign-off report for this story.

## Steps
1. Run Apex tests:
   \`\`\`bash
   sf apex test run --target-org <alias> --code-coverage --result-format human
   \`\`\`
2. Collect results: pass/fail count, coverage %.
3. Run Playwright (if applicable) — see \`run-playwright.md\`.
4. Write a summary: what was tested, results, any known limitations.
5. Record evidence: \`sa-fast evidence add --task <id> --role qa --type report --summary "Test report generated"\`
`,
    },
    // ─── Release ───────────────────────────────────────────────────────────────
    'release.md': {
        title: 'Release',
        body: `## Goal
Deploy validated changes to the target environment.

## Pre-flight
1. Confirm QA gate is approved (\`sf setup-agents workflow gate\`).
2. Confirm no open blockers in \`.setup-agents/state/\`.

## Steps
1. Quick deploy (uses last successful validation job):
   \`\`\`bash
   sf project deploy quick --job-id <validationJobId> --target-org <alias>
   \`\`\`
   Or full deploy if quick deploy is unavailable:
   \`\`\`bash
   sf project deploy start -d force-app --target-org <alias>
   \`\`\`
2. Monitor to completion. Report: status, duration, errors.
3. Run post-deploy smoke tests.
4. Record evidence: \`sa-fast evidence add --task <id> --role devops --type command --summary "Deployed to <org>"\`
`,
    },
    'candidate-release.md': {
        title: 'Candidate Release',
        body: `## Goal
Tag the current commit as a release candidate.

## Steps
1. Confirm all stories in scope are in \`done\` status.
2. Create a git tag:
   \`\`\`bash
   git tag rc-<version>-<YYYYMMDD>
   git push origin rc-<version>-<YYYYMMDD>
   \`\`\`
3. Create a GitHub release draft (do not publish yet).
4. Record evidence: \`sa-fast evidence add --task <id> --role devops --type command --summary "Release candidate tagged: rc-<version>"\`
`,
    },
    'validate.md': {
        title: 'Validate Deployment',
        body: `## Goal
Run a dry-run validation before deploying to production.

## Steps
1. Execute:
   \`\`\`bash
   sf project deploy validate -d force-app --target-org <alias> --test-level RunLocalTests
   \`\`\`
2. Wait for validation to complete.
3. Report: pass/fail, coverage %, any errors.
4. Record the validation job ID for use in quick deploy.
5. Record evidence: \`sa-fast evidence add --task <id> --role devops --type validation --summary "Validation passed, jobId: <id>"\`
`,
    },
    'doc-review.md': {
        title: 'Doc Review Playbook',
        body: `## Purpose
Gates documentation changes in the release phase. Run this playbook before closing the release task to confirm all docs meet project standards.

## Checklist
- [ ] All new/modified pages start with the Salesforce Cloud logo header
- [ ] Version header is incremented (\`**Version:** x.y\`)
- [ ] All internal links resolve — run \`yarn link-check\` to verify
- [ ] No orphan pages — every new page is linked from at least one nav or index
- [ ] Command examples match the actual CLI flags (verify against \`sf setup-agents --help\`)
- [ ] No commands, flags, or features from the previous version remain undocumented

## Evidence
\`\`\`bash
sa-fast evidence add --task <id> --role developer --type report --summary "Doc review passed: <summary of changes>"
\`\`\`
`,
    },
    'security-review.md': {
        title: 'Security Review Playbook',
        body: `## Goal
Perform a security assessment of the deliverable before it proceeds to QA.

## Cross-References
- **env-audit.md**: If new environment variables or secrets were introduced, ensure they are documented in \`docs/strategy/env-audit.md\` and follow the Named Credentials pattern.
- **Security Profile**: Review \`.cursor/rules/security-standards.mdc\` for project-specific security gates.

## Checklist
- [ ] No hardcoded credentials, tokens, or secrets in source code
- [ ] New environment variables documented in \`docs/strategy/env-audit.md\`
- [ ] CRUD/FLS enforcement: all DML uses \`Security.stripInaccessible()\` or \`WITH USER_MODE\`
- [ ] No SOQL injection: all dynamic queries use bind variables
- [ ] XSS prevention: all user input rendered via \`lightning:formattedText\` or encoded
- [ ] CSRF tokens present on all state-changing Visualforce pages
- [ ] Connected Apps use minimal OAuth scopes
- [ ] Sharing model respected: no \`without sharing\` unless documented
- [ ] sf scanner run passes with no HIGH/CRITICAL findings

## Evidence
\`\`\`bash
sa-fast evidence add --task <id> --role security --type report --summary "Security review: <pass|findings>"
\`\`\`
`,
    },
    'threat-model.md': {
        title: 'Threat Model Playbook',
        body: `## Goal
Create or update a STRIDE-based threat model for the feature under review.

## When to Run
- New external integrations or APIs
- New user roles or permission changes
- Data model changes involving PII or sensitive fields

## Steps
1. Identify trust boundaries (org boundary, API gateway, external system).
2. Apply STRIDE categories:
   - **S**poofing — authentication controls
   - **T**ampering — data integrity, FLS/CRUD
   - **R**epudiation — audit trail, Event Monitoring
   - **I**nformation Disclosure — encryption, sharing rules
   - **D**enial of Service — governor limits, API rate limits
   - **E**levation of Privilege — permission sets, sharing model
3. Document findings in \`docs/strategy/threat-model-<feature>.md\`.
4. Cross-reference \`docs/strategy/env-audit.md\` for any secrets or credentials.
5. Record mitigations as decisions.

## Evidence
\`\`\`bash
sa-fast evidence add --task <id> --role security --type report --summary "Threat model: <feature>, <n> threats identified, <n> mitigated"
sf setup-agents decision add --task <id> --role security --summary "Threat model acceptance" --rationale "<summary>"
\`\`\`
`,
    },
    'env-audit.md': {
        title: 'Environment Variable Audit',
        body: `## Goal
Document and audit all environment variables, secrets, and credentials used by the project.

## Location
Maintain this audit at \`docs/strategy/env-audit.md\` in the project root.

## Template

| Variable | Purpose | Storage | Rotation | Owner |
|----------|---------|---------|----------|-------|
| SF_TARGET_ORG | Deploy target | CI secret | Per sprint | DevOps |
| SLACK_WEBHOOK_URL | Notifications | Named Credential | Quarterly | Admin |

## Checklist
- [ ] Every \`process.env.*\` reference in source has a corresponding row
- [ ] No secrets stored in \`.env\` files committed to git
- [ ] All secrets use Named Credentials, Custom Metadata, or CI secret store
- [ ] Rotation schedule defined for each credential
- [ ] Stale/unused variables flagged for removal

## Security Cross-Reference
This playbook is referenced by the security-review phase. Any new environment variable introduced MUST be recorded here before the security gate passes.

## Evidence
\`\`\`bash
sa-fast evidence add --task <id> --role security --type report --summary "Env audit: <n> vars documented, <n> flagged"
\`\`\`
`,
    },
};
// ─── Public API ───────────────────────────────────────────────────────────────
/**
 * Returns all default playbooks as { relativePath → content }.
 * Paths are relative to PLAYBOOKS_DIR.
 */
export function generateDefaultPlaybooks(version) {
    return Object.fromEntries(Object.entries(PLAYBOOK_DEFINITIONS).map(([filename, { title, body }]) => [
        filename,
        versionedContent(`# ${title}\n\n${body.trimStart()}`, version),
    ]));
}
//# sourceMappingURL=playbook-generator.js.map