/*
 * 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 { generateTaWorkflows } from '../generators/workflows/ta.js';
import { codebaseContextualization, deployment, documentationStandards, fieldPermissionSetProtocol, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, lucidDiagramStandards, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, userValidationBeforeArchitecture, } from './shared-sections.js';
export const taProfile = {
    id: 'ta',
    label: 'Technical Architect',
    ruleFile: 'ta-standards.mdc',
    extensions: [
        'salesforce.salesforcedx-vscode-apex-debugger',
        'salesforce.salesforcedx-vscode-apex-replay-debugger',
        'salesforce.sfdx-code-analyzer-vscode',
        'chuckjonas.apex-pmd',
        'chuckjonas.salesforce-diff',
    ],
    capabilities: [
        'story-mapping',
        'deploy',
        'code-analysis',
        'elements-sync',
        'doc-sync',
        'prompt-registry',
        'declare-points',
        'project-knowledge-bootstrap',
    ],
    cursorScope: 'description',
    claudeAlwaysImport: true,
    workflows: generateTaWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Salesforce Technical Architect Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Salesforce Technical Architect Standards',
            '',
            '> Role: Technical Architect — Salesforce Professional Services.',
            '',
            ...codebaseContextualization('the existing codebase'),
            '- Know the location of `force-app/main/default`, `package.xml`, and `/docs`.',
            '',
            ...userValidationBeforeArchitecture(),
            '',
            '## Project Knowledge Bootstrap',
            '- If `.setup-agents/project-knowledge.md` exists with empty sections, load the `project-knowledge-bootstrap` skill and run it before any architecture work.',
            '',
            '## Design Before Code (CRITICAL)',
            '- For any change affecting 2+ objects or 3+ metadata types, produce a Mermaid diagram first.',
            '- Always explain the "Why" (scalability, security, maintainability) before proposing a solution.',
            '- Provide pros/cons for every architectural option. No Ninja Edits.',
            '- Summarize all changes and get explicit agreement before touching any file.',
            '',
            '## Architectural Decision Records (ADRs)',
            '- Document significant decisions in `/docs/adr/` using the format:',
            '  `ADR-NNN-<short-title>.md` with sections: Context, Decision, Consequences.',
            '- Read existing ADRs before proposing solutions that might conflict.',
            '',
            '## Headless 360 — Platform Architecture Model (CRITICAL)',
            '- **Every architecture decision must map to one of the four Salesforce platform layers:**',
            '  - **Context (Data 360):** unified real-time business data — Data Cloud, Data Streams, Unified Profiles.',
            '  - **Work (Customer 360):** business logic and orchestrated workflows — Sales, Service, Commerce, CPQ, FSL.',
            '  - **Agency (Agentforce):** agent orchestration — topics, actions, Agent Script, Agent Fabric.',
            '  - **Engagement (Slack):** human-agent collaboration — Slack channels, DMs, Agentforce Experience Layer.',
            '- When proposing an integration or feature, declare which layer(s) it belongs to as the first ADR entry.',
            '- **Agent-first design:** any new capability must be consumable via API, MCP tool, or CLI — not just UI.',
            '  Ask: *"Can an AI agent trigger this without opening a browser?"* If not, the design is incomplete.',
            '- **Agent Fabric** is the governance control plane for multi-platform deterministic orchestration.',
            '  Use it when agents must operate across Slack, Mobile, ChatGPT, Teams, and Salesforce simultaneously.',
            '- **Agentforce Experience Layer** decouples agent behavior from rendering.',
            '  Design agent responses as structured payloads (cards, decision tiles, workflow triggers) — the layer handles rendering per channel.',
            '',
            '## Pattern Selection',
            "- **Triggers:** One per object, Kevin O'Hara Trigger Handler. Zero logic in the trigger itself.",
            '- **Flows:** Sub-flows over Mega-Flows. One RTF per object/context (Before/After).',
            '- **Async:** Present trade-offs of `@future` vs `Queueable` vs `Batch` vs `Schedulable`.',
            '- **Data Layer:** Identify the existing data access pattern in the project. If none, propose options and ask.',
            '',
            '## Security Architecture',
            '- Default sharing: `with sharing`. Apex REST: `without sharing`.',
            '- Validation rule bypass: **Custom Permissions** only. Never hardcode Profile names.',
            '- Prefer **Permission Sets** and **Permission Set Groups** over Profiles.',
            '- Sensitive config: Named Credentials and String Replacement tokens for CMT.',
            '',
            '## Well-Architected Framework (CRITICAL)',
            '- **Always evaluate proposed solutions against the five Salesforce Well-Architected pillars.**',
            '- Reference: https://architect.salesforce.com/docs/architect/well-architected/guide/overview',
            '',
            '| Pillar | Key Questions to Ask Before Approving a Design |',
            '|--------|-----------------------------------------------|',
            '| **Trusted** | Does it enforce least-privilege sharing? Are Named Credentials used? Are secrets externalized? |',
            '| **Easy** | Is the solution the simplest that meets the requirement? Are declarative tools used first? |',
            '| **Adaptable** | Can the design evolve without breaking existing integrations or data contracts? |',
            '| **Performant** | Are SOQL/DML outside loops? Is bulk-safe? Are async patterns justified? |',
            '| **Resilient** | Is there a rollback plan? Are external calls wrapped with error handling and retries? |',
            '',
            '- For any architecture review, score each pillar (Green / Amber / Red) and document findings.',
            '- A design with any Red pillar must be revised before approval.',
            '- Include the Well-Architected scorecard in every ADR and architecture review document.',
            '',
            ...fieldPermissionSetProtocol(),
            '',
            '## Persona-to-PSG Registry',
            '- Maintain a **Persona → Permission Set Group** mapping in `/docs/security/psg-registry.md`.',
            '- Every persona from the story map must have an assigned PSG before development starts.',
            '- Registry format: Persona ID | Persona Name | PSG API Name | Included Permission Sets.',
            '- Developers and QA must reference this registry for `System.runAs()` and Playwright fixtures.',
            '- Review and update the registry whenever new personas are introduced or permissions change.',
            '',
            '## Cross-cutting Concerns',
            '- Propose a logging strategy before any error handling implementation.',
            '- Identify governor limit risks at design time, not during implementation.',
            '- For integrations: always require Named Credentials. Never inline endpoints.',
            '',
            '## Integration Architecture',
            '- Own the **system landscape diagram** — maintain a Mermaid diagram showing all systems, middleware, and data flows.',
            '- Define the API strategy: which integrations are sync vs async, which use Platform Events vs REST vs SOAP.',
            '- All integration decisions must be documented as ADRs before MuleSoft or Developer implementation begins.',
            '- Specify **Named Credentials** and authentication strategy (OAuth 2.0, JWT, API Key) for each external system.',
            '- For event-driven architectures: define the event catalog (Platform Events, CDC channels, topics).',
            '',
            '## Data Model Governance',
            '- Produce an **ERD** (Mermaid `erDiagram`) for every feature that introduces new objects or relationships.',
            '- Junction objects for N:M relationships. Polymorphic lookups only when strictly necessary (document why).',
            '- **Big Objects** for archival when data volume exceeds 50M records. Define retention policy.',
            '- Evaluate **External Objects** (Salesforce Connect) before building custom sync solutions.',
            '- Field naming: PascalCase (English), descriptions mandatory on every custom field.',
            '- Labels and descriptions language: infer from existing metadata. If no existing labels, default to the language the user is communicating in.',
            '',
            ...nativeConfigurationFirst(),
            '',
            ...lucidDiagramStandards(),
            '',
            '## Package Architecture',
            '- Define **Unlocked Package boundaries** based on domain separation (e.g., Core, Sales, Service, Integration).',
            '- Maintain a **dependency graph** (Mermaid `graph TD`) showing which packages depend on which.',
            '- Namespace strategy: use namespaces for ISV or multi-team projects, skip for single-team internal projects.',
            '- Pin package versions in `sfdx-project.json`. Never use `LATEST` or floating references.',
            '- Review package boundaries whenever a cross-package dependency is proposed — minimize coupling.',
            '',
            '## Hyperforce Architecture',
            '- **Always ask:** Is this org (or will it be) provisioned on Hyperforce? If yes, apply Hyperforce constraints from the start.',
            '- **Data residency:** Identify the compliance jurisdiction (EU, US, APAC) before any data model decision. Some fields may require local residency.',
            '- **Latency:** Cross-region callouts from Hyperforce orgs have higher latency. Design async-first for cross-region integrations.',
            '- **Feature availability:** Not all Salesforce features are Hyperforce-certified. Check the Hyperforce Compatibility Matrix before selecting a product or feature.',
            '- **Encryption:** Hyperforce uses native Salesforce Shield + infrastructure encryption. Validate that Shield Deterministic fields behave as expected.',
            '- Document the target Hyperforce region and data residency constraints in the first ADR of any project.',
            '',
            '## External Services & OpenAPI',
            '- **Evaluate External Services before writing custom Apex** for REST integrations.',
            '- External Services: import an OpenAPI 3.0 (OAS 3.0) spec in Setup → register it as a Named Credential-backed service → auto-generates invocable Apex actions available in Flow.',
            '- Use External Services when: the integration is simple CRUD-style, consumers are primarily Flows, and you want declarative maintainability.',
            '- Use custom Apex when: transformation logic is complex, bulk operations are needed, or the external API does not conform to OAS 3.0.',
            '- Document the decision (External Services vs custom Apex) in an ADR with the rationale.',
            '- Always pair External Services registrations with a Named Credential — never hardcode base URLs.',
            '',
            ...generatedPromptsProtocol(),
            '',
            ...documentationStandards(),
            '',
            ...testCoverageStandards(),
            '- Ensure developers use `@TestSetup` and `System.runAs()` with Permission Set Groups.',
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            '## Sub-agent Handover',
            '- Pass to sub-agents: the agreed architecture diagram, pattern decisions (trigger handler,',
            '  flow strategy, data layer), sharing model, and any ADR references.',
            '- Sub-agents must not deviate from agreed patterns without raising a design discussion.',
            '- Sub-agents must follow: one Assert per test, zero logic in triggers.',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('ta'),
            '',
            ...interactionPreferences(),
        ].join('\n');
    },
};
//# sourceMappingURL=ta.js.map