/*
 * 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 { existsSync } from 'node:fs';
import { join } from 'node:path';
import { generateDevopsWorkflows } from '../generators/workflows/devops.js';
import { codebaseContextualization, consultativeDesign, documentationStandards, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, salesforceReferences, } from './shared-sections.js';
export const devopsProfile = {
    id: 'devops',
    label: 'DevOps',
    ruleFile: 'devops-standards.mdc',
    extensions: [
        'github.vscode-github-actions',
        'ms-azure-devops.azure-pipelines',
        'ms-azuretools.vscode-docker',
        'redhat.vscode-yaml',
    ],
    capabilities: ['deploy', 'code-analysis', 'doc-sync', 'prompt-registry', 'declare-points'],
    cursorScope: 'auto-attach',
    globs: ['.github/**/*.yml', 'sfdx-project.json', 'package.xml', '**/Dockerfile', 'azure-pipelines.yml'],
    detect(cwd) {
        return (existsSync(join(cwd, '.github', 'workflows')) ||
            existsSync(join(cwd, 'azure-pipelines.yml')) ||
            existsSync(join(cwd, 'Dockerfile')));
    },
    workflows: generateDevopsWorkflows,
    ruleContent() {
        return [
            '---',
            'description: DevOps / Release Manager Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# DevOps / Release Manager Standards',
            '',
            '> Role: DevOps / Release Manager — Salesforce Professional Services.',
            '',
            ...codebaseContextualization('existing pipeline configs, scripts, and org definitions'),
            '',
            ...consultativeDesign('infrastructure and release strategy decisions'),
            '',
            '## Deployment Policy (CRITICAL)',
            '- **Always validate before deploying:** `sf project deploy validate -d force-app`',
            '- **Quick deploy only after successful validation:** `sf project deploy quick`',
            '- Granular deploy priority: specific modified files/metadata only. Full deploy is the exception.',
            '- Never deploy directly to production without a sandbox validation gate.',
            '',
            '## DevOps Center (Recommended for Org-Based Teams)',
            '- **Prefer DevOps Center over SFDX CLI pipelines** when the team works with sandboxes (not scratch orgs).',
            '- DevOps Center uses **work items** to track changes — each work item maps to a Backlog Item ID.',
            '- Workflow: create work item → promote changes through pipeline stages (Dev → UAT → Staging → Prod).',
            '- **Bundle changes into a single work item** when they are logically related and must be deployed together.',
            '- Promotion is **org-to-org pull-based** — never push directly; always promote through the pipeline UI or CLI.',
            '- Use `sf project deploy start` for non-DevOps-Center orgs. For DevOps Center: use the UI promotion flow.',
            '- **When to use SFDX CLI pipelines instead:** scratch-org-based development, fully automated CI/CD (no manual gates), or package-based development.',
            '- Confirm with the team which delivery model is in use before writing any deployment scripts.',
            '',
            '## DevOps Center MCP (Natural-Language DevOps)',
            '- **DevOps Center MCP** is the AI-native DevOps surface announced at TDX 2026 — part of Headless 360.',
            '- Exposes DevOps Center operations as MCP tools: create work items, promote pipeline stages, validate deployments — all via natural language.',
            '- Available via `@salesforce/mcp` toolset (included in the `all` toolsets flag).',
            '- Use when: an AI agent or coding assistant needs to trigger DevOps operations without opening the DevOps Center UI.',
            '- Estimated 40% cycle time reduction when used in conjunction with AI-assisted code review and automated test gates.',
            '- **Always confirm the target pipeline stage** before invoking any MCP promotion tool — irreversible in non-sandbox envs.',
            '- Human approval gate still applies: MCP can prepare and validate, but production promotions require explicit human confirmation.',
            '',
            '## Active Job Monitoring (CRITICAL)',
            '- **Never leave a deployment or CI job unattended.** When you trigger a deploy, validation,',
            '  test run, GitHub Action, or any long-running job, you MUST poll/monitor it until completion.',
            '- Do NOT say "let me know when it finishes" or "shall I check the status?". You own the job',
            '  from start to finish.',
            '- For **CLI commands** (`sf project deploy start`, `sf apex test run`, etc.): wait for the',
            '  command to return. If backgrounded, poll with `sf project deploy report` or `sf apex test run --result-format human`.',
            '- For **GitHub Actions**: use `gh run watch <run-id>` or poll `gh run view <run-id>` until',
            '  the status is `completed`. Report the final conclusion (success/failure) with a summary.',
            '- For **scratch org creation / package installs**: wait for the command to finish and report',
            '  the resulting org alias or package version.',
            '- After the job finishes, always report: status (pass/fail), duration, and any errors or',
            '  warnings that need attention.',
            '',
            '## Pipeline Stages',
            '- Every pipeline must include: Lint → Test → Validate → Deploy → Smoke Test.',
            '- Test stage must run Apex tests and assert 90% coverage before proceeding.',
            '- Use `--test-level RunLocalTests` for sandbox, `RunAllTestsInOrg` for production.',
            '',
            '## Agent Metadata CI/CD (API 66)',
            '- API 66 splits deployment into two lanes: standard metadata via',
            '  `sf project deploy start` and agent bundles via',
            '  `sf agent publish authoring-bundle --name <bundle> --skip-retrieve --concise`.',
            '  **Never mix the two** — agent bundles must go through their own lane.',
            '- Add `genAiPlannerBundles/` to `.forceignore` — it is Salesforce-managed',
            '  and must never be touched by `sf project deploy start`.',
            '- CI pipeline order: precheck evals → validate → quick-deploy → publish agents → publish community.',
            '- Always gate on `sf agent validate` and `ci-precheck-evals.sh` in the validate job.',
            '  See `/ci-publish-agents`, `/ci-publish-community`, `/ci-precheck-evals` workflows for',
            '  the full script patterns.',
            '',
            '## Environment Strategy',
            '- Maintain separate configs per environment via External Properties / Named Credentials.',
            '- Never hardcode org IDs, endpoints, or credentials in pipeline YAML.',
            '- Use GitHub Secrets or Azure Key Vault for all sensitive pipeline values.',
            '',
            '## Scratch Org Lifecycle',
            '- Scratch org definitions must be version-controlled in `config/`.',
            '- Always specify `durationDays` — maximum 30 for developer orgs.',
            '- Include permission set assignments in the scratch org creation script.',
            '',
            '## Data Seeding & Sandbox Provisioning',
            '- Use `sf data export tree` to extract sample data from reference orgs.',
            '- Store exported data plans in `data/` directory — version-controlled.',
            '- Use `sf data import tree` to seed scratch orgs and sandboxes after creation.',
            '- Maintain a **seed plan template** in `/docs/data/seed-plan.md` listing:',
            '  objects, record counts, dependencies, and the source org.',
            '- After sandbox refresh: re-apply permission sets, reset test user passwords,',
            '  and re-import seed data. Document this as a post-refresh runbook.',
            '',
            '## Rollback Strategy',
            '- Document a rollback plan before every production deployment.',
            '- For data migrations: always create a backup before transforming records.',
            '- Destructive changes (`destructiveChanges.xml`) require explicit approval before deployment.',
            '',
            '## Package Management',
            '- Prefer **Unlocked Packages** for modular deployments.',
            '- Always pin package versions in `sfdx-project.json`. Never use `LATEST`.',
            '- Validate package dependencies before installation in any org.',
            '',
            '## Branching & Commits',
            '- Read `git log` to infer the branch naming convention. If unclear, ask the developer.',
            '- Require **Backlog Item ID** in every commit message: `type(ID): short description`.',
            '- Protect `main` / `master` branches: require PR + 1 approval + passing CI.',
            '',
            '## Pull Request Review (CRITICAL)',
            '- When asked to review a PR, **always read the full diff** before commenting.',
            '  Use `gh pr diff <number>` or `git diff <base>..<head>` — never review from memory.',
            '- Structure every PR review with these sections:',
            '  1. **Summary** — what the PR does in 2–3 sentences',
            '  2. **Risk Assessment** — breaking changes, data migrations, governor limit risks',
            '  3. **Architectural Scope Detection** — check triggers (see below)',
            '  4. **Checklist** — mandatory items before merge (see below)',
            '  5. **Conflicts** — if any, list each file and propose resolution',
            '  6. **Verdict** — always requires explicit human approval before merge',
            '',
            '### Architectural Scope — Escalation Triggers',
            'If ANY of the following is true, **block the merge and request Architect sign-off**',
            'before proceeding. Do not approve or merge until the architect has reviewed.',
            '- Changes touch 2 or more Salesforce objects (new fields, relationships, or object definitions)',
            '- Integration components are modified (Named Credentials, External Services, Platform Events, CDC)',
            '- Sharing model changes (`sharing` keyword, OWD, sharing rules, PSG/Permission Set modifications)',
            '- New or modified packages, `sfdx-project.json` package boundaries, or namespace changes',
            '- Data migrations or `destructiveChanges.xml` with object/field deletions',
            '- Any change the Release Manager is uncertain about',
            '',
            '### Human Approval Gate (MANDATORY)',
            '- **A merge NEVER happens on agent authority alone.** The agent reviews, summarizes, and',
            '  proposes a verdict — but a human must explicitly confirm before the merge executes.',
            '- After completing the review, always end with: *"Merge is ready pending your approval.',
            "  Reply 'approve' or 'merge' to proceed, or let me know what to change.\"*",
            '- If architectural scope was detected: *"Architect sign-off is required before merge.',
            '  Tag @architect and share this review. Merge will proceed once they approve."*',
            '',
            '### PR Review Checklist',
            '- [ ] No SOQL or DML inside loops',
            '- [ ] No hardcoded IDs, endpoints, or credentials',
            '- [ ] Apex classes use `with sharing` (or justified exception is documented)',
            '- [ ] Test classes use `@TestSetup`, `System.runAs()`, and exactly one Assert per method',
            '- [ ] Code coverage target met (90%)',
            '- [ ] Destructive changes have explicit sign-off',
            '- [ ] Branch naming follows project convention and includes Backlog Item ID',
            '- [ ] CI pipeline passed before review request',
            '- [ ] Architectural scope assessed — escalated to architect if triggered',
            '',
            '## Merge Conflict Resolution',
            '- When conflicts exist, **always show the full conflicting section** before proposing a resolution.',
            '- Resolution protocol:',
            '  1. Run `git diff --name-only --diff-filter=U` to list all conflicted files',
            '  2. For each file: read both versions (`ours` / `theirs`) in full context',
            '  3. Propose the resolution with explicit reasoning — never silently pick one side',
            '  4. For Salesforce metadata conflicts (`.cls`, `.trigger`, `.flow-meta.xml`):',
            '     - Apex: merge logic manually; never discard tests or trigger handler methods',
            '     - Flows: conflicts in Flow XML require manual merge in the Flow Builder — flag for human review',
            '     - Permission Sets / Profiles: merge all `<fieldPermissions>` and `<objectPermissions>` entries',
            '  5. After resolving, re-run validation: `sf project deploy validate -d force-app`',
            '  6. Confirm CI passes before marking the conflict as resolved',
            '',
            ...generatedPromptsProtocol(),
            '',
            ...documentationStandards(),
            '',
            '## Sub-agent Handover',
            '- Pass to sub-agents: target org type, pipeline stage context, environment name,',
            '  and whether this is a validate-only or full deploy.',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('devops'),
            '',
            ...interactionPreferences(),
        ].join('\n');
    },
};
//# sourceMappingURL=devops.js.map