


Change and Review a Multi-Protocol Integration Gateway Without Breaking Access Checks
Use when an AI changes or reviews a gateway that links several protocols. It runs the project's checks, keeps access checks strict, keeps log and audit writes apart, builds migrations carefully, and asks before pushing.
To use this AI rule
## Find the Nearest Instructions and Trust Running Code When Sources Disagree
Begin with the repository-level guidance, then locate the nearest domain-specific instructions for the files being changed. Testing, plugins, deployment charts, documentation, protocol servers, and performance-sensitive runtimes may each have distinct workflows. Do not apply one area's rules to another without evidence.
Distinguish code-contributor guidance from end-user runtime instructions. Material written for a model or client using the deployed system does not automatically govern agents modifying the codebase.
Map the system before editing:
- Application entry points and environment configuration.
- Validation schemas, persistence models, and migrations.
- Business services, routes, middleware, and protocol transports.
- Authentication, authorization, plugins, and federation boundaries.
- Tests, documentation, deployment assets, and administrative interfaces.
When sources disagree, prefer active runtime code and canonical configuration, then supported build targets and dependencies, then environment examples, and finally documentation or comments. Confirm the current implementation before repeating numeric counts or operational limits that can become stale.
Inspect active source paths first. Ignore temporary workbenches, logs, coverage output, generated artifacts, and deferred-task folders unless the request specifically includes them.
## Run the Project's Checks and Secret Scans After Every Change
Use the repository's supported task runner and pinned toolchain instead of invoking underlying tools with ad hoc flags. Validate the development environment against the canonical example, run required preparation or generated-interface steps, and choose the local server or test mode that matches the task.
After changing code:
1. Run format, lint, type, security, and documentation checks that directly cover the changed language and files.
2. Use focused checks during iteration, then run the repository's required aggregate quality gate before proposing completion.
3. For a secondary systems language or performance runtime, run its formatter check, linter with warnings treated as errors, and crate or package tests.
4. Rebuild generated administrative or client assets when their sources change.
5. Include behavior tests for every externally visible change.
Use secret detection as a gate. For a verified false positive, use the project's sanctioned inline suppression only where it cannot alter a test or example's behavior. Otherwise regenerate and audit the approved baseline. Never suppress a real credential, and never place secrets in committed configuration.
Prefer extending the existing language, build, and automation stack. Add a dependency or new toolchain only when a concrete requirement cannot be met safely by what the project already supports.
## Check What Each User Can See and Do Separately, and Deny Unmapped Routes
Maintain two independent security layers on every protected path:
- Scope filtering determines which resources an identity can see.
- Role-based authorization determines which actions that identity can perform.
Passing one layer never substitutes for the other. Treat platform-public scope as visibility within the platform, not as permission for anonymous internet access.
Normalize each token class through one canonical policy function. For self-contained or legacy API tokens, missing or empty team scope must fail closed to public-only visibility; administrative bypass requires both an explicit bypass state and verified administrative status. For session-backed identities, persisted server-side membership and administrator state are authoritative, while token claims may only narrow access. An empty intersection must fail closed. Identities provisioned through trusted external sign-in must also use persisted local authorization state rather than trusting external privilege claims.
Apply these invariants:
- Authenticate before establishing a transport session or forwarding a message, then enforce action authorization before processing it.
- Default-deny protected routes that have no explicit authorization mapping.
- Derive ownership, team, and session identity from authenticated server-side state; never trust client-provided ownership fields.
- Never accept inbound client credentials through URL query parameters.
- Keep high-risk transports and unrestricted cross-domain routing disabled by default.
- Require an explicit domain allowlist for cross-gateway traffic; an empty allowlist blocks all destinations.
- Require communicating gateways to trust the same issuer, and propagate only the credentials required for remote authorization.
For delegated token exchange, never forward the user's inbound token to the downstream service. Exchange it through a trusted authorization server and forward only the exchanged token. Treat the configured exchange destination as an SSRF and egress boundary: validate it when configuration is saved, restrict configuration changes to privileged identities, record a correlation identifier, and never log raw inbound or exchanged tokens.
Security-sensitive changes must include regression tests for unauthenticated access, wrong scope, insufficient permission, disabled features, disallowed destinations, and other deny paths.
## Keep Trace and Audit Log Writes Apart From the Main Transaction
Understand the intended transaction boundary before modifying persistence code. Request data, observability records, and audit records may deliberately use different sessions and atomicity guarantees.
Best-effort observability writes may use short-lived independent sessions that commit immediately. This preserves traces and events when the main request fails, but it also means telemetry is not atomic with the request and may show partial or in-progress states. Query operations should still use request-scoped sessions so visibility and authorization filtering are applied.
Audit logging may also own its session and isolate its failures. Do not pass the request's already-committed session into an independent audit writer merely for convenience; a second commit or rollback can leave the shared transaction inactive and can surface an error after the primary resource was already persisted. If an audit record must become atomic with the primary write, treat that as an explicit design change requiring review, new failure semantics, and tests.
Independent tracing can create several database sessions per request. Measure concurrency, monitor pool-exhaustion signals, and size the pool for the actual database and workload rather than copying fixed capacity claims.
Do not classify a deliberate synchronous persistence strategy inside asynchronous handlers as an isolated bug without evidence. Converting individual call sites can create mixed semantics; propose a coordinated driver and transaction migration instead.
## Check the Current Head Before Adding a Database Migration
Before creating a migration, query the current migration head. The new revision's parent must reference that verified head; never guess or copy a parent identifier from an older file. After creation, verify that the history still has exactly one intended head.
Write idempotent migration steps when installations can differ. Inspect the current schema before modifying it, skip safely when an optional table is absent, and avoid adding a column or object that already exists. Keep fresh-database creation and upgrade paths consistent.
If a downgrade depends on runtime configuration, make it hermetic:
1. During upgrade, store every required configuration value in migration-owned metadata keyed by revision.
2. During downgrade, read the stored snapshot rather than the current environment.
3. Use live configuration only as a documented compatibility fallback for databases upgraded before snapshots existed.
4. Remove the snapshot when the downgrade completes.
A migration that reads configuration only to seed upgrade data does not need a downgrade snapshot unless the downgrade also depends on that value.
Verify the head again after editing and run the relevant migration and application tests. If the target database is behind, bring the controlled development or test database to the expected head before generating a new revision. Never perform that corrective upgrade against production without explicit authorization and a reviewed plan.
## Confirm Real Check Results and Get Permission Before Pushing
Review the final diff against the original request, the nearest domain guidance, and the security invariants above. Confirm actual results for linting, types, security scans, tests, migrations, generated assets, and documentation where relevant. Do not claim success from inspection alone.
Use the repository's required commit convention, signature policy, issue links, and pull-request template. Do not push, force-push, modify a contributor's branch, or change external project state until explicitly authorized.
For public reviews and issue comments:
- Lead with what is working before raising concerns.
- Separate blocking findings, suggestions, and minor notes.
- Explain the risk and offer questions or options instead of issuing needless directives.
- Be direct without being harsh or robotic.
Do not add internal assistant attribution, hidden operational commentary, credentials, or speculative effort claims to product diffs or public messages. Create new files or documentation only when the change genuinely requires them.
When triaging work, distinguish a request awaiting reporter information from a dependency blocker or an accepted deferred item. Mark an issue resolved only after the fixing change is merged, not merely implemented locally.
Before completion, verify that sensitive values remain outside version control, security deny paths have tests, source-of-truth precedence was respected, and no unrelated transient content entered the diff.
