/*
 * 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.
 */
/**
 * Shared rule sections used across multiple profiles.
 * Each function returns an array of lines (no trailing empty string)
 * that can be spread into a profile's ruleContent() array.
 */
const SF_LOGO_URL = 'https://cdn.prod.website-files.com/691f4b0505409df23e191b87/69416b267de7ae6888996981_logo.svg';
export function codebaseContextualization(domain = 'codebase patterns and utilities') {
    return [
        '## Codebase Contextualization',
        `- **Always scan existing ${domain}** before proposing changes.`,
        '- Read `.setup-agents/project-knowledge.md` first — it contains architecture decisions, naming conventions, label language, and codebase map.',
        '- If project-knowledge.md is missing or incomplete, ask the user before assuming conventions.',
        '- Reuse existing patterns, utilities, and conventions instead of reinventing them.',
    ];
}
export function documentationStandards() {
    return [
        '## Documentation Standards',
        '- Every `/docs/*.md` must start with the Salesforce Cloud logo header:',
        `  \`![Salesforce Cloud](${SF_LOGO_URL})\``,
        '- Author: **Salesforce Professional Services**. Version: increment on significant changes.',
        '- Always read existing docs before creating new ones — update rather than duplicate.',
    ];
}
export function semanticCommits() {
    return [
        '## Semantic Commits',
        '- Ask for **Backlog Item ID** before suggesting any commit.',
        '- Format: `type(ID): short description`.',
        '- Body: numbered list of changes + value proposition paragraph.',
    ];
}
export function interactionPreferences(justificationDomain = 'architectural') {
    return [
        '## Interaction Preferences',
        `- Concise, but detailed in ${justificationDomain} justifications.`,
        '- Correct mistakes directly without apologizing.',
    ];
}
export function consultativeDesign(prosConsTopic = 'non-trivial technical decisions') {
    return [
        '## Consultative Design (CRITICAL)',
        '- **No Ninja Edits.** Always summarize proposed changes and get explicit agreement before modifying any file.',
        `- Provide pros/cons for ${prosConsTopic} before implementing.`,
    ];
}
export function userValidationBeforeArchitecture() {
    return [
        '## PO/BA User Validation Gate (CRITICAL)',
        '- Product Owner / BA work must validate user stories, definitions, assumptions, acceptance criteria, non-goals, and priority with the user before architecture starts.',
        '- Do not hand work to Architect as ready-for-design while user-facing scope or expected behavior is still ambiguous.',
        '- Record open questions and keep the work in refinement when validation is missing.',
        '- Architect must reject architecture handoff when acceptance criteria, definitions, assumptions, non-goals, or priority are not user-validated.',
    ];
}
export function salesforceReferences() {
    return [
        '## Salesforce Reference Documentation',
        'Prefer these official sources when researching platform behavior, APIs, or standards.',
        '',
        '### Local Cache (check first)',
        '- Before fetching any doc URL, check `.setup-agents/references/` for a cached copy.',
        '  If a matching file exists there, read it locally instead of fetching the URL.',
        '- Run `sf setup-agents update --fetch-refs` to pre-populate the cache.',
        '',
        '### Doc Retrieval Protocol',
        'Salesforce docs come in three types — use the correct recovery method for each:',
        '',
        '**Type 1 — Atlas-style** (URL pattern: `/docs/atlas.en-us.{guide}.meta/...`)',
        '- 17 KB SPA shell, 0 HTML content. `get_document` API returns 0 bytes without auth.',
        '- **Recovery: PDF only.** Use the PDF at `resources.docs.salesforce.com/latest/latest/en-us/sfdc/pdf/{name}.pdf`.',
        '',
        '**Type 2 — New-style LWR** (URL pattern: `/docs/{product}/{guide}.html`)',
        '- ~64 KB, partial SSR: `<h1>` + intro paragraphs + TOC. Full content loads via JS at runtime.',
        '- **Recovery: WebFetch the URL for intro/TOC only.** For complete content use the corresponding PDF.',
        '',
        '**Type 3 — Direct PDFs** (`resources.docs.salesforce.com/.../sfdc/pdf/*.pdf`)',
        '- Full content, no JS. **Recovery: WebFetch the PDF URL directly.**',
        '',
        '### Core Platform',
        '- **Data Models (Type 2):** https://developer.salesforce.com/docs/platform/data-models',
        '- **Apex Developer Guide (Type 1 → PDF):** https://resources.docs.salesforce.com/latest/latest/en-us/sfdc/pdf/salesforce_apex_language_reference.pdf',
        '- **Metadata API Developer Guide (Type 1 → PDF):** https://resources.docs.salesforce.com/latest/latest/en-us/sfdc/pdf/api_meta.pdf',
        '- **SOQL & SOSL Reference (Type 1 → PDF):** https://resources.docs.salesforce.com/latest/latest/en-us/sfdc/pdf/salesforce_soql_sosl.pdf',
        '- **APIs (Type 2):** https://developer.salesforce.com/docs/apis',
        '- **Metadata Coverage (Type 2):** https://developer.salesforce.com/docs/metadata-coverage',
        '',
        '### Salesforce Architect',
        '- **Architect Hub:** https://architect.salesforce.com/',
        '- **Well-Architected Framework:** https://architect.salesforce.com/docs/architect/well-architected/guide/overview',
        '- **Diagram Standards:** https://architect.salesforce.com/diagrams',
        '- **Reference Diagrams Guide:** https://architect.salesforce.com/docs/architect/reference-diagrams/guide/introduction',
        '',
        '### Developer Centers',
        '- **LWC:** https://developer.salesforce.com/developer-centers/lightning-web-components',
        '- **Experience Cloud:** https://developer.salesforce.com/developer-centers/experience-cloud',
        '- **Commerce Cloud:** https://developer.salesforce.com/developer-centers/commerce-cloud',
        '- **Data Cloud:** https://developer.salesforce.com/developer-centers/data-cloud',
        '- **CRM Analytics:** https://developer.salesforce.com/developer-centers/crm-analytics',
        '- **LWC for Mobile:** https://developer.salesforce.com/developer-centers/lwc-for-mobile',
        '- **Mobile:** https://developer.salesforce.com/developer-centers/mobile',
        '- **Service SDK:** https://developer.salesforce.com/developer-centers/service-sdk',
        '',
        '### Lightning & LWC Guides',
        '- **Lightning Types Guide (Type 2):** https://developer.salesforce.com/docs/platform/lightning-types/guide',
        '',
        '### Commerce',
        '- **B2B & B2C Commerce Developer Guide (Type 2):** https://developer.salesforce.com/docs/commerce/salesforce-commerce/guide/b2b-b2c-comm-dev-guide.html',
        '',
        '### Agentforce & AI',
        '- **Agentforce Developer Guide (Type 2):** https://developer.salesforce.com/docs/einstein/genai/guide/agentforce-developer-guide.html',
        '',
        '### Data Cloud',
        '- **Data Cloud Developer Guide (Type 3 — PDF):** https://resources.docs.salesforce.com/latest/latest/en-us/sfdc/pdf/data_cloud.pdf',
        '',
        '### Design',
        '- **SLDS 2:** https://www.lightningdesignsystem.com/2e1ef8501/p/85bd85-lightning-design-system-2',
        '',
        '### Updates & Blogs',
        '- **Salesforce Developer Blog:** https://developer.salesforce.com/blogs',
    ];
}
export function generatedPromptsProtocol() {
    return [
        '## Generated Prompts Registry (CRITICAL — do not skip)',
        '- The project keeps `.generated-prompts/` at the repo root — one file per artifact type',
        '  (`apex.md`, `lwc.md`, `flows.md`, `triggers.md`, `diagrams.md`, `cicd.md`, etc.).',
        '- **Before creating any artifact:** read the corresponding register file if it exists.',
        '  Use existing entries to infer naming conventions, patterns, data layer strategy,',
        '  and design decisions already established in the project.',
        '- **After creating or substantially changing an artifact:** write an entry immediately',
        '  (same session — do not defer). Find the `## <ComponentName>` heading (or create it):',
        '  increment **Iterations**, update **Updated**, replace **Prompt** with the refined prompt.',
        '- Never stack versions — only the latest prompt lives in the entry.',
        '- **Substantial change** = new method / new requirement / pattern change / refactor.',
        '  Typos, formatting, and single-line corrections do NOT update the entry.',
        '',
        '  Entry format:',
        '  ```markdown',
        '  ## <ComponentName>',
        '  - **Created:** YYYY-MM-DD',
        '  - **Updated:** YYYY-MM-DD',
        '  - **Iterations:** N',
        '',
        '  ### Key decisions',
        '  - <pattern / constraint / design choice>',
        '',
        '  ### Prompt',
        '  ```',
        '  <prompt summarized to key decisions if over 500 words>',
        '  ```',
        '  ---',
        '  ```',
    ];
}
export function lucidDiagramStandards() {
    return [
        '## Lucid Diagram Standards (Salesforce Design Tokens)',
        '- **Do not use the Lucid MCP to search for assets** — the server has no shape library or assets at this time.',
        '  Use the MCP only to read or write diagram documents (create, update, list).',
        '- **Schema-first — always inspect `create_document` before building any payload:**',
        '  Call `tools/list` on the Lucid MCP, locate `create_document`, and read its input schema.',
        '  Derive field names and structure from the live schema — never hardcode them.',
        '- **Every diagram payload must comply with Salesforce architect.salesforce.com design tokens.**',
        '  Apply the constraints below while building the JSON — not as post-creation edits:',
        '  - Reference: https://architect.salesforce.com/diagrams',
        '  - Reference: https://architect.salesforce.com/docs/architect/reference-diagrams/guide/introduction',
        '- **Layout (apply in payload — Hybrid strategy):**',
        '  - Place related entities adjacent, grouped by domain or layer — not in a uniform grid.',
        '  - Set `use_assisted_layout: true` (if exposed by the schema) for automatic line routing.',
        '  - Never rely on a flat grid — it produces long connector paths and visual noise.',
        '- **Grouping (apply in payload):** use swim lanes or color bands by domain/layer — not by object type.',
        '  Examples: by Cloud (Commerce, Service, Core), by architecture layer (Context / Work / Agency / Engagement),',
        '  by integration boundary, by ownership. Adjacent entities = adjacent in the same swim lane.',
        '- **ERD / Data Model payload constraints:**',
        '  - Shapes: rectangle with rounded corners, branded fill colors.',
        "  - Connectors: crow's-foot notation for cardinality.",
        '  - Colors: Salesforce blue (#1B96FF) primary objects · gray (#F4F6F9) junction objects · orange (#E8A201) external.',
        '  - Typography: Salesforce Sans or system sans-serif, 12pt minimum.',
        '- **System / Integration payload constraints:**',
        '  - Salesforce org: official cloud icon shape.',
        '  - External systems: gray rectangle.',
        '  - Data flows: solid arrows (sync) · dashed arrows (async / event-driven).',
        '- **Multi-page diagrams:** represent all pages in the single `create_document` payload.',
        '  Check the schema for the pages/tabs array structure. Never call `create_document` once per page.',
        '- **One call per diagram — no exceptions.** Build the full spec (all shapes, groups, swim lanes,',
        '  connections, all pages) before calling. Never create shapes individually then connect in separate calls.',
        '- Always verify the result of each MCP call explicitly — throttle errors may be silent.',
    ];
}
export function flsAndCrudEnforcement() {
    return [
        '## FLS & Data Access Enforcement',
        '- **Always enforce FLS before DML using `Security.stripInaccessible()`.**',
        '  - Before returning data to the UI: `Security.stripInaccessible(AccessType.READABLE, records)`.',
        '  - Before insert: `Security.stripInaccessible(AccessType.CREATABLE, records)`.',
        '  - Before update: `Security.stripInaccessible(AccessType.UPDATABLE, records)`.',
        "- Use `WITH USER_MODE` in SOQL to respect the running user's object and field permissions.",
        '- Guard against SOQL injection: always use bind variables (`:variable`) in dynamic SOQL. Never concatenate user input.',
    ];
}
export function fieldPermissionSetProtocol() {
    return [
        '## Field Permission Set Protocol (CRITICAL)',
        "> Profiles no longer support Field-Level Security (FLS) as of API v61+ / Spring '23.",
        '> Every new custom field MUST be added to a Permission Set — never to a Profile.',
        '',
        '### When creating a custom field, execute this protocol before generating any metadata:',
        '',
        '1. **Scan for existing `*_ObjectAccess` Permission Set:**',
        '   ```',
        '   find force-app/ -name "*_ObjectAccess*.permissionset-meta.xml"',
        '   ```',
        '2. **Exactly 1 result found →** add `<fieldPermissions>` to that file automatically:',
        '   ```xml',
        '   <fieldPermissions>',
        '       <editable>true</editable>',
        '       <field>ObjectName__c.FieldName__c</field>',
        '       <readable>true</readable>',
        '   </fieldPermissions>',
        '   ```',
        '3. **0 results found →** STOP. Ask:',
        '   > *"No `*_ObjectAccess` Permission Set found. Should I create one (e.g. `<ObjectName>_ObjectAccess`) or specify an existing PS to receive FLS for `<FieldAPIName>`?"*',
        '4. **2+ results found →** STOP. Ask:',
        '   > *"Multiple `*_ObjectAccess` PSets found: [list]. Which one should receive FLS for `<FieldAPIName>`?"*',
        '',
        '### FORBIDDEN',
        '- **Never add `<fieldPermissions>` inside a Profile metadata file** (`*.profile-meta.xml`).',
        '- Never silently skip FLS — a field with no PS access is invisible to all users.',
        '- Never assume the same PS from a previous field applies — always re-run the scan.',
    ];
}
export function apexModernPatterns() {
    return [
        '## Apex Modern Patterns',
        '- **`inherited sharing` on service and utility classes.** Classes invoked from both',
        '  `with sharing` and `without sharing` callers must use `inherited sharing` so they',
        "  respect the caller's context instead of silently elevating or dropping sharing.",
        '- **Safe navigation `?.` (API 54+).** Replace multi-level null guards:',
        '  `if (acc != null && acc.Contact != null)` → `acc?.Contact?.Name`.',
        '- **`@AuraEnabled(cacheable=true)` cannot perform DML.** The platform blocks it at',
        '  runtime — there is no compile-time error. Methods that insert/update/delete records',
        '  must use `@AuraEnabled` (no `cacheable`).',
        '- **Partial-success DML: `Database.insert(records, false)` + `SaveResult[]`.**',
        '  Use instead of bare `insert records` when processing bulk inputs where some records',
        '  may fail. Iterate `SaveResult` to log or surface individual errors.',
        '- **`Test.setMock(HttpCalloutMock.class, new MyMock())` for all callout tests.**',
        '  Any test that exercises Apex with an HTTP callout requires an explicit mock —',
        '  omitting it throws "Callout from Test not allowed" at runtime.',
    ];
}
export function lwcModernPatterns() {
    return [
        '## LWC Modern Patterns (ES2024 / LWC v9)',
        '- **Optional chaining `?.` and nullish coalescing `??`** for wire data.',
        '  Replace `data && data.records && data.records.length > 0` with',
        '  `data?.records?.length > 0` and `value ?? defaultValue`.',
        '- **`@track` is deprecated (API 46+).** All properties are reactive by default.',
        '  Only add `@track` for deep mutations inside nested objects or arrays.',
        '  Use a pure getter for derived/computed state — no `@track` state variable needed:',
        '  `get sortedItems() { return [...(this.items ?? [])].sort(...); }`',
        '- **`async/await` scope rules.** Valid in: event handlers, `@api` methods,',
        '  `renderedCallback`. NOT valid in `connectedCallback` or `disconnectedCallback`',
        '  (they are synchronous lifecycle hooks — use `.then()/.catch()` there).',
        '- **Private class fields `#field` (API 59+ / LWC v9.1).** Prefer `#field` over',
        '  `_field` with getter/setter boilerplate. Private methods (`#method()`) are also',
        '  GA as of LWC v9.1.0 — use for internal helpers not exposed via `@api`.',
        '- **`Object.groupBy()` (ES2024)** to group wire result arrays.',
        '  Replace `records.reduce((acc, r) => { ... }, {})` with',
        '  `Object.groupBy(records, r => r.Type__c)`.',
        '- **`lwc:if` / `lwc:elseif` / `lwc:else` — `if:true` / `if:false` are deprecated.**',
        '  Always use the directive form: `<template lwc:if={condition}>`. Remove any',
        '  remaining `if:true` / `if:false` during refactors.',
        '- **`<lwc:component lwc:is={ctor}>` replaces `lwc:dynamic`** (deprecated).',
        '  Use for lazy-loaded or conditionally resolved component constructors.',
        '- **`lwc:ref` for DOM queries in light DOM and slotted content.**',
        '  Prefer `this.refs.myRef` over `this.template.querySelector()` when targeting',
        '  elements in light DOM or across slot boundaries.',
        '- **Signals (Beta — design awareness only).** LWC Signals provide granular',
        '  reactivity without `@track`. Do NOT ship Signals code to production yet —',
        '  wait for GA. Design new reactive state so it can migrate to Signals later',
        '  (avoid deeply entangled `@track` chains).',
    ];
}
export function apexComplexityRules() {
    return [
        '## Apex Complexity Rules',
        '- **No nested loops.** Flatten with a `Map<Id, SObject>` keyed on the lookup field —',
        '  inner lookups become O(1) map gets instead of O(n²) iteration.',
        '- **if/else chains with 3+ branches on the same variable → `switch on`.**',
        '  `switch on` supports String, Integer, Long, and sObject type. Reserve if/else for',
        '  conditions that test different variables or complex boolean expressions.',
    ];
}
export function testCoverageStandards() {
    return [
        '## Test Coverage Standards',
        '- **Exactly one Assert per test method** using the modern `Assert` class.',
        '- Use `@TestSetup` for shared test data; `System.runAs()` with Permission Set Group-based test users.',
        '- Target **90% code coverage**.',
    ];
}
export function deployment() {
    return [
        '## Deployment',
        '- Granular deploy: specific modified files/metadata ONLY.',
        '- **Validate before deploying:** `sf project deploy validate -d force-app`.',
        '- **Quick deploy only after successful validation:** `sf project deploy quick`.',
    ];
}
export function nativeConfigurationFirst() {
    return [
        '## Native Configuration Before Custom Objects (CRITICAL)',
        '- **Before proposing any custom object or custom solution, check whether the target product already',
        '  provides a native configuration that covers the requirement.**',
        '- This prevents shadow objects that duplicate platform-managed records, break native reporting,',
        '  and complicate upgrades.',
        '',
        '### Configuration Types to Verify by Product',
        '',
        '| Requirement Area | Native Configuration to Check First | Product Admin Guide |',
        '|-----------------|-------------------------------------|---------------------|',
        '| Approval workflows | Approval Processes (Setup > Approval Processes) | https://help.salesforce.com/s/articleView?id=sf.approvals_checklist.htm |',
        '| SLA / response times | Entitlements, Service Contracts, Milestones | https://help.salesforce.com/s/articleView?id=sf.entitlements_overview.htm |',
        '| Case escalation | Escalation Rules (Setup > Escalation Rules) | https://help.salesforce.com/s/articleView?id=sf.case_escalation.htm |',
        '| Service milestones | Case Milestones (Service Cloud Setup) | https://help.salesforce.com/s/articleView?id=sf.milestones_overview.htm |',
        '| Field service scheduling | Work Orders, Service Appointments, FSL Policies | https://help.salesforce.com/s/articleView?id=sf.fsl_service_setup.htm |',
        '| Quote / order line items | CPQ Quote Lines, Order Products | https://help.salesforce.com/s/articleView?id=sf.cpq_getting_started.htm |',
        '| Omni-channel routing | Queues, Routing Configurations, Omni-Channel | https://help.salesforce.com/s/articleView?id=sf.omnichannel_intro.htm |',
        '| Knowledge content | Salesforce Knowledge article types | https://help.salesforce.com/s/articleView?id=sf.knowledge_whatis.htm |',
        '| Asset tracking | Asset object, Asset Relationships | https://help.salesforce.com/s/articleView?id=sf.assets_overview.htm |',
        '| Entitlement processes | Entitlement Process, Milestone Actions | https://help.salesforce.com/s/articleView?id=sf.entitlements_process_overview.htm |',
        '',
        '### Evaluation Protocol',
        '1. Identify the business requirement.',
        '2. Ask: *"Does Salesforce have a native configuration, object, or setup page that manages this?"*',
        '3. If yes: propose configuring the native feature. Document the configuration spec in `/docs/`.',
        '4. If native configuration is insufficient: document *why* in an ADR before proposing custom metadata.',
        '5. Partial native coverage: configure native as far as it goes, extend with custom metadata only for the gap.',
        '',
        '### Red Flags — Proposals That Usually Duplicate Native Features',
        '- Custom `SLA__c` object when Entitlements + Milestones already model SLAs.',
        '- Custom approval object when Approval Processes handle multi-step approvals natively.',
        '- Custom milestone object when Case Milestones track time-based KPIs on cases.',
        '- Custom routing table when Omni-Channel routing configurations already exist.',
        '- Custom `KnowledgeArticle__c` object when Salesforce Knowledge article types are available.',
        '- Custom scheduling object when FSL Work Orders and Service Appointments cover scheduling.',
        '',
        '**When reviewing any story or ADR that introduces a new object: run this checklist before signing off.**',
    ];
}
export function architectPushback() {
    return [
        '## Architect Challenge Authority (CRITICAL)',
        '> You are NOT a passive executor of Architect proposals. Evaluate the design in TWO passes before implementing anything.',
        '',
        '### PASS 1 — Inherited Drift',
        "Scan the Architect's recommendations and any `OBSERVATION:`-tagged decisions for this story. Evaluate each against:",
        '1. **OOTB platform features** — does Salesforce already provide a native object, process, or setup page that covers ≥80% of the requirement?',
        '2. **Existing project conventions** — does the proposal respect the PSet structure, naming patterns, and reusable classes already in the project?',
        '3. **Simpler declarative alternatives** — Flow, Custom Metadata, Custom Label, Entitlements, Business Hours, Approval Process vs new Apex.',
        '4. **Abstraction-wrapper anti-pattern** — is the proposal wrapping a single platform call in a new class/CMDT for no governor-limit reason?',
        '',
        'Output `## Architectural Concerns (inherited)` listing each finding with:',
        "- **(a)** Architect's proposal verbatim",
        '- **(b)** The OOTB alternative or simpler pattern',
        '- **(c)** The rationale citing at least one Salesforce platform reference',
        '',
        'If no inherited drift found, output the section with "None identified."',
        '',
        '### PASS 2 — Self-Scrutiny',
        'Before finalising any implementation contract, scan your OWN proposed metadata additions against the same 4 criteria:',
        '- Custom fields, picklists, CMDT records, Custom Labels, Permission Set entries, new Apex classes, new Flows',
        '',
        'For each NEW metadata item you propose, write a one-line justification:',
        '`<metadata API name>: <why this is needed> vs <OOTB platform feature or reuse target>`',
        '',
        'If an OOTB feature covers the need → **drop the custom metadata from the proposal**.',
        'If no OOTB feature covers it → state that explicitly with a citation.',
        '',
        'Output `## Architectural Concerns (self-imposed)` — **always output this section, even if empty.**',
        '**Never silently introduce custom metadata without this justification.**',
    ];
}
export function redoProtocol() {
    return [
        '## Re-do Protocol (CRITICAL — read first)',
        '> When invoked as a re-do — i.e. `OBSERVATION:`-tagged decisions on this story postdate the latest doc version, or the run context indicates `mode=redo` — you MUST follow this protocol. Skipping it is an error.',
        '',
        '### Mandatory steps',
        '1. Scan `decisions.jsonl` for all decisions tagged `OBSERVATION:` on the active story.',
        '2. For **each** OBSERVATION, output verbatim:',
        '   ```',
        '   OBSERVATION: <decision summary>',
        '   Verdict: ACCEPT | REJECT | DEFER',
        '   Reasoning: <justify with at least one Salesforce platform reference or project convention>',
        '   ```',
        '3. Mark every superseded section in the prior doc with: `~~<original text>~~ *(SUPERSEDED — see v<n>)*`.',
        '4. Bump the document version: `1.0 → 2.0` for substantive redesign; `1.0 → 1.1` for clarifications only.',
        '5. If the redesign exceeds the scope of the existing doc, produce a new numbered doc (e.g. ADR-010).',
        '6. Honor explicit output paths declared in `META`-tagged decisions — write to the specified file, not the default.',
        '',
        '### FORBIDDEN in re-do mode',
        '- Producing a "Sign-Off", "Post-Pipeline Review", or "CLEARED" section that endorses the prior design while unaddressed OBSERVATION decisions exist.',
        '- Generating a new doc that omits the OBSERVATION verdict table.',
        '- Treating the prior design as final without per-observation reasoning.',
        '',
        '### When re-do mode is NOT active',
        'If no OBSERVATION decisions postdate the latest doc version, proceed with standard phase execution.',
    ];
}
export function apexTriggerHandlerPattern() {
    return [
        '## Apex Trigger Handler Pattern (CRITICAL)',
        '- One trigger per object. Zero logic in triggers — instantiate the controller and call `run()`.',
        "- Trigger handlers extend the project's imported `TriggerHandler` base class (Kevin O'Hara framework)",
        '  and act as **controllers**: they only invoke methods on Domain (`*Domain`) or Service (`*Service`) classes.',
        '  NO business logic inside handler overrides.',
        '- **Domain class**: encapsulates SObject-level rules and persistence.',
        '- **Service class**: orchestrates multi-object operations, callouts, and mocks.',
    ];
}
export function deploymentRiskChallenge() {
    return [
        '## Deployment Risk Challenge (CRITICAL)',
        '> Before authoring the deployment runbook, evaluate the design against deployment smells. You are the last gate before production.',
        '',
        '### Smell checklist',
        '| Smell | Threshold |',
        '|-------|-----------|',
        '| Wave count vs story size | > 3 waves for a story sized ≤ M |',
        '| Custom metadata replaceable by OOTB | Any CMDT, RSS, custom field with a native equivalent |',
        '| PSet / FLS convention drift | `fieldPermissions` outside the designated `*_ObjectAccess` PSet |',
        '| Rollback complexity vs change size | Rollback steps > 2× the deploy steps for the same wave |',
        '',
        'If **≥ 2 smells** are identified:',
        '1. Output a MANDATORY `## Deployment Risk Challenge` section at the TOP of the runbook.',
        '2. List each smell with: **(a)** the smell, **(b)** the specific instance, **(c)** a proposed simplification.',
        '3. Do NOT author the runbook as if the design is final — flag for Architect review before wave planning.',
        '',
        'If **< 2 smells**: proceed with runbook authoring, noting any single smell as a minor observation.',
    ];
}
export function branchingStrategy() {
    return [
        '## Branching & Release Strategy',
        '- **Flow:** Trunk-based development — all work merges to `main`.',
        '- **Branch naming:** `feature/<ID>-short-desc`, `fix/<ID>-short-desc`, `hotfix/<desc>`.',
        '- **PR requirements:** All changes via Pull Request. Squash merge preferred. CI must pass.',
        '- **Release:** Semantic versioning. Tags: `v<major>.<minor>.<patch>`. No long-lived release branches — releases cut from `main`.',
        '- **Hotfix:** Branch from latest tag, PR back to `main`.',
        '- **Commit style:** Conventional commits (`feat:`, `fix:`, `chore:`, `refactor:`, `test:`, `docs:`).',
    ];
}
export const SHARED_SECTION_REGISTRY = [
    {
        section: apexTriggerHandlerPattern,
        profiles: [
            'developer',
            'cpq',
            'fsl',
            'fsc',
            'health',
            'commerce',
            'service',
            'omnistudio',
            'cgcloud',
            'manufacturing',
            'communications',
            'automotive',
            'education',
            'netzero',
            'nonprofit',
            'public-sector',
            'media',
            'energy',
            'revenue',
            'maps',
            'loyalty',
            'industries',
        ],
    },
    {
        section: apexComplexityRules,
        profiles: [
            'developer',
            'ta',
            'devops',
            'cpq',
            'fsl',
            'fsc',
            'health',
            'commerce',
            'service',
            'omnistudio',
            'cgcloud',
            'manufacturing',
            'communications',
            'automotive',
            'education',
            'netzero',
            'nonprofit',
            'public-sector',
            'media',
            'energy',
            'revenue',
            'maps',
            'loyalty',
            'industries',
        ],
    },
    {
        section: apexModernPatterns,
        profiles: [
            'developer',
            'ta',
            'devops',
            'security',
            'cpq',
            'fsl',
            'fsc',
            'health',
            'commerce',
            'service',
            'omnistudio',
            'cgcloud',
            'manufacturing',
            'communications',
            'automotive',
            'education',
            'netzero',
            'nonprofit',
            'public-sector',
            'media',
            'energy',
            'revenue',
            'maps',
            'loyalty',
            'industries',
        ],
    },
    {
        section: lwcModernPatterns,
        profiles: [
            'developer',
            'ux',
            'cpq',
            'fsl',
            'fsc',
            'health',
            'commerce',
            'service',
            'omnistudio',
            'cgcloud',
            'manufacturing',
            'communications',
            'automotive',
            'education',
            'netzero',
            'nonprofit',
            'public-sector',
            'media',
            'energy',
            'revenue',
            'maps',
            'loyalty',
            'industries',
        ],
    },
    {
        section: branchingStrategy,
        profiles: ['developer', 'ta', 'devops', 'release-manager'],
    },
    {
        section: redoProtocol,
        profiles: ['ta', 'developer', 'devops', 'release-manager'],
    },
    {
        section: deploymentRiskChallenge,
        profiles: ['devops', 'release-manager'],
    },
    {
        section: architectPushback,
        profiles: [
            'developer',
            'ta',
            'devops',
            'release-manager',
            'ux',
            'fsl',
            'fsc',
            'health',
            'mulesoft',
            'admin',
            'cgcloud',
            'sfmc',
            'security',
            'cpq',
            'crma',
            'commerce',
            'omnistudio',
            'service',
            'manufacturing',
            'communications',
            'automotive',
            'education',
            'netzero',
            'nonprofit',
            'public-sector',
            'media',
            'energy',
            'revenue',
            'maps',
            'loyalty',
            'industries',
        ],
    },
];
/**
 * Returns the additional shared lines for the given profileId
 * based on the registry. Each section is preceded by a blank line separator.
 */
export function getSharedSectionLines(profileId) {
    const lines = [];
    for (const entry of SHARED_SECTION_REGISTRY) {
        if (entry.profiles.includes(profileId)) {
            lines.push('', ...entry.section());
        }
    }
    return lines;
}
//# sourceMappingURL=shared-sections.js.map