# Ground Rules Reference

Single source of truth for all generation and architecture rules. Other docs reference rules by ID (e.g., "Rule G-3"). Lint rules are in `lint-reference.md` — this file covers **agent behavior rules** (what the model must/must not do).

## Generation Rules (G)

| ID | Severity | Rule | Rationale |
|---|---|---|---|
| G-1 | ⛔ HALT | **Create .xaml files ONLY via `scripts/generate_workflow.py`.** Never via Write, create_file, or hand-writing. Write a JSON spec → run the CLI → get validated .xaml. | Hand-written XAML bypasses hallucination guardrails: wrong enum values, missing child elements, malformed namespaces. #1 cause of lint errors. |
| G-2 | ⛔ HALT | **Write JSON specs to disk as `.json` files BEFORE calling generate_workflow.py.** Never embed specs inline in Agent/subagent prompts or compose from memory. | When specs are embedded in prompts, the subagent composes types from memory (`Dictionary(String,Object)` instead of `Dictionary`), skips TYPE_MAP normalization, and produces XAML that crashes Studio. |
| G-3 | ⛔ HALT | **Framework wiring snippets MUST come from generator output.** When using `modify_framework.py` (`insert-invoke` or `replace-marker`), the XAML snippet must be generated by `generate_workflow.py` or `gen_*()` functions first. Never compose XAML inline in tool arguments. | The wiring script validates snippets and rejects hallucinated patterns (exit code 1). |
| G-4 | ⛔ HALT | **Never generate XAML from scratch.** All XAML in `assets/` are real UiPath Studio exports. Copy from the closest template and modify. Never write namespace blocks, assembly references, or ViewState from memory. | Studio's XAML schema is complex — invented namespaces or attributes crash the IDE. |
| G-5 | 🔴 ERROR | **Never guess NuGet package versions.** Run `scripts/resolve_nuget.py`. UiPath packages use non-standard version schemes. | Grabbing latest without filtering picks up `-preview` versions that break projects. |
| G-6 | 🔴 ERROR | **Never add variables to framework files via Write/Edit tool.** Use `modify_framework.py add-variables`. | It handles indent, creates `<Sequence.Variables>` if missing, and skips duplicates. |
| G-7 | 🟡 WARN | **Use type shortcuts in JSON specs.** `"String"` not `"x:String"`, `"Dictionary"` not `"Dictionary(String,Object)"`. See `cheat-sheet.md` § type keys. | The generator auto-maps short forms. Long-form types bypass TYPE_MAP and crash Studio. |
| G-9 | 🔴 ERROR | **UI activity specs MUST include `obj_repo` bindings.** After generating the Object Repository (Phase 2c), read `refs.json` and add `"obj_repo": {"reference": "...", "content_hash": "...", "guid": "..."}` to every UI activity's `args` in the JSON spec. Add `"obj_repo_app"` to NApplicationCard specs. Skip only for NCheckState targeting elements not in `selectors.json`. | Without obj_repo, the Object Repository exists but activities use hardcoded inline selectors — refactoring requires manually updating every activity. Lint 94 catches missing `.objects/` but cannot detect missing bindings in XAML. |
| G-8 | ⛔ HALT | **Never use Edit/Write tools on .xaml files.** All XAML modifications go through scripts: `generate_workflow.py` (new files), `modify_framework.py` (framework wiring, variables, expressions), `validate_xaml --fix` (deterministic auto-fixes). If a framework file needs a type change, use `add-variables` with short-form types. If it needs an expression replacement, use `set-expression`. | Hand-editing .xaml bypasses type normalization, snippet validation, and lint guardrails. Every raw Edit in the CCSH project produced errors that required further fixes. |

## Inspection Rules (I)

| ID | Severity | Rule | Rationale |
|---|---|---|---|
| I-1 | ⛔ HALT | **Playwright/browser inspection is READ-ONLY.** Never type into form fields, enter credentials, or click submit. Login page → STOP, output the Login Gate message, WAIT for user. | Safety — never interact with live credentials or production systems. |
| I-2 | ⛔ HALT | **HALT at login gates during Playwright inspection.** When navigation hits a login redirect: inspect the login page, ask the user to log in, then END YOUR RESPONSE. Do not inspect other pages or proceed to XAML generation. Resume only after user confirms login. | The model cannot authenticate — attempting to continue produces wrong selectors from the login page. |
| I-3 | ⛔ HALT | **Never guess selectors.** Browser selectors come from Playwright MCP inspection. SAP selectors come from `inspect-sap-tree.ps1`. Desktop selectors come from `inspect-ui-tree.ps1` via PowerShell. No "placeholder" selectors, no "TODO: VERIFY" markers. If you don't have real selectors, STOP. | Guessed selectors are wrong 100% of the time for SAP dynpro paths and near-100% for dynamic web apps. |
| I-4 | 🟡 WARN | **Inspect target applications BEFORE generating any XAML.** If Playwright MCP or PowerShell is available (Windows), use it. Do NOT skip to generation with guessed selectors. | Real selectors from live inspection are the only reliable source. |

## Architecture Rules (A)

| ID | Severity | Rule | Rationale |
|---|---|---|---|
| A-1 | 🔴 ERROR | **ALL apps open and ready in InitAllApplications.** Every app must be launched, logged in, and ready by end of `InitAllApplications.xaml`. Process.xaml and action workflows ONLY attach (`OpenMode="Never"`). They NEVER open or launch apps. | Separates initialization from business logic. Apps stay open across transactions. |
| A-2 | 🔴 ERROR | **Persistence activities MUST stay in Main.xaml.** `WaitForFormTaskAndResume` and `CreateFormTask`+wait pairs are persistence points — they serialize workflow state to Orchestrator. They ONLY work in the entry-point file. Lint 26 enforces this. | Runtime error — bookmark context unavailable in sub-workflows. |
| A-3 | 🔴 ERROR | **Credentials retrieved where used, NEVER passed as arguments.** `GetRobotCredential` goes inside the workflow that uses the credentials. Pass only `in_strCredentialAssetName` (the Orchestrator asset name string). Never pass `in_strUsername`/`in_strPassword`/`in_secPassword`. | Security — credentials should never traverse argument boundaries. Orchestrator audit trail is per-robot. |
| A-4 | 🔴 ERROR | **Never modify `SetTransactionStatus.xaml`.** The default Framework implementation handles all cases correctly. | Custom logic here breaks REFramework's retry/exception handling contract. |
| A-5 | 🔴 ERROR | **Modular decomposition.** Never put an entire process into a single Main.xaml. Break into `Workflows/<AppName>/` subfolders connected via `InvokeWorkflowFile`. One UI scope per workflow, ≤150 lines per file. | Long workflows are unreadable, untestable, and unmaintainable. |
| A-6 | 🔴 ERROR | **Navigation is always a separate invoke from the page action.** First invoke `Browser_NavigateToUrl.xaml` (from Utils/), then invoke `AppName_DoAction.xaml`. Never create app-specific NavigateTo workflows — the generic util handles all URL navigation. | Keeps navigation reusable. Callers assemble full URLs from Config. |
| A-7 | 🟡 WARN | **Log bookends on every workflow.** First and last activity: `LogMessage "[START/END] WorkflowName"`. Applies to Main.xaml AND all sub-workflows. | Essential for production debugging and Orchestrator log analysis. |
| A-8 | 🟡 WARN | **URLs from Config, never hardcoded.** Store base URL + path segments in Config.xlsx Assets sheet. Caller assembles full URL via `String.Format`. Workflow receives complete URL in `in_strUrl`. | Environment portability — Dev/UAT/Prod use different URLs. Lint 37 catches this. |
| A-9 | 🟡 WARN | **Browser defaults: `IsIncognito="True"`, `InteractionMode="Simulate"`, `AttachMode="SingleWindow"`.** Desktop: NO IsIncognito, `Simulate` or `HardwareEvents`, `AttachMode="ByInstance"`. | Incognito kills session on close (no logout needed). Simulate is fastest and most reliable for web. |
| A-10 | 🟡 WARN | **One browser instance per web app.** Each web app gets its own incognito browser with a distinct UiElement variable (`uiWebApp`, `uiSHA1Online`). Never share tabs across apps. | Tab-sharing causes race conditions and makes close/error-handling unpredictable. |
| A-11 | 🟡 WARN | **Wrap API/network activities in RetryScope.** 3 retries, 5s interval. Exception: `NetHttpRequest` has built-in retry — do NOT double-wrap. | Transient failures are common with Orchestrator and external APIs. |
| A-12 | 🟡 WARN | **Extraction workflows return ALL data — filtering is a separate step.** `AppName_ExtractData.xaml` outputs the raw DataTable. Filtering belongs in the caller or `Process_FilterData.xaml`. | Keeps extraction reusable across projects with different filter criteria. |

## PDD Rules (P)

| ID | Severity | Rule | Rationale |
|---|---|---|---|
| P-1 | 🔴 ERROR | **Follow the PDD exactly.** Implement the PDD's specified approach faithfully — do NOT substitute alternatives without asking. If you believe an alternative is better: implement PDD way first, propose alternative separately, let user decide. | The PDD represents stakeholder requirements. Unilateral substitution breaks trust. |
| P-2 | 🔴 ERROR | **Architecture check for PDDs.** Does the PDD describe BOTH reading items AND processing each one? → Recommend Dispatcher + Performer (two projects). | Single-project approaches don't scale for transaction-level retry and status tracking. |
| P-3 | 🟡 WARN | **Technical improvements are OK — functional changes are NOT.** Override PDD only for: selector strategies, error handling, variable naming, decomposition, retry logic. Never for: which app to automate, which website to use, programmatic alternatives to UI automation. | The PDD defines WHAT to automate. The skill defines HOW to do it well. |

## SAP-Specific Rules (S)

| ID | Severity | Rule | Rationale |
|---|---|---|---|
| S-1 | 🔴 ERROR | **SAP activities MUST be inside NSAPLogon scope.** All SAP-specific activities require a `ScopeIdentifier` referencing the parent `NSAPLogon.ScopeGuid`. | SAP COM bridge context is scoped to the logon session. |
| S-2 | 🔴 ERROR | **Status bar check after EVERY write operation.** After Save, Type Into + Enter, or Call Transaction: `NSAPReadStatusbar` → check `MessageType.Equals("E")` → Throw. | SAP errors are silent without status bar validation. |
| S-3 | 🔴 ERROR | **Toolbar buttons are NOT regular NClick.** System toolbar (Enter/Save/Back/Exit/Cancel) → `NSAPClickToolbarButton`. Only user area buttons use `NClick` with selectors. | Wrong activity type produces no error but silently does nothing. |
| S-4 | 🔴 ERROR | **Table cells use NSAPTableCellScope, not direct selectors.** Wrap the action in `NSAPTableCellScope` targeting ColumnName + RowType. | Direct cell selectors break when rows shift. The scope handles dynamic indexing. |
| S-5 | 🟡 WARN | **Dynpro numbers are volatile — field names are stable.** Don't "fix" dynpro numbers in selectors. Use the full path from inspection output. | Dynpro numbers change when sections expand/collapse. Field names (`txtMEPO_TOPLINE-EBELN`) are stable. |
| S-6 | 🟡 WARN | **NEVER hardcode SAP values.** Every data value (credentials, transaction codes, asset names, field values, connection names) comes from arguments or variables, never as literals in XAML. | Hardcoded values break reusability and environment portability. |

## Skill Authoring Rules (K)

| ID | Severity | Rule | Rationale |
|---|---|---|---|
| K-1 | 🟡 WARN | **SKILL.md should be a routing table + ground rules + architecture constraints. Target ≤8,000 tokens for 1M-context models.** Code recipes, expression guides, and selector references belong in `references/` files loaded on demand. Routing tables, capabilities, decomposition rules (K-3), and ground rules belong inline. Avoid line counts or other metadata that drifts silently. Run `scripts/check_skill_budget.py` to verify. | SKILL.md is loaded into context on skill invocation. With 1M-context models, 3 skills at 8K each = 24K tokens (2.4% of budget) — negligible. On 200K-context models the same 24K is ~12% — still manageable but no longer negligible; tighten budgets or reduce active skills if targeting smaller contexts. The old 3K target forced externalizing content that models then skipped, causing worse routing and monolith generation. Keep essential guidance inline; externalize only reference data that's useful on-demand (code recipes, expression syntax, selector patterns). |
| K-2 | 🟡 WARN | **Mark "always read" references in the routing table with ⚠️.** If a reference file should be read on every task for that skill (e.g., `sap-generation.md` for any SAP generation), mark the routing entry with ⚠️ and bold text. | The agent needs a strong signal to not skip critical references. ⚠️ markers in the routing table are the mechanism — they're cheaper than putting the content inline. |
| K-3 | 🟡 WARN | **Keep decomposition rules inline in SKILL.md.** Decomposition/architecture sections are the most likely to be skipped if externalized — agents love to skip decomposition and generate monoliths. These stay in SKILL.md even if they push past the 3K token target. | The cost of the agent skipping decomposition (monolith workflows, failed battle tests) outweighs the token savings from externalizing it. |
