/*
 * 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 { getProfileOrchestrationMetadata } from '../profiles/index.js';
import { lines } from './shared.js';
/** Returns the Risk Scale section as an array of lines, for embedding in any tool's guidelines. */
export function riskScaleLines() {
    return [
        '## Action Risk Scale (CRITICAL)',
        '> Before executing any action, classify it. Do NOT skip this — it prevents irreversible mistakes.',
        '',
        '### ✅ AUTO — execute without asking',
        '- Read any file, search codebase, run linters or tests',
        '- Create or edit source files, config files, markdown, JSON',
        '- Run `sf project deploy validate` (validation only, no deploy)',
        '- Run `yarn`, `npm`, `npx` scripts that are not destructive',
        '- Run `sf` read-only commands (`sf org list`, `sf data query`, `sf apex run` in scratch orgs)',
        '- Add evidence or decisions (`sf setup-agents evidence add`, `sf setup-agents decision add`)',
        '',
        '### ⚠️ ASK — show plan and wait for explicit user confirmation ("yes", "proceed", "go ahead")',
        '- `git commit`, `git push` (any branch)',
        '- `sf project deploy start` (real deploy to any org)',
        '- `sf org create scratch`, `sf package version create`',
        '- Installing or uninstalling packages/plugins',
        '- Creating, renaming, or deleting branches',
        '- Modifying CI/CD pipeline files (`.github/workflows/`, `Jenkinsfile`)',
        '- Any change to org configuration (profiles, permission sets, sharing rules)',
        '- Running scripts that write to shared or remote state',
        '',
        '### 🛑 NEVER — do not execute under any circumstances; tell the user to run it manually',
        '- `rm -rf`, `git clean -f`, or any recursive file deletion',
        '- `git reset --hard`, `git push --force` / `--force-with-lease`',
        '- `sf org delete`, dropping databases, truncating tables',
        '- Revoking or modifying org user permissions in production',
        '- Any command that cannot be undone and affects shared/production state',
        '',
        '> If a user asks you to execute a 🛑 action, decline and provide the exact command for them to run.',
        '> If unsure which tier an action belongs to, default to ⚠️ ASK.',
    ];
}
/** Returns the Plugin Workflow section as an array of lines, for embedding in any tool's guidelines. */
export function pluginWorkflowLines() {
    return [
        '## Plugin Workflow (CRITICAL — autonomous behavior required)',
        '> This project uses `@jterrats/setup-agents`. **Do NOT wait for user instruction** — run the pre-flight',
        '> check automatically at the start of every task. The plugin is the single source of truth for all',
        '> task state, evidence, and workflow progression. Never manage these manually.',
        '',
        '### Pre-flight check (run automatically before any implementation)',
        '> Prefer `sa-fast` (fast-path CLI, ~200ms) over `sf setup-agents` (~15s) for state commands.',
        '> If `sa-fast` is not in PATH, fall back to `sf setup-agents`.',
        '',
        '```bash',
        'sa-fast task list --json                    # identify if a task exists for this work',
        'sa-fast workflow pending --json             # check if a workflow run is already active',
        '```',
        '- If a matching task exists → claim it with `sa-fast task claim --id <id>`.',
        '- If no run is active and the work spans a story → start one with `sf setup-agents workflow run --story <id>`.',
        '- If no task exists → create one with `sa-fast task create --summary "<text>" --profile developer`.',
        '',
        '### Starting work on a story',
        '```bash',
        'sf setup-agents workflow run --story <id>   # full PM→BA→Architect→Developer↔QA→Release pipeline',
        '```',
        '',
        '### Working on a specific task (outside the pipeline)',
        '```bash',
        'sa-fast task claim --id <id>               # mark a task in-progress',
        'sa-fast task done --id <id>                # mark complete',
        '```',
        '',
        '### Checking workflow state',
        '```bash',
        '# Gate: blocks phase transition until approved — use at end of gated phase (e.g. ba→architect, qa→release)',
        'sf setup-agents workflow gate --task <id>',
        '# Clarify: mid-phase question to another role — use when blocked without needing a phase change',
        'sf setup-agents workflow clarify --task <id> --question "<text>"',
        'sf setup-agents workflow rollback --to <phase> --run <id>  # revert a phase',
        '```',
        '',
        '### Recording evidence and decisions',
        '```bash',
        'sa-fast evidence add --task <id> --role <profile> --type <command|file|report|validation> --summary "<text>"',
        'sf setup-agents decision add --task <id> --summary "<text>"',
        '```',
        '',
        '### Checking for stale rules',
        '```bash',
        'sf setup-agents update --dry-run            # see which rule files are outdated',
        'sf setup-agents update                      # regenerate stale files',
        '```',
        '',
        '### Project Knowledge (MANDATORY — read first)',
        '**Before** creating or modifying any Salesforce artifact: read `.setup-agents/project-knowledge.md` if it exists.',
        'It contains architecture decisions, naming conventions, label language, codebase map, and active stories.',
        'If a section is empty or the file does not exist, **ask the user** before assuming conventions.',
        'After an architecture decision is confirmed, update the relevant section.',
        '',
        '### Prompt Registry (MANDATORY — do not skip)',
        '**Before** creating any artifact: read `.generated-prompts/<type>.md` to infer existing conventions.',
        '**After** creating or substantially changing any artifact: write an entry immediately — same session.',
        '',
        'File → artifact type mapping:',
        '```',
        'apex.md      → Apex classes   lwc.md    → LWC   flows.md  → Flows',
        'triggers.md  → Triggers       tests.md  → Test classes',
        'metadata.md  → Objects/Fields/Permissions   cicd.md  → CI/CD   diagrams.md  → Diagrams',
        '```',
        '',
        'Entry format (append or update in-place — one entry per component, latest prompt only):',
        '```markdown',
        '## <ComponentName>',
        '- **Created:** YYYY-MM-DD',
        '- **Updated:** YYYY-MM-DD',
        '- **Iterations:** N',
        '',
        '### Key decisions',
        '- <pattern / constraint / design choice>',
        '',
        '### Prompt',
        '```',
        '<the prompt that produced this artifact, summarized if over 500 words>',
        '```',
        '---',
        '```',
        'Substantial change = new method / new requirement / pattern change / refactor.',
        'Typos, formatting, and single-line corrections do NOT create a new entry.',
        '',
        '### Lessons Learned (read before acting)',
        'Before implementing anything, scan `.setup-agents/state/evidence.jsonl` for past failures on the same topic:',
        '```bash',
        '# Find relevant lessons for a topic (e.g. "apex", "flow", "deploy", "agent"):',
        'grep -i "<topic>" .setup-agents/state/evidence.jsonl',
        '```',
        'If a matching failure summary exists, read it fully before proceeding — do not repeat known errors.',
        'Also check `docs/strategy/env-audit.md` or any `docs/` markdown that contains lessons-learned tables.',
        '',
        '- **After completing a task**, always run `sa-fast task done --id <id>` — never just close the chat.',
        '- **Evidence is required** before a gate can be approved. Add at least one evidence entry per task.',
    ];
}
/** Generates `setup-agents-autonomous.mdc` — short, directive pre-flight rule that Cursor follows reliably. */
export function generateAutonomousPreFlight(version) {
    return lines(mdcFrontmatter('MANDATORY pre-flight — run sf setup-agents task/workflow commands before ANY work', version), '', '# MANDATORY: Task & Workflow Pre-flight', '', '**BEFORE doing anything else** — before reading files, before planning, before editing — run:', '', '```bash', 'sa-fast task list --json', 'sa-fast workflow pending --json', '```', '', '> `sa-fast` is the fast-path CLI (~200ms). If unavailable, fall back to `sf setup-agents task list --json`.', '', 'Then:', '- Task exists for this work → `sa-fast task claim --id <id>`', '- No task exists → `sa-fast task create --summary "<what you are doing>" --profile developer`', '- Story scope (multi-phase work) → `sf setup-agents workflow run --story <id>`', '- Workflow already active → resume it, do NOT create a new one', '', '**DURING work** — record evidence as you go:', '```bash', 'sa-fast evidence add --task <id> --role <profile> --type <command|file|report|validation> --summary "<text>"', '```', '', '**AFTER completing work** — NEVER close the conversation without:', '```bash', 'sa-fast task done --id <id>', '```', '', '> This is non-negotiable. Skipping pre-flight or task-done breaks workflow tracking.', '> If neither `sa-fast` nor `sf` is available, inform the user immediately instead of proceeding without it.');
}
/** Generates `agent-guidelines.mdc` content. */
export function generateBaseGuidelines(version) {
    return lines(mdcFrontmatter('Agent guidelines for this project', version), '', '# Agent Guidelines', '', '## General Principles', '- Always read existing code before making changes.', '- Prefer editing existing files over creating new ones.', '- Follow the coding conventions already present in this project.', '- Write concise, self-documenting code. Avoid unnecessary comments.', '', '## Language Policy', '- Default all agent-facing outputs to English (CLI messages, docs, workflow text, prompts).', '- Switch to another language only when the user explicitly requests it.', '- Keep one language per artifact; do not mix languages in the same file/output.', '- For Salesforce metadata (labels, descriptions, help text): infer the language from existing metadata. If none exist, default to the language the user is communicating in.', '- If profile rules conflict with language defaults, prioritize project metadata conventions and keep tooling communication in English unless requested otherwise.', '', '## Planning', '- Before modifying any file, present a concise plan of the changes and wait for explicit user confirmation.', '- Do not execute edits until the user confirms with a clear signal ("proceed", "go ahead", "yes", etc.).', '- For changes affecting multiple files or architectural decisions, include a Mermaid diagram in the plan.', '- If the scope grows during execution, pause and re-confirm before continuing.', '', '## Active Job Monitoring', '- When you trigger a deployment, validation, test run, CI pipeline, or any long-running job,', '  you MUST monitor it to completion. Never ask the user to check or suggest reviewing later.', '- Poll or wait for the command to finish, then report: status, duration, and any errors.', '- For CLI commands: wait for return or poll with the relevant report command.', '- For GitHub Actions: use `gh run watch` or poll `gh run view` until `completed`.', '', '## Code Quality', '- Ensure all new code is covered by tests.', '- Do not introduce linter errors or suppress warnings.', '- Handle errors explicitly; never swallow exceptions silently.', '', '## Security', '- Never hardcode credentials, tokens, or sensitive data.', '- Use environment variables or secret managers for sensitive values.', '', '## Command Execution Safety (CRITICAL)', '- **NEVER use `sudo`** — if a command requires elevated privileges, inform the user', '  and let them run it manually. Do not attempt `sudo` in any script or terminal command.', '- **Run CLI tools outside the sandbox** — tools like `gh`, `sf`, `glab`, `az`, `curl` to', '  external APIs, and git push/pull may fail inside a sandboxed environment.', '  When using Cursor, request `required_permissions: ["all"]` for shell commands that', '  need network access or write to paths outside the workspace.', '  When using other tools, instruct the user to run the command in their terminal directly.', '- If a command fails with a permissions or network error, do NOT retry blindly —', '  check whether sandbox restrictions are the cause and advise accordingly.', '', '## Token-Efficient Visual Editing', "- When generating diagrams, push the output to the user's visual tool", '  (Lucidchart, Figma, draw.io, or Mermaid Live Editor) instead of iterating via chat.', '- Visual tweaks (layout, colors, positioning) should be done by the user in the visual tool.', '- Only handle structural changes (add/remove nodes, rename, change relationships) via chat.', '- If no visual tool is configured, suggest the Mermaid Live Editor', '  (mermaid-editor-live.vercel.app) as a free, no-install fallback.', '', '## Autonomous Sub-agent Delegation (CRITICAL)', '- At the START of every task, check whether it spans 2+ profiles in `sub-agent-protocol.mdc`.', '- If yes, DO NOT wait for user instruction — activate sub-agents proactively using the routing table.', '- Signals that require parallel sub-agents: implementation + test + deployment in the same task;', '  design + code + review in the same task; 2+ distinct Salesforce clouds or domains in scope.', '- Every sub-agent invocation MUST include: role declaration, `sourceApiVersion` from `sfdx-project.json`,', '  agreed architectural decisions, and the active profiles list from `sub-agent-protocol.mdc`.', '- Reference routing table: `.cursor/rules/sub-agent-protocol.mdc` (or the equivalent for your tool).', '- **PDF Registry:** before asserting platform capabilities or OOTB coverage, consult `salesforce-pdf-registry.mdc` and WebFetch the relevant PDF.', '', '## Artifact Output Protocol (CRITICAL)', '- When the task output is a file artifact (canvas `.tsx`, markdown, ADR, schema, diagram, test file,', '  source code), **write it to the filesystem at the agreed path BEFORE summarizing in chat**.', '- Never deliver a file artifact as chat-only output. A chat summary is a supplement, not a substitute.', '- Sub-agent handoff MUST include a **Files Written** manifest listing every path written.', '  An empty manifest when artifact output was expected means the phase is NOT complete.', '- Examples of artifacts that MUST be written to disk:', '  `docs/canvases/*.canvas.tsx`, `docs/adr/ADR-*.md`, `docs/reviews/*.md`,', '  `schemas/*.json`, `src/**/*.ts`, `test/**/*.ts`, any file agreed in the task plan.', '', ...riskScaleLines(), '', '## Plugin Workflow', '> Task and workflow commands are defined in `setup-agents-autonomous.mdc`.', '> That file is the single source of truth for pre-flight and task lifecycle. Do not duplicate here.');
}
/** Generates `salesforce-standards.mdc` content. */
export function generateSfStandards(version) {
    return lines(mdcFrontmatter('Salesforce Development Rules & Project Standards (Master Edition v3.0)', version), '', '# Salesforce Development Standards', '', '> You are a Senior Architect for Salesforce Professional Services.', '', '## 1. Codebase Contextualization', '- Search the codebase before answering. Reuse existing patterns and utility classes.', '- Know the location of `force-app/main/default`, `package.xml`, and `/docs`.', '', '## 2. Consultative Design Flow', '- Discuss and agree before modifying files. Provide pros/cons and Mermaid diagrams.', '- For changes affecting 2+ objects or 3+ metadata types, require a diagram first.', '- Summarize all changes before execution.', '', '## 3. Documentation', '- Every `/docs/*.md` must start with the Salesforce Cloud logo header.', '- Author: **Salesforce Professional Services**. Increment version only on significant changes.', '- Always read existing docs before creating new ones to avoid duplication.', '- Keep agent/tooling communication in English by default; switch only on explicit user request.', '', '## 4. Metadata & Manifest', '- `CustomObject` in `package.xml` covers Standard Objects, CMT, Custom Settings, and Custom Objects.', '- For standard picklists, prioritize **StandardValueSets**.', '- API Names: **PascalCase** (English).', '- Labels and descriptions: infer the language from existing metadata. If none exist, ask the user which language to use. Default to the language the user is communicating in.', '', '## 5. Trigger Strategy', '- Exactly **one trigger per object**. Zero logic in triggers.', "- Delegate entirely to the **Kevin O'Hara Trigger Handler**.", '', '## 6. Flow Strategy', '- No Mega-Flows. Use Sub-flows for modularity.', '- Flow Orchestration only for multi-step, multi-user, or long-running processes.', '- One Record-Triggered Flow per object/context (Before/After).', '', '## 7. Sharing Strategy', '- Default: `with sharing` on all Apex classes.', '- Exception: Apex REST classes → always `without sharing`.', '', '## 8. API Version Policy', '- Always read `sfdx-project.json` → `sourceApiVersion` before generating code.', '- Never hardcode an API version; derive it from the project configuration.', '', '## 9. Data Layer & Logic', '- Scan the project for an existing data access pattern (dynamic queries helper, selector layer, etc.).', '- If none found, ask: *"What data layer strategy should I use? (e.g., dynamic query utility, selector pattern, inline SOQL)"*.', '- **No SOQL or DML inside loops.** Always bulkify: handle 1 to N records.', '', '## 10. Naming Conventions', '- Infer naming patterns from the existing project (prefixes, suffixes, casing).', '- If the project has a framework prefix, preserve it as-is. Do not enforce or invent namespaces.', '- If no naming conventions are evident, ask the user before creating new classes/components.', '- Common Salesforce patterns (when user confirms): Test classes `<ClassName>_Test`, Handlers `<ObjectName>TriggerHandler`.', '', '## 11. Async Apex Strategy', '- No fixed pattern. When async need arises, discuss architecture with the developer.', '- Evaluate `@future`, `Queueable`, `Batch`, and `Schedulable` based on the use case.', '', '## 12. Exception Strategy', '- Scan for an existing custom exception class before writing `try-catch`.', '- If none exists, propose one (e.g., `AppException extends Exception`) before coding.', '', '## 13. Security & Validation Rules', '- Bypass validation rules via **Custom Permissions** (`$Permission.Bypass_Validation_Rules`).', '- If the permission does not exist, propose creating it.', '- Sensitive data: Named Credentials and String Replacement tokens for CMT.', '', '## 14. Permission Set Strategy', '- Prefer **Permission Sets** and **Permission Set Groups** over Profiles.', '', '## 15. LWC & Frontend', '- Styling: **SLDS Styling Hooks** over custom CSS.', '- Use **LDS 2** and **Lightning Data Service** whenever possible.', '', '## 16. Error Handling & Observability', '- Scan for existing logging frameworks before writing `try-catch`.', '- Never use `eslint-disable` or `@SuppressWarnings` as a first resort.', '- User feedback: `addError()` (Triggers) or Toasts (LWC) with **Custom Labels**.', '', '## 17. Testing Standards', '- **Exactly one Assert per test method** (modern `Assert` class).', '- Use `@TestSetup` for shared test data.', '- Use `System.runAs()` with Permission Set Group-based test users for permission/sharing tests.', '- Wrap async operations in `Test.startTest()` / `Test.stopTest()`.', '- Target **90% coverage**.', '', '## 18. Deployment', '- Granular deploy: specific modified files only.', '- Full deploy (exception): `sf project deploy validate -d force-app` → `sf project deploy quick`.', '', '## 19. Semantic Commits & Branching', '- Ask for **Backlog Item ID** before suggesting a commit.', '- Format: `type(ID): short description` with a numbered list of changes in the body.', '- Read `git log` to infer the branch naming convention. If unclear, ask the developer.', '', '## 20. Sub-agent Orchestration', '- Pass architectural context and these rules to sub-agents.', '- Sub-agents must follow: one assert per test, zero logic in triggers, Salesforce Professional Services authorship.', '', '## 21. Setup Path Verification (CRITICAL)', '- **NEVER document a Salesforce Setup path without user confirmation.**', '- If you are unsure of the exact navigation path (e.g., Setup > Feature > Sub-feature),', '  use the placeholder: `[Setup > VERIFY PATH > Feature Name]` and ask the user to confirm.', '- Do not guess Setup menu locations — Salesforce UI changes across releases.', '- Before documenting any configuration steps, ask: "Can you confirm the exact Setup path for this feature?"', '', '## 22. Salesforce Documentation Citation (CRITICAL)', '- When explaining how to configure or implement any Salesforce feature, **always reference', '  official Salesforce documentation** from `help.salesforce.com` or `developer.salesforce.com`.', '- Include the URL in the documentation or configuration spec.', '- If no official source is found, explicitly state: "No official Salesforce documentation found for this feature."', '- Never present Salesforce configuration guidance without citing an authoritative source.');
}
/** Generates `sub-agent-protocol.mdc` content. */
export function generateSubAgentProtocol(profiles, version) {
    const roleRegistry = profiles.map((p) => `| ${p.label} | \`${p.ruleFile}\` |`).join('\n');
    const profileMetadata = buildProfileMetadata(profiles);
    const taskRouting = buildTaskRouting(profiles);
    const handoverChecklist = buildHandoverChecklist(profiles);
    const collaborationFlows = buildCollaborationFlows(profiles);
    return lines(mdcFrontmatter('Sub-agent orchestration protocol for this project', version), '', '# Sub-agent Orchestration Protocol', '', '> This file is generated by `sf setup-agents local`. It defines how to assign work to sub-agents', '> and what context to pass during handover. Update it when profiles change.', '', '## Active Profiles', '', '| Role | Rule File |', '|------|-----------|', roleRegistry, ...(profileMetadata
        ? [
            '',
            '## Profile Activation Metadata',
            '',
            'Use this table before spawning or handing off to a sub-agent. Activation signals decide when the profile is relevant; expected evidence and gates define what the profile should produce or review.',
            '',
            profileMetadata,
        ]
        : []), '', '## Task-to-Profile Routing', '', 'When spawning a sub-agent, identify the task type and assign the corresponding profile:', '', taskRouting, '', '## Handover Checklist', '', 'Every sub-agent invocation MUST include:', '', '1. **Role declaration** — state which profile the sub-agent is acting under.', '2. **`sourceApiVersion`** — read from `sfdx-project.json` before passing.', '3. **Agreed architectural decisions** — patterns, data layer strategy, sharing model.', '4. **Profile-specific context:**', '', handoverChecklist, ...(collaborationFlows
        ? [
            '',
            '## Collaboration Flows',
            '',
            'When one profile completes work that feeds into another, follow these handoff chains:',
            '',
            collaborationFlows,
        ]
        : []), '', '## Conflict Resolution', '', 'When a task could fall under multiple profiles:', '- **Architect** takes precedence for design decisions and cross-cutting concerns.', '- **Domain profile** (cgcloud, crma, data360) takes precedence for platform-specific rules.', '- **Developer** handles implementation once design is agreed.', '- **QA** validates after Developer completes implementation.', '', '## Role Rule Injection', '', 'Profile rules are **not all loaded by default** in Claude Code and Codex — only `developer` and `architect`', 'are always imported. When delegating to any other role, include the rule file explicitly in the sub-agent prompt:', '', '```', '# When delegating to BA:', '@.claude/rules/ba.md', '', '# When delegating to Data Cloud:', '@.claude/rules/data360.md', '```', '', 'This applies to: ba, pm, ux, devops, qa, mulesoft, sfmc, service, admin, security, fsl, crma, data360, cgcloud,', 'commerce, cpq, omnistudio, ai, slack, tableau.', '', '## Context Transmission Rule', '', 'Sub-agents must NOT be spawned without:', '- An explicit role declaration from the list above.', '- The relevant rule file injected via `@.claude/rules/<id>.md` (if not always-loaded).', '- The active profiles list (copy the Active Profiles table above).', '- A summary of agreed decisions for the current task.', '', '## Sub-agent Handoff — Files Written Manifest', '', 'Every sub-agent handoff MUST include:', '- **Files Written:** list every file path written to the filesystem during this phase.', '- **Decisions Made:** list key architectural or implementation decisions.', '- **TBDs Raised:** list any open questions that block the next phase.', '- **Runtime Capability Signals:** list concise comma-separated signals the next sub-agent should activate,', '  such as `qa evidence`, `release evidence`, `diagram export`, or `acceptance criteria coverage`.', '', 'An empty **Files Written** section when artifact output was expected means the phase is NOT complete.', 'Do not mark a phase done if the expected artifact (canvas, ADR, schema, test) was not written to disk.');
}
// ─── Internal helpers ──────────────────────────────────────────────────────
const MAX_DESCRIPTION_LENGTH = 255;
export function lintDescriptionLengths(profiles) {
    const violations = [];
    for (const profile of profiles) {
        const content = profile.ruleContent();
        const match = /^description:\s*(\S[^\n]*)$/m.exec(content);
        if (match && match[1].length > MAX_DESCRIPTION_LENGTH) {
            violations.push({ file: profile.ruleFile, description: match[1], length: match[1].length });
        }
    }
    return violations;
}
function mdcFrontmatter(description, version, scope, globs) {
    const globsLine = scope === 'auto-attach' && globs && globs.length > 0 ? `globs: ${globs.join(', ')}` : 'globs:';
    const alwaysApply = !scope || scope === 'always' ? 'alwaysApply: true' : 'alwaysApply: false';
    return lines('---', `description: ${description}`, globsLine, alwaysApply, `pluginVersion: "${version}"`, '---');
}
function buildTaskRouting(profiles) {
    const rows = [];
    const ids = new Set(profiles.map((p) => p.id));
    if (ids.has('ta'))
        rows.push({
            task: 'Architecture decisions, ADRs, pattern selection, cross-cutting concerns',
            profile: 'Technical Architect',
            ruleFile: 'ta-standards.mdc',
        });
    if (ids.has('sa'))
        rows.push({
            task: 'Scope analysis, solution design, story templating (OmniStudio/Flow/Experience Cloud)',
            profile: 'Solution Architect',
            ruleFile: 'sa-standards.mdc',
        });
    if (ids.has('developer'))
        rows.push({
            task: 'Apex, LWC, Triggers, SOQL, DML, unit tests',
            profile: 'Developer',
            ruleFile: 'developer-standards.mdc',
        });
    if (ids.has('ba'))
        rows.push({
            task: 'User stories, acceptance criteria, Flow configuration, process documentation',
            profile: 'Business Analyst',
            ruleFile: 'ba-standards.mdc',
        });
    if (ids.has('ux'))
        rows.push({
            task: 'LWC UI components, SLDS styling, accessibility, design tokens',
            profile: 'UX / UI',
            ruleFile: 'ux-standards.mdc',
        });
    if (ids.has('cgcloud'))
        rows.push({
            task: 'CGCloud extension points, Modeler configuration, cgcloud__ namespace',
            profile: 'CGCloud Developer',
            ruleFile: 'cgcloud-standards.mdc',
        });
    if (ids.has('crma'))
        rows.push({
            task: 'Recipes, Dataflows, Datasets, SAQL, Dashboards, security predicates',
            profile: 'Analytics Engineer',
            ruleFile: 'analytics-standards.mdc',
        });
    if (ids.has('data360'))
        rows.push({
            task: 'Data Streams, DMOs, Identity Resolution, Calculated Insights, Segments, Activation',
            profile: 'Data Cloud Engineer',
            ruleFile: 'data360-standards.mdc',
        });
    if (ids.has('mulesoft'))
        rows.push({
            task: 'API design (RAML/OAS), Mule flows, integrations, MUnit tests',
            profile: 'MuleSoft Developer',
            ruleFile: 'mulesoft-standards.mdc',
        });
    if (ids.has('devops'))
        rows.push({
            task: 'Pipelines, deployment validation, scratch orgs, package versioning',
            profile: 'DevOps Engineer',
            ruleFile: 'devops-standards.mdc',
        });
    if (ids.has('qa'))
        rows.push({
            task: 'Playwright tests, Page Objects, accessibility automation, test reports',
            profile: 'QA Engineer',
            ruleFile: 'qa-standards.mdc',
        });
    if (rows.length === 0)
        return '- No specific profiles active. Use `agent-guidelines.mdc` as base.';
    return rows
        .map((r) => `| ${r.task} | **${r.profile}** | \`${r.ruleFile}\` |`)
        .reduce((acc, row) => `${acc}\n${row}`, '| Task Type | Assigned Role | Rule File |\n|-----------|--------------|-----------|');
}
function buildProfileMetadata(profiles) {
    if (profiles.length === 0)
        return '';
    const rows = profiles.map((profile) => {
        const metadata = getProfileOrchestrationMetadata(profile);
        return `| ${profile.label} | ${metadata.activationCriteria.join('; ')} | ${metadata.expectedEvidence.join('; ')} | ${metadata.gates.join('; ')} |`;
    });
    return rows.reduce((acc, row) => `${acc}\n${row}`, '| Profile | Activation Signals | Expected Evidence | Gates |\n|---------|--------------------|-------------------|-------|');
}
function buildHandoverChecklist(profiles) {
    return profiles
        .map((p) => {
        const content = p.ruleContent().split('\n');
        const start = content.findIndex((l) => l.startsWith('## Sub-agent Handover'));
        if (start === -1)
            return `- **${p.label}:** see \`${p.ruleFile}\``;
        const items = content
            .slice(start + 1)
            .filter((l) => l.startsWith('- '))
            .join('\n  ');
        return `**${p.label}:**\n  ${items}`;
    })
        .join('\n\n');
}
const COLLABORATION_FLOW_DEFS = [
    {
        from: 'pm',
        to: 'ba',
        label: 'PM → BA',
        description: 'PM defines sprint scope and priorities. BA refines stories with acceptance criteria and personas.',
    },
    {
        from: 'ba',
        to: 'sa',
        label: 'BA → SA',
        description: 'BA passes refined stories. SA produces scope analysis and solution design grounded in metadata.',
    },
    {
        from: 'sa',
        to: 'ta',
        label: 'SA → TA',
        description: 'SA hands off solution design. TA validates architecture patterns, ADRs, and Well-Architected compliance.',
    },
    {
        from: 'ta',
        to: 'developer',
        label: 'TA → Developer',
        description: 'TA hands off agreed patterns, ADR references, and data layer strategy. Developer implements.',
    },
    {
        from: 'ta',
        to: 'ux',
        label: 'TA → UX',
        description: 'TA defines component boundaries. UX designs within SLDS constraints and produces the LWC Interaction Checklist.',
    },
    {
        from: 'ta',
        to: 'mulesoft',
        label: 'TA → MuleSoft',
        description: 'TA defines integration points and Named Credentials. MuleSoft implements API-led flows.',
    },
    {
        from: 'developer',
        to: 'qa',
        label: 'Developer → QA',
        description: 'Developer deploys to sandbox and confirms test data. QA writes Playwright tests against the deployed feature.',
    },
    {
        from: 'qa',
        to: 'devops',
        label: 'QA → DevOps',
        description: 'QA confirms all tests pass. DevOps proceeds with validation and production deployment.',
    },
    {
        from: 'devops',
        to: 'pm',
        label: 'DevOps → PM',
        description: 'DevOps reports deployment result (pass/fail, duration). PM updates status report and release calendar.',
    },
];
function buildCollaborationFlows(profiles) {
    const ids = new Set(profiles.map((p) => p.id));
    const flows = COLLABORATION_FLOW_DEFS.filter((def) => ids.has(def.from) && ids.has(def.to)).map((def) => `- **${def.label}:** ${def.description}`);
    if (flows.length === 0)
        return '';
    return flows.join('\n');
}
//# sourceMappingURL=mdc-generator.js.map