Search Results for

    Generalized Style Guide — .NET and Frontend

    Version: 1.3 (2026-12-02). Rule IDs are stable across versions; a rule whose meaning changes gets a new ID.

    This guide is project-agnostic. It carries the shared house rules for .NET backends, libraries and frontends, plus the shared-library map. A project adopts it by referencing it from the project's own STYLE_GUIDE.md; project rules then add to it, override its defaults, or bypass its required rules with explicit tags (next section). If project code and this guide disagree and no valid tag covers the difference, the guide wins.

    How a project adopts this guide

    The project guide starts with an adoption line and an overrides section:

    # <Project> — Style Guide
    
    This project adopts the Generalized Style Guide v1.3. Project rules below add
    to it. Overrides and bypasses of generalized rules are listed under
    "Generalized guide overrides" and nowhere else.
    
    ## Generalized guide overrides
    
    - OVERRIDE SG-FMT-03: <replacement rule> — <reason>
    - BYPASS SG-SEC-04: <reason> — approved: <name>, review: YYYY-MM-DD
    - BYPASS-LIB ZhEaIsNsAaBn.PrintPDF: <reason> — alternative: <what replaces it>
    

    Rule tiers and bypass tags

    Every rule carries an ID and a tier: REQUIRED or DEFAULT.

    • DEFAULT rules are house defaults. A project overrides one with an OVERRIDE tag naming the rule ID, the replacement rule, and the reason. An optional scope: glob limits the override to matching paths; without a scope it applies repo-wide.
    • REQUIRED rules must hold. A project force-overrides one only with a BYPASS tag naming the rule ID, the reason, who approved it, and a review date at most 12 months out. An optional scope: glob limits the bypass.
    • Libraries are REQUIRED as a class (section 0). A project bypasses one library with a BYPASS-LIB tag naming the package ID, the reason, and what replaces it.
    • A tag is valid only when the ID exists in this guide, the reason is present, a BYPASS carries an approver and an unexpired review date, and the scope covers the code in question. An invalid or expired tag counts as no tag, and the tag itself is reported as stale.
    • Code-level suppressions (for example SuppressMessage with justification) are not guide bypasses. They follow the quality-gate rules in section 13.

    Precedence, highest first:

    1. Valid project tags (OVERRIDE, BYPASS, BYPASS-LIB).
    2. Project guide rules that do not conflict with REQUIRED rules.
    3. REQUIRED rules in this guide.
    4. DEFAULT rules in this guide.
    5. Framework and stack guidance for correctness, security and performance.

    How reviewers report guide findings:

    • REQUIRED rule broken with no valid bypass: HIGH (BLOCKER when the main review scale calls it exploitable, data-losing or merge-unsafe).
    • DEFAULT rule broken with no override: LOW, or MEDIUM when it carries a concrete cost.
    • Valid OVERRIDE: no finding. Valid BYPASS on a non-security rule: no violation finding; name the bypass in the verdict notes. Valid BYPASS on a security rule (SG-SEC, SG-FE-SEC): one HIGH finding naming the bypass, its reason and its review date, so the force-override stays visible.
    • Hand-rolled infrastructure that duplicates an Available library with no BYPASS-LIB: HIGH.
    • Invalid or expired tag: LOW finding on the tag; the underlying rule is judged normally.

    0. Libraries — must use

    • SG-LIB-01 [REQUIRED] Before writing infrastructure code, check the package map below. If an Available ZhEaIsNsAaBn.* package covers the need, use it. Do not rewrite it in the project.
    • SG-LIB-02 [REQUIRED] Must-use applies to packages marked Available. Planned packages are built behind a small interface and marked as library candidates (SG-LIB-03). Held and Do-not-use packages must not be used.
    • SG-LIB-03 [DEFAULT] When nothing covers a reusable need, write it in the project behind a small interface and add // TODO@<Project>(#N): candidate for ZhEaIsNsAaBn.<Area> — <why> with its tracking issue.
    • SG-LIB-04 [REQUIRED] Exact signatures live in each package's README. Never guess an overload; open the README.
    • SG-LIB-05 [REQUIRED] Packages come from the library feeds (GitHub Packages; published Essentials packages also on nuget.org) with package source mapping and exact version pins. Credentials never go in a repository feed config.
    • SG-LIB-06 [REQUIRED] Bypassing one library needs a BYPASS-LIB tag for that package ID. A bypass for one package never covers another.

    Package map — backend

    Need Package Entry points Status
    Result type for every fallible call ZhEaIsNsAaBn.LayerResponse (namespace ZhEaIsNsAaBn.Utilities) LayerResponse, LayerResponse<T>, Error, CommonErrors, TryGetResult Available
    API envelope and HTTP status ZhEaIsNsAaBn.AspNetCore.APIResponses BaseResponse, AddAPIResponses() Available
    Global exception handling ZhEaIsNsAaBn.AspNetCore.ExceptionHandlers (+ .EFCore where EF is used) AddCustomExceptionHandlers().WithHandler<T>().Build() Available
    OpenAPI documentation ZhEaIsNsAaBn.OpenAPI.Basics with Microsoft.AspNetCore.OpenApi and Scalar /openapi/v1.json, /scalar, schema transformers for examples Available
    Logging and tracing setup ZhEaIsNsAaBn.Serilog.BasicLog builder registration, Serilog defaults Available
    Validation ZhEaIsNsAaBn.Utilities.FluentValidation with FluentValidation rule extensions Available
    Entities, audit, soft delete, keys ZhEaIsNsAaBn.Domain IBaseEntity<TId>, audit and soft-delete contracts Available
    EF Core context, auditing, transactions ZhEaIsNsAaBn.EFCore BaseDbContext<T>, AddEFCore(), SaveChangesSafeAsync, ExecuteInTransactionAsync Available
    EF Core providers ZhEaIsNsAaBn.EFCore.PostgreSql, ZhEaIsNsAaBn.EFCore.SqlServer provider registration extensions Available
    Specification queries ZhEaIsNsAaBn.EFCore.Specifications GetListAsync(spec), GetPagedAsync(spec), FirstOrDefaultAsync(spec) Available
    Paging model ZhEaIsNsAaBn.ViewModels PagedResult<T>, OrderDirection Available
    SQL building and dynamic queries ZhEaIsNsAaBn.Sql with dialect packages, ZhEaIsNsAaBn.DataQuery SqlStatement, ISqlDialect, catalog Expose<T>() Available
    Seed and reference data ZhEaIsNsAaBn.DbSeeder with provider packages and the dotnet dbseeder tool versioned seed migrations Available
    HTML to PDF ZhEaIsNsAaBn.PrintPDF AddPrintPdf() Available
    Hijri dates (backend) ZhEaIsNsAaBn.Utilities HijriDate Available
    Test severity and categories ZhEaIsNsAaBn.NUnit TestSeverity, TestCategory Available
    Integration test fixtures ZhEaIsNsAaBn.IntegrationTestingBases (+ PostgreSql) database fixture, web app factory, Respawn reset Available
    Settings stored in the database ZhEaIsNsAaBn.APPSettings EF-backed configuration source Held — do not use until its reload issue is fixed

    Package map — frontend

    Need Package Entry points Status
    Page model types @zheaisnsaabn/page-model types generated from the Pages JSON Schema Available
    Page builder @zheaisnsaabn/page-builder providePageBuilder(settings) Available
    Design tokens and brand UiKit tokens (--zh-* custom properties) token stylesheet or theme Available
    Page runtime @zheaisnsaabn/page-runtime web components Planned

    Do not use

    • SG-LIB-07 [REQUIRED] No ValidationResponses beside the result type: it duplicates it. One result model per codebase.
    • SG-LIB-08 [REQUIRED] No Swashbuckle. OpenAPI goes through the OpenAPI package above with schema transformers for examples.
    • SG-LIB-09 [REQUIRED] No Xamarin (MAUI is the successor), no runtime-reflection mapper (mapping is source-generated), no embedded database without a health-gate decision recorded in the project guide.

    Not available yet

    • SG-LIB-10 [DEFAULT] Auth has no library package yet: use ASP.NET Core JWT bearer directly, behind the project's auth boundary.
    • SG-LIB-11 [DEFAULT] No SignalR library package yet: build hub handling in the project behind a small interface and mark it as a library candidate.
    • SG-LIB-12 [DEFAULT] API versioning has no library package yet: version contracts explicitly (for example contracts/v1/); add a versioning package only on a real need, through the health gate.
    • SG-LIB-13 [DEFAULT] Reporting and rendering beyond HTML-to-PDF are planned library stages. Ask before building anything report-like in a project; SQL building itself is covered by the Sql and DataQuery packages above.

    Part 1 — Backend (.NET)

    1. Naming

    • SG-NAME-01 [REQUIRED] Product or brand prefix lives in project and namespace names only, never in type names.
    • SG-NAME-02 [REQUIRED] Private fields, instance and static: _camelCase, readonly where possible. Never the s_ prefix.
    • SG-NAME-03 [REQUIRED] No public or protected fields; expose a property.
    • SG-NAME-04 [REQUIRED] Constants at any accessibility: PascalCase. Parameters and locals: camelCase.
    • SG-NAME-05 [REQUIRED] Interfaces carry the I prefix. Generic parameters are descriptive T* (TEntity, TResult).
    • SG-NAME-06 [REQUIRED] Every Task/ValueTask method ends in Async, suffix always last.
    • SG-NAME-07 [REQUIRED] Transport models are *Request / *Response; options are *Settings; no Dto suffix.
    • SG-NAME-08 [DEFAULT] Services are <Feature>Service behind I<Feature>Service. Validators are <Request>Validator.
    • SG-NAME-09 [REQUIRED] Error codes come from nameof(...), never hand-typed strings.
    • SG-NAME-10 [DEFAULT] Booleans read as questions: IsDeleted, HasFilter, CanJoin.
    • SG-NAME-11 [DEFAULT] Acronym casing: Guid, Db, Html, Pdf, Json, Sql, Http, Url, Id.
    • SG-NAME-12 [DEFAULT] Spelling: Registration (never Registeration), Extensions/ (never Extentions/).
    • SG-NAME-13 [REQUIRED] File-scoped namespaces; namespace equals project plus folder path. One public type per file; file name equals type name.
    • SG-NAME-14 [DEFAULT] The product display name lives in one constant or config value only.

    2. Solution structure

    • SG-STRUCT-01 [DEFAULT] One .slnx solution, global.json SDK pin, Directory.Build.props, Directory.Packages.props, root .editorconfig, docs/STYLE_GUIDE.md (the adopting project guide).
    • SG-STRUCT-02 [DEFAULT] Group code by feature (vertical slices), not by kind. Inside an app: feature folders plus core/ (shell, auth, interceptors) and shared/ (dumb UI pieces).
    • SG-STRUCT-03 [DEFAULT] Blocks depend only on the contracts of the blocks below them; the application composes them. A library block never reaches sideways into another block's internals.
    • SG-STRUCT-04 [DEFAULT] If the existing layout differs, move toward the target layout feature by feature. No big-bang moves.
    • SG-STRUCT-05 [DEFAULT] GlobalUsings.cs per project for shared imports.

    3. Patterns

    • SG-PAT-01 [REQUIRED] Values are never written into SQL text. SQL statements are text plus typed parameters (see SG-SEC-02).

    • SG-PAT-02 [DEFAULT] Libraries do not own resources they did not create: a data-access runner receives its connection and transaction from the caller, with timeout and row cap, and never opens or disposes them.

    • SG-PAT-03 [DEFAULT] No generic repository wrapping DbContext without a concrete problem it solves. Domain repositories only when the domain needs them; no unit-of-work layer until a real need appears.

    • SG-PAT-04 [DEFAULT] Mapping is source-generated. Runtime-reflection mapping needs a health-gate decision in the project guide.

    • SG-PAT-05 [DEFAULT] Do not push patterns (CQRS, mediator libraries, clean architecture layers, extra interfaces) without a concrete problem they solve.

    • SG-PAT-06 [REQUIRED] Every outbound call (HTTP, database, broker) has a timeout, and retries use bounded backoff with jitter through resilience pipelines (Microsoft.Extensions.Resilience/Polly). Retrying non-idempotent operations without an idempotency key is forbidden.

    • SG-PAT-07 [DEFAULT] Caching defaults to HybridCache (in-process plus distributed, stampede-protected). Cache keys, TTLs and invalidation triggers are decided per feature and recorded; a cache without an invalidation story is a finding.

    • SG-PAT-08 [DEFAULT] EF Core 10 features are used where the provider supports them: LeftJoin/RightJoin instead of GroupJoin/DefaultIfEmpty workarounds, named query filters instead of disabling all filters, vector/JSON types only through the health gate.

    • SG-PAT-09 [REQUIRED] Single responsibility, functions: a method does one thing at one level of abstraction. If describing it needs "and", split it. Orchestration methods only sequence steps; step methods only do the work — never both in one body. A 200-line method is never acceptable, generated code excepted (SG-PAT-13).

    • SG-PAT-10 [REQUIRED] Single responsibility, classes: one reason to change. A class mixing concerns — persistence with formatting, transport with domain rules, validation with orchestration — is split before it grows. God classes are forbidden; a class whose name needs "Manager", "Helper" or "Util" to cover what it does is a smell to resolve, not a name to keep.

    • SG-PAT-11 [REQUIRED] Size thresholds are hard caps, enforced by the packs, not advice: method at most 50 lines (target 30); class at most 500 lines; file at most 1000 lines; cognitive complexity at most 15; cyclomatic complexity at most 10; at most 7 parameters (more means a *Request or private record). Test code follows the same caps with the test .editorconfig relaxations.

    • SG-PAT-12 [DEFAULT] Nesting depth at most 3. Guard clauses and early returns replace nested if pyramids; a method that needs deeper nesting is decomposed (SG-PAT-09), not indented further.

    • SG-PAT-13 [DEFAULT] A threshold breach is fixed by extraction, never by raising the cap in the same change. Caps change only through a project-guide OVERRIDE with a reason. Generated code (source generators, scaffolding, designer files) is exempt by path, recorded in the project guide.

    4. Dependency injection

    • SG-DI-01 [REQUIRED] No scoped service captured by a singleton. Hosted services create a scope per unit of work.

    • SG-DI-02 [DEFAULT] Configuration uses the options pattern, validated on start.

    • SG-DI-03 [DEFAULT] No service-locator calls (GetService in business code) outside composition roots and framework-required factories.

    • SG-DI-04 [DEFAULT] Library configuration goes through one Add<Thing>() registration method (backend) or provide<Thing>() function (frontend) with a typed *Settings object.

    • SG-DI-05 [DEFAULT] Feature flags go through one flag abstraction with typed flag names; flags carry an owner and a removal date, and dead flags are removed in the change that makes them dead.

    5. Async

    • SG-ASYNC-01 [REQUIRED] Every async method takes CancellationToken cancellationToken = default last and always forwards it.
    • SG-ASYNC-02 [REQUIRED] No .Result, .Wait() or GetAwaiter().GetResult() on async work. No async void except UI event handlers.
    • SG-ASYNC-03 [REQUIRED] ConfigureAwait(false) on every await in library code (CA2007 as error). Application code follows its host's convention.
    • SG-ASYNC-04 [DEFAULT] ValueTask only where the framework call returns one. Pure pass-through methods return the task without await; await when using or try needs it.
    • SG-ASYNC-05 [REQUIRED] Fire-and-forget work logs failures and respects shutdown. Shared mutable state is locked on every access; no lock across await.

    6. Error handling

    • SG-ERR-01 [REQUIRED] Return errors, don't throw them: expected failures return the result type (SG-LIB-01); callers map it. Throw only for programmer errors (ArgumentNullException.ThrowIfNull, InvalidOperationException).
    • SG-ERR-02 [REQUIRED] Feature error catalogs, one per feature: static readonly error values or factory methods, codes from nameof (SG-NAME-09).
    • SG-ERR-03 [REQUIRED] Never swallow exceptions. No empty catch, no catch that returns success. Every catch returns an error or rethrows with throw;.
    • SG-ERR-04 [REQUIRED] OperationCanceledException always propagates; it is never converted to an error value.
    • SG-ERR-05 [REQUIRED] Unexpected exceptions propagate to the consuming application or the global handler; they are not converted to generic errors deep in the stack.
    • SG-ERR-06 [DEFAULT] One validation approach per repository (FluentValidation validators per request). No second validation-result type beside the result type.
    • SG-ERR-07 [REQUIRED] Errors shown to clients carry code and messages only, never stack traces or internals.

    7. Logging and tracing

    • SG-LOG-01 [REQUIRED] Application and library code logs through ILogger<T> only. No logging-library types outside host setup.
    • SG-LOG-02 [REQUIRED] Structured message templates with named PascalCase holes, never string interpolation.
    • SG-LOG-03 [REQUIRED] Never log secrets, tokens, passwords, connection strings, or full SQL with parameter values.
    • SG-LOG-04 [DEFAULT] Instrument with System.Diagnostics.Metrics; report percentiles (p50/p95/p99), not averages alone.

    8. EF Core

    • SG-EF-01 [DEFAULT] One IEntityTypeConfiguration<T> per entity. No data annotations on entities except where a package requires them.
    • SG-EF-02 [DEFAULT] One key type app-wide: Guid v7 (Guid.CreateVersion7(), time-ordered). Never string keys or sequential int ids in public URLs.
    • SG-EF-03 [DEFAULT] Audit keys: CreatedById non-nullable; UpdatedById nullable until the first update. Audit and soft-delete behaviour is read from the entity model; no SaveChanges overrides for it.
    • SG-EF-04 [DEFAULT] PostgreSQL names are snake_case via one convention. Stored instants are UTC.
    • SG-EF-05 [REQUIRED] Reads are AsNoTracking() by default. Lists are paged or explicitly bounded; no unbounded ToListAsync() on user-facing paths.
    • SG-EF-06 [DEFAULT] Project to *Response inside the query, not after loading full entities. Avoid N+1 queries and cartesian explosion (Include, projections, split queries as the shape needs).
    • SG-EF-07 [REQUIRED] Migrations: one per change, PascalCase name. Never edit a migration that has shipped.
    • SG-EF-08 [REQUIRED] DbContext is never shared across threads or held in a singleton; one per scope or unit of work. Multi-step writes run in a transaction.

    9. Formatting

    Formatting is tooling-owned. Flag deviations only where tooling does not already catch them, at LOW or nitpick severity. The repository .editorconfig wins over this section.

    • SG-FMT-01 [DEFAULT] Spaces inside parentheses in calls, declarations and control statements: if ( query is not null ). Spaced attribute brackets: [ Authorize ]. Spaces inside generic declaration angles, none at use sites.
    • SG-FMT-02 [DEFAULT] Column-align = in assignment blocks, field declarations and object initializers.
    • SG-FMT-03 [DEFAULT] Explicit usings in one #region Usings before the namespace; never empty.
    • SG-FMT-04 [DEFAULT] var everywhere, except when the declared type intentionally differs.
    • SG-FMT-05 [DEFAULT] Expression-bodied members for single expressions. Braces always; single-statement blocks on one line.
    • SG-FMT-06 [DEFAULT] Long parameter lists: parameters on indented continuation lines, closing ) on its own line. Fluent chains: one call per line, aligned under the first ..
    • SG-FMT-07 [DEFAULT] Two blank lines between logical steps inside a method body.
    • SG-FMT-08 [DEFAULT] Modern C#: target-typed new(), collection expressions, is null / is not null, ??=, patterns. Optional reference parameters are always nullable (string? note = null).
    • SG-FMT-09 [DEFAULT] C# 14: use the field keyword for simple property validation or trimming; null-conditional assignment is fine; extension member blocks not yet (classic static extension methods); no primary constructors.
    • SG-FMT-10 [REQUIRED] XML docs are errors when missing on public API (CS1591): every public type, member and parameter; every property on *Request/*Response/*Settings; service interfaces list error codes in <returns>.
    • SG-FMT-11 [REQUIRED] No commented-out code; git keeps history.
    • SG-FMT-12 [DEFAULT] TODOs only with a tracking issue: // TODO@<Project>(#N): <what> — <why>. No TODO without an issue.
    • SG-FMT-13 [REQUIRED] Human characters only: source code files contain printable ASCII (0x20-0x7E) plus tab and newline. No smart quotes, em or en dashes, arrows, checkmarks, emoji or other typographic or decorative Unicode in code, comments or string literals. Identifiers use ASCII letters, digits and underscore only — a homoglyph identifier (Cyrillic а for Latin a) is a defect, not a style choice.
    • SG-FMT-14 [REQUIRED] Invisible and control characters are forbidden in every text file, documentation included: zero-width characters, byte-order marks (files are UTF-8 without BOM), bidi controls (the Trojan Source attack class), non-breaking spaces, soft hyphens, and control characters other than tab and newline. These characters survive copy-paste invisibly and break builds, diffs and reviews.
    • SG-FMT-15 [DEFAULT] Non-ASCII text belongs in localization resources and user-facing content files, never inline in code. A code file that genuinely needs a non-ASCII literal (test data, i18n fixtures, currency symbols in format strings) records an OVERRIDE SG-FMT-15 with a scope covering exactly those files.

    10. Dependencies

    • SG-DEP-01 [REQUIRED] Shipped dependencies must be free and permissive (MIT, Apache-2.0, BSD). Copyleft, commercial, or licences that pass obligations to consumers fail. Licensed build tooling that does not ship is exempt.

    • SG-DEP-02 [REQUIRED] Every third-party package passes the health gate before it is added and before any major bump. Fail criteria: latest stable release older than 18 months or prerelease-only; no commit in 12 months or archived; unmaintained backlog; any unpatched vulnerability advisory; does not run on the target frameworks; used slice could be written and tested in under roughly 1,000 lines (build it instead).

    • SG-DEP-03 [DEFAULT] Health-gate warn criteria (release 12–18 months old; last commit 6–12 months; more than 50 open PRs or recent unanswered issues; compatibility-only target framework; single maintainer) need one decision line in the project guide: which check, why accepted, review date within 6 months.

    • SG-DEP-04 [DEFAULT] Every third-party pin carries evidence: a checked-date comment with last release, last commit and licence.

    • SG-DEP-05 [DEFAULT] Re-check all pins before every promotion and quarterly: outdated plus vulnerable, including transitive.

    • SG-DEP-06 [DEFAULT] One choice per purpose. JSON is System.Text.Json by default; alternatives only where a dependency forces it, documented.

    • SG-DEP-07 [REQUIRED] Application projects commit packages.lock.json (RestorePackagesWithLockFile) and CI restores with --locked-mode, so a changed resolution fails the build instead of drifting.

    • SG-DEP-08 [REQUIRED] NuGet audit warnings for high and critical advisories (NU1903/NU1904) are build errors, including transitive packages (NuGetAuditMode=all). Suppressing an advisory needs its URL, a reason and an expiry recorded beside the suppression.

    • SG-DEP-09 [REQUIRED] Package source mapping pins each package ID pattern to its intended feed, with inherited sources cleared. A package arriving from the wrong feed fails restore.

    • SG-DEP-10 [DEFAULT] Releases generate an SBOM (CycloneDX or SPDX) from the locked dependency graph and keep it with the release artifacts.

    • SG-DEP-11 [DEFAULT] Security analyzers run at AnalysisLevelSecurity=latest-all (or the repo's agreed equivalent) so security rules are enforced by the build, not by review memory.

    11. Build and versioning

    • SG-BUILD-01 [DEFAULT] global.json pins the SDK with feature roll-forward. Central package management: one version per package.

    • SG-BUILD-02 [REQUIRED] Exact version pins; no floating versions.

    • SG-BUILD-03 [DEFAULT] Directory.Build.props carries target framework, Nullable, ImplicitUsings, TreatWarningsAsErrors, latest-recommended analysis level, code-style enforcement in build, and documentation file generation.

    • SG-BUILD-04 [REQUIRED] Feed credentials never go in a repository feed config: user-level config locally, secrets in CI.

    • SG-BUILD-05 [REQUIRED] Libraries use SemVer per package. Breaking changes only in a major version, deprecated first where a deprecation path exists.

    • SG-BUILD-06 [DEFAULT] Container images are multi-stage, run as non-root, ship no secrets or build tools in the final layer, and prefer chiseled/distroless bases. The image carries a health check matching SG-OBS-04.

    • SG-BUILD-07 [DEFAULT] CI restores in locked mode (SG-DEP-07) and caches by lock-file hash; a cache hit never changes resolution.

    • SG-BUILD-08 [DEFAULT] Architecture decisions with lasting cost (transport, storage, auth, major dependencies) are recorded as short ADRs in docs/adr/, linked from the project guide.

    12. Testing

    • SG-TEST-01 [REQUIRED] Core and data code is tested comprehensively, not sampled: unit and integration tests, in CI, for every package. A feature is not done until its tests are green in CI.

    • SG-TEST-02 [REQUIRED] Integration tests run against real databases. Never fake the database in a way that hides SQL; do not mock DbContext or the database for data-access tests.

    • SG-TEST-03 [REQUIRED] A skipped integration test is never a passing one: skip explicitly and do not claim green until CI runs it.

    • SG-TEST-04 [REQUIRED] Test isolation: each test starts from a known state; tests never depend on each other's data or on run order.

    • SG-TEST-05 [DEFAULT] Test names: Method_Scenario_ExpectedResult (backend); does X when Y in describe blocks (frontend).

    • SG-TEST-06 [REQUIRED] Coverage on new code is at least 80% as a floor, not the goal. A bug fix ships with the test that failed before the fix. Branch coverage is reported for branching code; an untested branch is a gap.

    • SG-TEST-07 [REQUIRED] Behaviour-preserving refactors follow the protocol, in order: read line and branch coverage and list uncovered branches; characterization tests per uncovered branch asserting today's behaviour (fix the test, not the code; commit tests alone, green); mutation check (every mutant must fail a test); one extraction per commit with zero warnings and tests green after each; repeat the mutation check; confirm the quality gate after push.

    • SG-TEST-08 [DEFAULT] Test methods obey the same size thresholds as production code (SG-PAT-11); long arrange blocks move into builders or fixtures instead of growing the test.

    • SG-TEST-09 [REQUIRED] Unreachable branches are never deleted silently: throw UnreachableException naming the invariant, in its own commit, linked to an issue.

    • SG-TEST-10 [DEFAULT] Test projects relax library rules by test .editorconfig only: no Async suffix requirement and no XML docs in tests.

    • SG-TEST-11 [DEFAULT] Mutation testing (Stryker.NET) grades test quality on critical paths: diff-scoped runs on pull requests, full runs nightly. Surviving mutants on auth, money or access-control paths become tests; 100% is not the target.

    • SG-TEST-12 [DEFAULT] Service boundaries carry contract tests (consumer-driven, for example Pact) so producer changes break CI, not consumers.

    • SG-TEST-13 [DEFAULT] Pure logic with wide input spaces (parsers, calculators, encoders) gets property-based tests (FsCheck) for its invariants, beside example tests.

    • SG-TEST-14 [REQUIRED] Tests never sleep or widen assertions to pass. A flaky test is fixed or quarantined with an issue and an owner in the same change that quarantines it.

    13. Quality gate

    • SG-GATE-01 [REQUIRED] On new code: zero new issues at any severity, coverage at least 80%, duplication at most 3%. A red gate fails the build.
    • SG-GATE-02 [DEFAULT] Run the scanner locally before push; CI is the second check, not the first place a failing gate is discovered.
    • SG-GATE-03 [REQUIRED] Suppressions live in code with justification, or as .editorconfig severity none with a comment when a rule conflicts everywhere. Never UI-only accepted or false-positive marks; a line edit re-raises them.
    • SG-GATE-04 [DEFAULT] Fix in order: vulnerabilities, bugs, security hotspots, code smells.
    • SG-GATE-05 [DEFAULT] The gate judges new work only (new-code definition: previous version). Clean old issues while touching them, not in one sweep.

    14. Git

    • SG-GIT-01 [REQUIRED] Changes land through a feature branch with a pull request into the integration branch. No direct pushes to protected branches; no direct commits to release branches.
    • SG-GIT-02 [DEFAULT] Conventional Commits: feat:, fix:, refactor:, docs:, test:, chore:, feat!: for breaking. Scope is the feature or package name.
    • SG-GIT-03 [REQUIRED] Each commit builds, passes tests and passes the gate on its own. One commit per feature; foundation pieces land first. Small pull requests, in order.

    15. Security

    • SG-SEC-01 [REQUIRED] No secrets in code or committed config. Local: user-secrets or environment variables. Server: environment variables or a secret store.

    • SG-SEC-02 [REQUIRED] Raw SQL is parameterised only. String concatenation into SQL is forbidden (see SG-PAT-01).

    • SG-SEC-03 [REQUIRED] Injection defences hold on every input path: SQL, command, path traversal, LDAP and XSS sinks are parameterised, validated or encoded as their context requires.

    • SG-SEC-04 [REQUIRED] Authentication and authorization are checked on the server for every endpoint and hub method. Client-side checks are never the authorization. Object-level access checks prevent IDOR.

    • SG-SEC-05 [REQUIRED] No tokens, connection strings or user data in logs, build reports or error responses.

    • SG-SEC-06 [REQUIRED] AI features send only what the feature needs; never secrets or other users' data to an AI provider.

    • SG-SEC-07 [REQUIRED] Encryption is AES-GCM only. Passwords use PasswordHasher<T> or PBKDF2. Integrity hashes are SHA-256 or stronger. Never 3DES, ECB or MD5.

    • SG-SEC-08 [REQUIRED] No unsafe deserialization, no disabled TLS validation, no hand-rolled cryptography.

    • SG-SEC-09 [REQUIRED] Server-side request forgery is treated as broken access control: outbound URLs from user input are allow-listed by scheme and host, redirects are re-validated, and cloud metadata endpoints are unreachable from application code.

    • SG-SEC-10 [REQUIRED] Secure configuration is code-reviewed like code: debug modes off, default credentials removed, directory listing and verbose errors off, security headers set, and configuration drift is checked in CI where the platform supports it.

    • SG-SEC-11 [REQUIRED] Exceptional conditions fail safe: timeouts, resource exhaustion and partial failures leave data consistent (transactions, compensation) and never bypass authorization or validation. Fail-open paths are forbidden.

    • SG-SEC-12 [REQUIRED] Security events are logged and alerted, not only recorded: authentication failures, authorization denials and integrity failures raise alerts with an owner. Logs are tamper-evident where the platform supports it.

    • SG-SEC-13 [DEFAULT] Passwordless sign-in (passkeys/WebAuthn) is offered where the identity stack supports it; passwords remain only where passkeys cannot serve the users.

    • SG-SEC-14 [REQUIRED] CI runs secret scanning on every change. A leaked secret is rotated, not only removed from history.

    16. Observability

    Logging rules live in section 7; this section covers traces, metrics and health.

    • SG-OBS-01 [REQUIRED] Services emit the three signals through OpenTelemetry: traces (ActivitySource), metrics (Meter) and structured logs (ILogger), exported over OTLP to a collector. Vendor SDKs are not referenced directly in application code.
    • SG-OBS-02 [REQUIRED] Logs carry the current trace and span IDs (logging scopes or the OpenTelemetry log bridge), so a log line joins its trace. Error responses expose the trace ID for support correlation.
    • SG-OBS-03 [REQUIRED] Metric tags are low-cardinality and bounded. Per-request values (user IDs, entity IDs) belong in traces and logs, never in metric dimensions.
    • SG-OBS-04 [REQUIRED] Health endpoints split liveness from readiness: liveness checks only that the process answers; readiness checks dependencies. Dependency checks never sit on liveness (a database failover must not restart every instance). Health output is minimal: no versions, connection strings or exception details.
    • SG-OBS-05 [DEFAULT] Instrument business operations with custom spans and counters (orders placed, messages processed, latency percentiles). Automatic instrumentation covers plumbing; domain questions need domain telemetry. Sampling and exporter cost are decided in the project guide.

    17. Time handling

    • SG-TIME-01 [REQUIRED] Production code never reads the system clock directly. Inject TimeProvider, register TimeProvider.System once, and call GetUtcNow(). Read the clock once per operation and reuse the value.
    • SG-TIME-02 [REQUIRED] Delays, timers and timeouts use the TimeProvider overloads (Task.Delay(delay, time, ct), PeriodicTimer(period, time), WaitAsync(timeout, time)), so tests control waiting without sleeping.
    • SG-TIME-03 [REQUIRED] Instants are stored and exchanged in UTC as DateTimeOffset. Local time and time zones are presentation concerns, converted at the edge. Calendar and recurrence math uses a calendar-aware library (NodaTime) decided in the project guide, never hand-rolled AddMonths arithmetic.
    • SG-TIME-04 [DEFAULT] Time-dependent rules are tested at the boundary: one tick before, exactly on, and just after, including across midnight UTC, with FakeTimeProvider. No tolerance windows or sleeps to make time tests pass.

    18. Backend API contract

    • SG-API-01 [REQUIRED] One error contract per API: the library envelope (SG-LIB-01) with server-decided HTTP status, or RFC 9457 Problem Details where the project guide chooses it. Error bodies carry code, messages and trace ID only (SG-ERR-07).
    • SG-API-02 [REQUIRED] Mutating endpoints that clients may retry (payments, orders, submissions) support an Idempotency-Key header: the first response is stored with the key and replayed for duplicates within its retention window. Duplicate execution on retry is a defect.
    • SG-API-03 [REQUIRED] List endpoints are paged. Large or fast-changing collections use keyset (cursor) pagination; offset pagination is limited to small, stable sets. Page size has a server-enforced maximum.
    • SG-API-04 [REQUIRED] Public and partner APIs are rate-limited with partitioned policies (per client, user or IP) returning 429 with Retry-After. Expensive operations (exports, reports, search) carry concurrency limits.
    • SG-API-05 [DEFAULT] Breaking changes ship in a new contract version (SG-LIB-12). Deprecated versions announce sunset with Deprecation/Sunset headers and a removal date in the project guide.
    • SG-API-06 [DEFAULT] Cacheable GET responses send validators (ETag/Last-Modified) and honor conditional requests. Responses that must not be stored send explicit Cache-Control: no-store.

    19. Messaging

    • SG-MSG-01 [REQUIRED] Message handlers are idempotent. Every transport delivers at least once; duplicate delivery must not duplicate effects (dedupe keys, upserts, or processed-message records).
    • SG-MSG-02 [REQUIRED] State changes and their outgoing messages commit together (transactional outbox or equivalent). Publishing after commit without an outbox is forbidden where a lost message loses business data.
    • SG-MSG-03 [REQUIRED] Poison messages go to a dead-letter destination with the failure reason recorded, and dead letters are monitored and replayable. No infinite retry loops.
    • SG-MSG-04 [DEFAULT] Transport choice is recorded in the project guide. House default for internal fan-out is Redis Pub/Sub, with Streams where replay is needed; a durable broker (or MassTransit over one) is adopted when durable replay, independent consumers that must not miss messages, or ingress beyond roughly 10k messages/second requires it.
    • SG-MSG-05 [DEFAULT] Consumers acknowledge only after successful processing (manual offset/ack management), bound prefetch/concurrency, and shut down gracefully without dropping in-flight messages.

    20. Hosting and background work

    • SG-HOST-01 [REQUIRED] Background loops catch, log and keep running, or exit non-zero so the supervisor restarts the process. An unhandled exception that stops the host silently is a defect.
    • SG-HOST-02 [REQUIRED] Every loop and delay honors the stopping token; shutdown finishes within the host timeout, draining or checkpointing in-flight work.
    • SG-HOST-03 [DEFAULT] Scheduled jobs are idempotent and overlap-safe: a second instance or a retry must not double-apply effects (leases, dedupe keys, or single-runner locks).
    • SG-HOST-04 [DEFAULT] Periodic work uses PeriodicTimer with the injected TimeProvider (SG-TIME-02); missed ticks coalesce by design and the job tolerates it.

    21. Performance measurement

    • SG-PERF-01 [REQUIRED] Performance claims come from measurement, never from intuition: a fixed harness (BenchmarkDotNet for micro-benchmarks; the same scenario and load for system measurements) so numbers stay comparable across changes.
    • SG-PERF-02 [DEFAULT] Latency-critical paths record p50/p95/p99 and throughput before and after a change, and the decision (including runtime choices such as Native AOT per phase) is written down with its numbers.
    • SG-PERF-03 [DEFAULT] Hot paths avoid avoidable allocations: span-based parsing, pooled buffers and writers where profiling shows allocation pressure. Optimization without a profile is a review finding.
    • SG-PERF-04 [DEFAULT] Libraries stay trim/AOT compatible where their consumers need it (IsAotCompatible, no unannotated reflection); trim warnings in library builds are errors or justified suppressions.

    22. Money

    • SG-MONEY-01 [REQUIRED] Money is decimal (or integer minor units), never float/double. Amounts always travel with their currency code.
    • SG-MONEY-02 [REQUIRED] Rounding mode is explicit at every money boundary (calculation, storage, display) and recorded in the project guide. Midpoint cases are tested.
    • SG-MONEY-03 [DEFAULT] Money crosses APIs as decimal strings or minor units per the contract, never as binary floating point.

    23. Privacy

    • SG-PRIV-01 [REQUIRED] Personal data is classified in the project guide (what is collected, why, retention period). Logs and telemetry never carry personal data beyond identifiers needed for support (extends SG-LOG-03).
    • SG-PRIV-02 [DEFAULT] User data has an export path and a delete path before public release, including derived data and backups policy.
    • SG-PRIV-03 [DEFAULT] Data residency (where user data is stored and processed) is decided in the project guide and enforced by configuration, not by convention.

    24. AI features

    • SG-AI-01 [REQUIRED] AI features degrade gracefully: provider timeouts, rate limits and outages produce a defined fallback (cached, reduced, or a clear error), never a hung request or silent wrong output.
    • SG-AI-02 [DEFAULT] Prompts, models and tool definitions are versioned artifacts in the repo; a change to any of them runs the feature's eval set before merge.
    • SG-AI-03 [DEFAULT] AI calls carry cost and token budgets per request and per tenant where applicable, enforced in code, with usage logged (without user content, SG-SEC-06).
    • SG-AI-04 [DEFAULT] Model output is untrusted input: validated against schemas and authorization before it drives actions, exactly like user input.

    Part 2 — Frontend

    25. TypeScript core

    • SG-FE-TS-01 [REQUIRED] strict: true plus noUncheckedIndexedAccess, noImplicitOverride, exactOptionalPropertyTypes.
    • SG-FE-TS-02 [REQUIRED] No any; use unknown and narrow. Non-null ! only right after a check the compiler cannot see, with a comment.
    • SG-FE-TS-03 [DEFAULT] PascalCase types with no I prefix; camelCase functions, variables and properties; UPPER_SNAKE_CASE true constants.
    • SG-FE-TS-04 [REQUIRED] Transport models are *Request / *Response / *Settings; no Dto suffix (same as backend).
    • SG-FE-TS-05 [DEFAULT] Booleans read as questions. No Async suffix on promise functions; observables end in $.
    • SG-FE-TS-06 [DEFAULT] Prefer union string literals over enum; as const objects for runtime values. Discriminated unions for results and states.
    • SG-FE-TS-07 [DEFAULT] readonly on properties and arrays callers must not change.
    • SG-FE-TS-08 [DEFAULT] Files are kebab-case, one exported concept per file. A package's public API is its entry point only. No default exports.
    • SG-FE-TS-09 [DEFAULT] Package or brand prefix lives in the package scope only, never in type, function, component, selector or CSS class names.
    • SG-FE-TS-10 [REQUIRED] The backend size thresholds apply unchanged (SG-PAT-09 to SG-PAT-13): function at most 50 lines, component or service class at most 500 lines, file at most 1000 lines, complexity at most 10, nesting at most 3, parameters at most 7. A component renders and binds; data shaping and business rules live in services or pure functions.

    26. API contract and results

    • SG-FE-API-01 [REQUIRED] Never hand-write API types. Generate them from the OpenAPI document or schema; generated files are never edited by hand.
    • SG-FE-API-02 [REQUIRED] Unwrap the server envelope in one place (interceptor or client wrapper) into a Result<T> discriminated union. Components never see the raw envelope.
    • SG-FE-API-03 [REQUIRED] Read the error code; never parse message text to decide behaviour. HTTP status is decided by the server.
    • SG-FE-API-04 [REQUIRED] The browser draws, the server decides: no SQL, permission logic or business rules in the browser. Client checks are UX only; the server re-checks everything.
    • SG-FE-API-05 [REQUIRED] Auth tokens never live in localStorage or sessionStorage. Prefer an HttpOnly, Secure, SameSite cookie or a BFF; credentialed requests only to the app's own API origin.
    • SG-FE-API-06 [REQUIRED] Fallible calls return a result, not a thrown error. Throw only for programmer errors.
    • SG-FE-API-07 [REQUIRED] Never swallow errors: no empty catch, no stream error handler that completes silently without logging and a user-visible state.
    • SG-FE-API-08 [DEFAULT] Network, timeout and cancellation map to fixed client codes (Network, Timeout, Cancelled). Cancellation is not shown as an error.
    • SG-FE-API-09 [REQUIRED] Pick the localized message by locale. Never show error codes or stack traces to users.

    27. Localisation, RTL and dates

    • SG-FE-I18N-01 [DEFAULT] Every app supports its locales, including RTL, from day one. lang and dir come from the active locale.
    • SG-FE-I18N-02 [REQUIRED] CSS logical properties only (margin-inline-start, inset-inline-start, text-align: start); never left/right for layout. Directional icons mirror under RTL.
    • SG-FE-I18N-03 [REQUIRED] No hard-coded user-facing text in templates or code in a multilingual app; every string goes through the i18n layer.
    • SG-FE-I18N-04 [DEFAULT] Numbers, money and dates go through Intl; never string-concatenate dates. Hijri dates use the built-in Islamic calendar via Intl; the server stays the source of truth for stored values.
    • SG-FE-I18N-05 [DEFAULT] Dates cross the wire as ISO 8601 strings and convert at the edge, not in components.

    28. Styling and accessibility

    • SG-FE-STYLE-01 [DEFAULT] Design tokens are CSS custom properties (--zh-*) defined once and themed by overriding. No raw hex or pixel values in components; spacing and type scales come from tokens, no magic numbers.
    • SG-FE-STYLE-02 [DEFAULT] Component styles are encapsulated; globals live only in the app styles folder. Class names are kebab-case, prefixed in shared libraries.
    • SG-FE-STYLE-03 [DEFAULT] No !important except to override unreachable third-party styles, with a comment.
    • SG-FE-A11Y-01 [REQUIRED] Target WCAG 2.2 AA. Semantic HTML first; ARIA only when no native element fits.
    • SG-FE-A11Y-02 [REQUIRED] Every interactive element is keyboard-reachable with a visible focus style; no outline: none without a replacement.
    • SG-FE-A11Y-03 [REQUIRED] Every form control has a label; errors are linked with aria-describedby. Contrast at least 4.5:1 for text; never colour alone to carry meaning.
    • SG-FE-A11Y-04 [DEFAULT] Automated axe checks run in component tests for shared components.

    29. Frontend security

    • SG-FE-SEC-01 [REQUIRED] No secrets in shipped frontend code or environment files; anything shipped to the browser is public.
    • SG-FE-SEC-02 [REQUIRED] No raw HTML from users or the server into the DOM. Render sanitised HTML in a sandboxed iframe; any sanitizer bypass is reviewed and commented with the source and why it is safe.
    • SG-FE-SEC-03 [REQUIRED] No eval, new Function, inline handler strings or custom user JavaScript. Pages are data, not code.
    • SG-FE-SEC-04 [REQUIRED] Ship a Content Security Policy without unsafe-eval. External links open with rel="noopener noreferrer".
    • SG-FE-SEC-05 [REQUIRED] npm audit high and critical findings fail CI.

    30. Frontend dependencies, formatting, testing, packaging

    • SG-FE-DEP-01 [REQUIRED] Every third-party npm package passes the section 10 health gate before it is added. No vendor-licensed packages in libraries; licences are MIT, Apache-2.0 or BSD.
    • SG-FE-DEP-02 [REQUIRED] Libraries declare framework packages as peerDependencies, never dependencies.
    • SG-FE-DEP-03 [DEFAULT] Apps pin exact versions through the committed lockfile and install with npm ci in CI. Libraries use caret ranges on peers matching supported majors.
    • SG-FE-FMT-01 [DEFAULT] Prettier owns formatting (print width 120, single quotes). The C# spacing profile does not apply to TypeScript, HTML or SCSS.
    • SG-FE-FMT-02 [DEFAULT] ESLint owns correctness: no explicit any, explicit module boundary types on public APIs, no floating promises, strict equality, no console beyond warn/error, import ordering.
    • SG-FE-FMT-03 [DEFAULT] TSDoc on every exported library symbol: summary, params, returns, throws where it can throw, example on entry points. Apps document only non-obvious code.
    • SG-FE-TEST-01 [DEFAULT] Test behaviour through the public surface, not private internals. No real network in unit tests; mock at the HTTP layer.
    • SG-FE-TEST-02 [DEFAULT] Shared components cover rendering, keyboard interaction, RTL layout and axe. End-to-end tests cover critical journeys only.
    • SG-FE-PKG-01 [REQUIRED] SemVer per package, bumped in the same commit as the change. Breaking changes only in a major version, deprecated first.
    • SG-FE-PKG-02 [DEFAULT] Libraries ship ESM with types and sideEffects: false unless they register global styles. Every package ships a README and a changelog.

    31. Angular addendum

    • SG-FE-NG-01 [DEFAULT] Standalone components only, zoneless change detection, strictTemplates, strictInjectionParameters and strictInputAccessModifiers on. Follow the official Angular style guide and CLI defaults unless this guide says otherwise.
    • SG-FE-NG-02 [DEFAULT] Selector prefix zh in libraries; a short app prefix set in angular.json in apps. Injection tokens are UPPER_SNAKE_CASE. Provider functions are provide<Thing>().
    • SG-FE-NG-03 [REQUIRED] OnPush on every component (explicit before v22; the default on v22+, where it is not set explicitly).
    • SG-FE-NG-04 [REQUIRED] Signal APIs for inputs and outputs (input(), input.required(), output(), model()); no @Input / @Output decorators.
    • SG-FE-NG-05 [REQUIRED] Built-in control flow (@if, @for with track, @switch, @defer); no structural-directive control flow.
    • SG-FE-NG-06 [DEFAULT] Route-level components load data; shared components take inputs and emit outputs only. No template logic beyond simple reads; derive with computed(). Host bindings via host metadata.
    • SG-FE-NG-07 [DEFAULT] Signals for state; RxJS only for streams. Async data via the resource APIs. Bridge with toSignal() / toObservable(); never subscribe() in a component without takeUntilDestroyed(). effect() only for side effects that leave Angular, never to copy one signal into another.
    • SG-FE-NG-08 [DEFAULT] inject() in field initializers. Services are providedIn: 'root' unless they hold per-feature state. Library configuration goes through one provide<Thing>() returning EnvironmentProviders with a typed *Settings and an InjectionToken.
    • SG-FE-NG-09 [DEFAULT] Angular CDK for behaviour, Angular Material for app chrome. Libraries do not force a theme; they read the design tokens and the host app themes them. RTL logic uses the CDK Directionality service, never document.dir directly.
    • SG-FE-NG-10 [DEFAULT] i18n uses built-in @angular/localize with per-locale builds; switching language reloads into the other locale build. A runtime i18n library only when an app must switch without reload, through the health gate.
    • SG-FE-NG-11 [REQUIRED] Functional interceptors only. One envelope interceptor turns the server envelope into Result<T>; one error interceptor maps network, timeout and cancel to the fixed client codes. Every request is cancellable; search-as-you-type uses switchMap with debounce.
    • SG-FE-NG-12 [DEFAULT] New forms use Signal Forms (v22+); existing reactive forms may stay until touched. Validation messages are keyed by the same error codes the backend returns. Client validation is UX only; the server result is final.
    • SG-FE-NG-13 [REQUIRED] Never bypassSecurityTrust* without a review comment naming the value's source and why it is safe. No [innerHTML] with server or user data; use the sandboxed preview iframe. XSRF configuration when the API uses cookie auth.
    • SG-FE-NG-14 [DEFAULT] Tests run zoneless with await fixture.whenStable(); no fakeAsync reliance. Shared components use TestBed with CDK component harnesses.

    32. Frontend performance

    • SG-FE-PERF-01 [DEFAULT] Public pages meet Core Web Vitals at p75 field data (LCP, INP, CLS within Google's good thresholds), measured in CI with budgets per route; a budget breach is a finding, not a suggestion.
    • SG-FE-PERF-02 [DEFAULT] Images ship responsive sizes in modern formats with explicit dimensions; fonts load with font-display: swap and subsetting. Third-party scripts load deferred and budgeted.

    Part 3 — MAUI

    33. MAUI

    • SG-MAUI-01 [REQUIRED] MVVM with CommunityToolkit.Mvvm source generators ([ObservableProperty], [RelayCommand]). Views bind to view models; code-behind holds no business logic.
    • SG-MAUI-02 [REQUIRED] Compiled bindings everywhere: x:DataType on every binding scope, binding warnings (XC0022/XC0025) treated as errors. Reflection-based bindings are forbidden in shipped builds.
    • SG-MAUI-03 [REQUIRED] The UI thread does no I/O or CPU-heavy work. Async work marshals only UI updates back through the dispatcher. Startup registers services without doing work; non-essential initialization waits until after the first page renders.
    • SG-MAUI-04 [DEFAULT] Lists use CollectionView with flat item templates and virtualization. Layouts prefer flat Grid over nested stacks; Border replaces Frame; ListView is not used.
    • SG-MAUI-05 [DEFAULT] Platform code lives in Platforms/ folders or partial classes behind interfaces. Handlers and mappers customize controls; renderers are migration steps only. Each platform follows its own conventions (navigation, back behavior, safe areas, text scaling).
    • SG-MAUI-06 [DEFAULT] The compilation strategy is chosen per platform and recorded: ReadyToRun by default, NativeAOT where the app and its libraries are trim/AOT compatible. Trim warnings are fixed or justified, never shipped unexplained. Performance is measured on real devices in Release builds against a baseline.

    Overrides template

    Copy this into the project guide and keep every tag in this one section:

    ## Generalized guide overrides
    
    <!-- DEFAULT rules: replace freely. -->
    - OVERRIDE SG-FMT-03: <replacement rule> — <reason>
    
    <!-- REQUIRED rules: force-override only with approval and a review date. -->
    - BYPASS SG-SEC-04: <reason> — approved: <name>, review: YYYY-MM-DD
    
    <!-- Libraries: one tag per bypassed package. -->
    - BYPASS-LIB <PackageId>: <reason> — alternative: <what replaces it>
    
    <!-- Optional scope limits any tag to matching paths. -->
    - OVERRIDE SG-NAME-07: <replacement rule> — <reason> [scope: src/legacy/**]
    

    Reviewer checklist

    1. Find the project guide and its overrides section. Collect every OVERRIDE, BYPASS and BYPASS-LIB tag.
    2. Validate each tag: ID exists, reason present, bypass approver and unexpired review date present, scope covers the changed code.
    3. Check the library map before judging infrastructure code: a covering Available package must be used unless a valid BYPASS-LIB covers it.
    4. Judge conventions against project rules first, then REQUIRED rules, then DEFAULT rules. Framework correctness and security also follow the stack references.
    5. Cite the rule ID (and the tag, when one applies) in every guide finding's Ref.
    6. Judge responsibility, not just size: a method under the line cap can still break SG-PAT-09 by mixing orchestration with work, and a small class can still break SG-PAT-10 by mixing concerns. Analyzers enforce the caps; the reviewer enforces the responsibility.
    • Edit this page
    In this article
    Back to top Generated by DocFX