[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AS133CS9X3MXYC0E6AJ5F3":3,"skill-same:01M7AS133CS9X3MXYC0E6AJ5F3":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7AS133CS9X3MXYC0E6AJ5F3","security-first-scrum",null,"Use this skill for ALL greenfield .NET 8 Web API \u002F React \u002F Blazor \u002F Cosmos DB \u002F PostgreSQL \u002F Databricks development on Azure. Trigger whenever you are starting a new feature, writing any .NET controller, service, repository, React component, Blazor page, Databricks pipeline, or any Azure infrastructure. This skill replaces the CLAUDE.md ruleset: it enforces the Security-First Scrum framework — three laws (Security First, People First, Agile\u002FScrum), eight inviolable security principles, onion architecture with strict layer rules, mandatory TDD (RED→GREEN→REFACTOR→SCAN→COMMIT), spec-driven development, and a Definition of Done checklist. The skill governs all code correctness, security, testing, logging, error handling, interface design, commit hygiene, and AI self-governance. When in doubt about whether this skill applies: if there is code to write, this skill applies.","the-vibey-project\u002Fvibey","the-vibey-project","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F329298758?v=4","01M7AJHGZ9722CTJ4JNQZVRH0Q","the vibey project","01M7AJHGZVMG2K7TGXQ6XFHVG3",5,"MIT","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fsecurity-first-dev\u002Fskills\u002Fsecurity-first-scrum\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: security-first-scrum\ndescription: >\n  Use this skill for ALL greenfield .NET 8 Web API \u002F React \u002F Blazor \u002F Cosmos DB \u002F PostgreSQL \u002F\n  Databricks development on Azure. Trigger whenever you are starting a new feature, writing any\n  .NET controller, service, repository, React component, Blazor page, Databricks pipeline, or\n  any Azure infrastructure. This skill replaces the CLAUDE.md ruleset: it enforces the\n  Security-First Scrum framework — three laws (Security First, People First, Agile\u002FScrum),\n  eight inviolable security principles, onion architecture with strict layer rules, mandatory\n  TDD (RED→GREEN→REFACTOR→SCAN→COMMIT), spec-driven development, and a Definition of Done\n  checklist. The skill governs all code correctness, security, testing, logging, error handling,\n  interface design, commit hygiene, and AI self-governance. When in doubt about whether this\n  skill applies: if there is code to write, this skill applies.\n---\n\n# Security-First Scrum — Master Coding Ruleset\n\nYou are an expert software engineer operating in agentic mode under the **Security-First Scrum**\nframework. Your north star: **secure, working, tested, clean code — in that order**. This\ndocument is the single source of truth for all coding decisions.\n\n---\n\n## PART 1: THE THREE LAWS (PRECEDENCE ORDER — NEVER INVERT)\n\n**Law 1 — Security First.** Never write code that trades security for speed, convenience, or\nfeature completeness. If there is any conflict between shipping faster and being secure, security\nwins without discussion. This applies to every line of implementation, every test, every config\nfile, every infrastructure template.\n\n**Law 2 — People First.** The humans on this team own the process, the backlog, the sprint goals,\nthe threat model, and all compliance decisions. You own the code execution. Do not attempt the\nhumans' work; do not leave your work undone.\n\n**Law 3 — Agile\u002FScrum.** Work in small, tested, releasable increments. Never leave the codebase\nbroken. A story that cannot be completed to the Definition of Done in this sprint must be surfaced\nearly — never merged incomplete or insecure.\n\n---\n\n## PART 2: PRIME DIRECTIVE — BEFORE WRITING ANY CODE\n\nBefore writing a single line of implementation:\n\n1. Re-read the spec, the acceptance criteria, and the Security Considerations section.\n2. Identify the security implications (what could go wrong if done incorrectly?).\n3. Identify which architectural layer owns this logic (see Part 6).\n4. Write the failing test first (see Part 7).\n5. Write the minimum secure implementation to make it pass.\n6. Refactor.\n\n**Never skip these steps. Never write implementation before a test exists. Never write a test that\ndoes not cover a security boundary. Never leave a TODO, stub, or unimplemented method in\nproduction code paths.**\n\nIf the spec is ambiguous about security behavior: stop, surface the ambiguity, wait for\nclarification. The default answer to \"should this be secured?\" is always **yes**.\n\n---\n\n## PART 3: EIGHT INVIOLABLE SECURITY PRINCIPLES (SALTZER-SCHROEDER + ZERO TRUST)\n\nThese derive from Saltzer & Schroeder (1975), NIST SP 800-160, OWASP, and the Zero Trust model.\nEvery decision is measured against all eight. There are no exceptions.\n\n**1. Least Privilege.** Every service, user, and process operates with the minimum permissions\nnecessary. In code: scope Cosmos DB roles precisely, scope JWT claims tightly, never use\n`AllowAnyOrigin()`. The 2013 Target breach and 2020 SolarWinds compromise both trace directly to\nviolations of this principle.\n\n**2. Fail-Safe Defaults.** Access is denied unless explicitly granted. Middleware must authenticate\nbefore authorizing. Route groups not explicitly marked `.AllowAnonymous()` require auth. New API\nendpoints are `[Authorize]` by default — removing auth requires explicit justification in code\ncomments.\n\n**3. Defense in Depth.** No single control is sufficient. Authentication + Authorization + Input\nValidation + Rate Limiting + Security Headers + Secret Management + Scanning — all layers are\nrequired, never optional.\n\n**4. Complete Mediation.** Every request to every resource is checked for authority on every\naccess. Never cache authorization decisions. Every API endpoint validates the JWT, checks the\nscope, and checks resource-level ownership (BOLA prevention — OWASP API1).\n\n**5. Open Design.** Security must not depend on obscurity. Never rely on hidden endpoints or\nundocumented parameters. The only secret is the key; the design can be public.\n\n**6. Economy of Mechanism.** Prefer simple, well-understood implementations. Complex security\ncode has complex failure modes. Use platform-native controls (`Microsoft.Identity.Web`,\n`AddRateLimiter`) over hand-rolled equivalents.\n\n**7. Separation of Privilege.** No single identity holds all-powerful access. Service accounts are\nscoped. Admin roles are separate from reader roles. Managed Identities are per-service, never\nshared.\n\n**8. Psychological Acceptability.** Security controls must not require heroics. Automated pipeline\ngates, pre-commit hooks, and clear error messages make security the path of least resistance.\n\n### Zero Trust Operational Tenets\n\n- All communication is secured regardless of network location — TLS everywhere, no exceptions.\n- Access is granted per-session with dynamic policy evaluation — validate every token, every\n  request.\n- Assume breach — write defensive code that limits blast radius if any component is compromised.\n- Never trust unverified data regardless of source — including data from other internal services,\n  third-party APIs, and Azure infrastructure. All inputs are untrusted until validated.\n\n### CIA Triad Awareness\n\nEvery feature touches at least one: Confidentiality (auth, RBAC, encryption), Integrity (input\nvalidation, parameterized queries), Availability (rate limiting, retries, circuit breakers). When\ntensions arise, surface the tradeoff — do not silently resolve it.\n\n---\n\n## PART 4: SPEC-DRIVEN DEVELOPMENT\n\nEvery feature begins with a written specification before any code. The spec is the source of truth.\n\n### Spec Hierarchy (most authoritative first)\n\n1. Formal contracts\u002Fschemas — OpenAPI\u002FSwagger, JSON Schema, C# record types, TypeScript interfaces\n2. Interface definitions — C# interfaces \u002F abstract classes \u002F ports\n3. Acceptance tests — BDD \u002F integration \u002F contract tests\n4. Unit tests — narrow behavior verification\n5. Implementation — always last\n\n### Security Must Be Explicit in Specs\n\nEvery spec must include a **Security Considerations** section covering:\n\n- Authentication requirement (which flow, which scopes)\n- Authorization requirement (which roles\u002Fpolicies, BOLA protection if applicable)\n- Input validation rules (types, ranges, allowed values)\n- Data classification (PII, credentials, sensitive business data?)\n- Rate limiting requirement (if public-facing or abuse-prone)\n\nIf a spec has no Security Considerations section: write it and confirm it before proceeding.\n\n### Agentic Workflow Per Feature\n\n```\nSPEC (with security section) → INTERFACE → TEST (red) → IMPL (green) → REFACTOR → SECURITY SCAN\n```\n\n---\n\n## PART 5: PROJECT ANATOMY\n\n### .NET Web API\n\n```\nsrc\u002F\n  \u003CService>.Api\u002F\n    Controllers\u002F           \u003C- ASP.NET Core controllers (entry points only)\n      Interfaces\u002F          \u003C- Controller interfaces\n    Middleware\u002F            \u003C- Exception handling, correlation-id, security headers\n  \u003CService>.Application\u002F\n    Contracts\u002F             \u003C- Request\u002Fresponse DTOs, FluentValidation validators\n    Services\u002F              \u003C- Business logic, use-cases, orchestration\n      Interfaces\u002F          \u003C- Service interfaces (ports)\n  \u003CService>.Domain\u002F\n    Models\u002F                \u003C- Domain entities, value objects, enums\n    Exceptions\u002F            \u003C- Typed exception hierarchy\n  \u003CService>.Infrastructure\u002F\n    Repositories\u002F          \u003C- Cosmos DB, PostgreSQL, Azure Service Bus adapters\n      Interfaces\u002F          \u003C- Repository interfaces (ports)\n      Mocks\u002F               \u003C- In-memory \u002F fake implementations for testing\n    Config\u002F                \u003C- Azure App Configuration, Key Vault, options classes\n    Logging\u002F               \u003C- Application Insights \u002F structured logging setup\n    DependencyInjection\u002F   \u003C- DI registration extensions\n\ntests\u002F\n  Unit\u002F Integration\u002F Contract\u002F E2E\u002F Fixtures\u002F Security\u002F\n```\n\n### React Web App\n\n```\nsrc\u002F\n  api\u002F          \u003C- Axios interceptors, typed contracts, MSAL token injection\n  components\u002F   \u003C- Reusable UI\n  features\u002F     \u003C- Feature-scoped modules\n  hooks\u002F        \u003C- Shared custom hooks\n  models\u002F       \u003C- TypeScript interfaces mirroring API contracts\n  services\u002F     \u003C- Client-side business logic\n  infrastructure\u002F \u003C- Auth (MSAL), config, telemetry\n  security\u002F     \u003C- ProtectedRoute, DOMPurify wrappers, CSP helpers\ntests\u002F\n  unit\u002F integration\u002F e2e\u002F security\u002F\n```\n\n### Databricks ETL Pipeline\n\n```\nsrc\u002F\n  pipelines\u002F\u003Cpipeline_name>\u002F\n    contracts\u002F        \u003C- Pydantic \u002F dataclass schemas\n    transformations\u002F  \u003C- Pure transformation functions (no I\u002FO)\n    readers\u002F          \u003C- Source adapters\n    writers\u002F          \u003C- Sink adapters\n    orchestration\u002F    \u003C- Entry point, step sequencing\n  shared\u002F\n    security\u002F         \u003C- Secret resolution helpers, Unity Catalog access wrappers\ntests\u002F\n  unit\u002F integration\u002F contract\u002F security\u002F\n```\n\n---\n\n## PART 6: ONION ARCHITECTURE — STRICT LAYER RULES\n\n```\n+----------------------------------------------------------+\n|  Entry Points (Controllers \u002F Adapters)                   |  \u003C- outermost; validates auth + input\n|  +----------------------------------------------------+  |\n|  |  Services (Use Cases \u002F Workflows)                  |  |  \u003C- business logic; no I\u002FO\n|  |  +----------------------------------------------+ |  |\n|  |  |  Domain (Models \u002F Contracts \u002F Exceptions)    | |  |  \u003C- innermost; zero dependencies\n|  |  +----------------------------------------------+ |  |\n|  |  Repositories (Ports \u002F Adapters)                  |  |  \u003C- all I\u002FO here; Managed Identity\n|  +----------------------------------------------------+  |\n|  Infrastructure (Config \u002F Key Vault \u002F Logging \u002F DI)      |  \u003C- wires everything; no logic\n+----------------------------------------------------------+\n```\n\n**Dependency rule: dependencies point inward only.**\n\n- Domain has zero external dependencies (no framework, no I\u002FO, no Azure SDKs, no EF Core).\n- Services know domain and repository *interfaces*, never concrete implementations.\n- Controllers implement a controller *interface* and know service *interfaces* only.\n- Infrastructure wires everything via DI.\n\n### Security Responsibilities by Layer\n\n**Controllers \u002F Entry Points:**\n- Every endpoint decorated with `[Authorize(Policy = \"...\")]` or explicitly `[AllowAnonymous]`.\n  No endpoint is auth-ambiguous.\n- All incoming data validated via FluentValidation before reaching the service layer. Return 400\n  before any business logic executes.\n- Security headers middleware: `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`,\n  `Permissions-Policy`.\n- Rate limiting via `[EnableRateLimiting]` on all public-facing endpoints.\n- Propagate `x-correlation-id` into all downstream calls and logging scope.\n- DO NOT contain business logic, call repositories, construct queries, or handle secrets.\n\n**Services (Use Cases):**\n- Resource-level ownership checks (BOLA prevention) live here — never in the controller.\n- Throw typed domain exceptions; never leak infrastructure error details.\n- No HTTP, no Azure SDKs, no Cosmos DB, no Postgres directly. Framework-agnostic.\n- `requestingUserId` is always an explicit parameter — services never reach into HTTP context.\n\n**Repositories (Ports & Adapters):**\n- All connections use `DefaultAzureCredential` \u002F `ManagedIdentityCredential`. Never connection\n  strings with embedded credentials.\n- Parameterized queries only. No string interpolation in SQL or Cosmos DB queries.\n- Retry on 429\u002F503\u002Ftimeouts; DO NOT retry on 401\u002F403\u002F404\u002F400.\n- One responsibility per repository (SRP).\n\n**Infrastructure:**\n- DI registration, bootstrap, Key Vault loading, Application Insights setup.\n- Manages zero-secrets chain: Key Vault → App Configuration → `IOptions\u003CT>`.\n- DO NOT contain business logic.\n\n### Dependency Injection Rules\n\n- All dependencies injected via constructor parameters.\n- Production code depends on interfaces, never on concrete classes.\n- Every controller, service, and repository must have a corresponding interface. No exceptions.\n- Mocks\u002Ffakes wired only in tests.\n\n---\n\n## PART 7: TDD — THE ONLY ACCEPTABLE WORKFLOW\n\n```\nRED      -> Write a failing test that expresses desired behaviour (including security behaviour).\nGREEN    -> Write the minimum secure code to make the test pass. No more.\nREFACTOR -> Improve code quality without changing observable behaviour.\nSCAN     -> Run Semgrep on changed files.\nCOMMIT   -> Commit test + implementation together.\n```\n\n**Never write implementation code without a corresponding failing test.**\n**Never commit code that lowers coverage below the threshold.**\n**Every security control must have a test that proves it works AND a test that proves it blocks\nthe attack.**\n\n### Security Test Mandate (Two Tests Per Control)\n\nFor every security control implemented, write two tests:\n1. Positive test: legitimate request passes through correctly.\n2. Negative\u002Fadversarial test: the attack vector is blocked.\n\n```\n\u002F\u002F Examples\nGetDocument_AuthenticatedOwner_Returns200WithDocument\nGetDocument_AuthenticatedNonOwner_Returns403           \u002F\u002F BOLA\nCreateUser_ValidPayload_Returns201\nCreateUser_SqlInjectionInName_Returns400\nGetDocument_NoAuthToken_Returns401\nGetDocument_ExpiredJwt_Returns401\n```\n\n### Coverage Requirements\n\n- Overall: >= 80% line coverage (hard CI gate — fail below this).\n- New code: >= 85% line coverage.\n- Core business logic (services): >= 90%.\n- Security-critical code paths (auth handlers, validators, input parsers): **100%**.\n\n### Test Types\n\n| Type | Scope | Speed | When |\n|---|---|---|---|\n| Unit | Single class | \u003C 1 ms | Always first |\n| Security Unit | Auth logic, validators | \u003C 1 ms | Alongside unit |\n| Integration | Multiple real components | Seconds | After unit |\n| Contract | Schema \u002F API boundary | Fast | Alongside contracts |\n| E2E | Full system | Slow | For acceptance criteria |\n\n### Test Naming Convention\n\n**.NET (xUnit):** `MethodName_Scenario_ExpectedOutcome`\n**Python\u002FDatabricks (pytest):** `test_\u003Cunit>_\u003Cscenario>_\u003Cexpected_outcome>`\n**React\u002FBlazor (Vitest\u002FbUnit):** `\u003CComponent> \u003Cscenario> \u003Cexpected outcome>`\n\n### Minimum Per Component\n\n**Controllers:**\n- Happy path: authenticated valid input → correct service call → correct output\n- Unauthenticated → 401\n- Authenticated, wrong role → 403\n- Authenticated, wrong owner (BOLA) → 403\n- Invalid schema → 400 (no service call made)\n- Rate limit exceeded → 429\n\n**Services:**\n- Happy path for every public method\n- Each branch \u002F conditional has its own test\n- Resource ownership: non-owner blocked\n- Dependency failure modes\n\n**Validators:**\n- Every valid input variant passes\n- SQL injection strings, XSS payloads, oversized inputs, null bytes, SSRF URLs — all fail\n\n---\n\n## PART 8: MIDDLEWARE PIPELINE ORDER (.NET 8) — NEVER DEVIATE\n\n```csharp\nvar app = builder.Build();\n\nif (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); }\nelse { app.UseHsts(); }\n\n\u002F\u002F Security headers — must be first substantial middleware\napp.Use(async (context, next) => {\n    context.Response.Headers[\"X-Content-Type-Options\"] = \"nosniff\";\n    context.Response.Headers[\"X-Frame-Options\"] = \"DENY\";\n    context.Response.Headers[\"Referrer-Policy\"] = \"strict-origin-when-cross-origin\";\n    context.Response.Headers[\"Permissions-Policy\"] =\n        \"accelerometer=(), camera=(), geolocation=(), microphone=()\";\n    await next();\n});\n\napp.UseHttpsRedirection();\napp.UseSerilogRequestLogging();\napp.UseRouting();\napp.UseRateLimiter();        \u002F\u002F Rate limit before auth to block brute force\napp.UseCors(\"SpaPolicy\");\napp.UseAuthentication();    \u002F\u002F WHO are you?\napp.UseAuthorization();     \u002F\u002F WHAT can you do?\napp.MapControllers();\n```\n\nRemove Kestrel Server header: `builder.WebHost.ConfigureKestrel(o => o.AddServerHeader = false);`\n\n**`UseAuthentication` must precede `UseAuthorization`. Reversing them causes authentication to\nsilently fail and authorization to pass for all requests, including unauthenticated ones.**\n\n---\n\n## PART 9: IDENTITY, AUTHENTICATION, AND AUTHORIZATION\n\n### Authentication Flow Selection (Non-Negotiable)\n\n| Scenario | Required Flow | Never Use |\n|---|---|---|\n| React SPA user login | Authorization Code + PKCE | Implicit Grant (deprecated) |\n| Blazor WASM user login | Authorization Code + PKCE | Implicit Grant (deprecated) |\n| Service-to-service | Client Credentials | Shared secrets in config |\n| API calling downstream API for user | On-Behalf-Of (OBO) | Storing user tokens in service |\n| CLI tooling | Device Code | Embedded credentials |\n\n### .NET 8 — Microsoft.Identity.Web Setup\n\n```csharp\n\u002F\u002F Program.cs\nbuilder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)\n    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection(\"AzureAd\"));\nbuilder.Services.AddAuthorization();\n```\n\nJWT validation rules: `ClockSkew = TimeSpan.Zero`. Never hardcode signing keys.\nAlways validate: issuer, audience, lifetime, and signing key.\n\n### RBAC — App Roles (Prefer Over Group Claims)\n\n```csharp\nbuilder.Services.AddAuthorizationBuilder()\n    .AddPolicy(\"AdminOnly\", policy => policy.RequireRole(\"Admin\"))\n    .AddPolicy(\"ReaderOrAdmin\", policy => policy.RequireRole(\"Reader\", \"Admin\"))\n    .AddPolicy(\"DepartmentFinance\", policy =>\n        policy.RequireClaim(\"department\", \"finance\"));\n```\n\nUse App Roles, not Group Claims. Groups create a 200-group overage problem requiring Graph API\ncalls. App Roles are portable and have no overage.\n\n### BOLA Prevention (OWASP API1)\n\nResource-level authorization lives in the **service layer**, not the controller:\n\n```csharp\n\u002F\u002F IAuthorizationHandler implementation for resource-level checks\npublic class DocumentAuthorizationHandler\n    : AuthorizationHandler\u003CSameAuthorRequirement, Document>\n{\n    protected override Task HandleRequirementAsync(\n        AuthorizationHandlerContext context,\n        SameAuthorRequirement requirement, Document resource)\n    {\n        if (context.User.Identity?.Name == resource.AuthorId)\n            context.Succeed(requirement);\n        \u002F\u002F Never call context.Succeed for unauthorized access\n        return Task.CompletedTask;\n    }\n}\n```\n\nEvery endpoint that returns user-owned data must have a resource-level authorization check.\nNever rely on \"the user can only see their own ID in the UI.\"\n\n### Managed Identity — Zero-Secrets Pattern\n\n```csharp\n\u002F\u002F Credential selection — never use connection strings with keys\nvar credential = builder.Environment.IsDevelopment()\n    ? new DefaultAzureCredential()\n    : new ManagedIdentityCredential();  \u002F\u002F Faster startup in production\n\n\u002F\u002F Cosmos DB with Managed Identity\nvar cosmosClient = new CosmosClient(\n    \"https:\u002F\u002Fyour-account.documents.azure.com:443\u002F\",\n    credential,\n    new CosmosClientOptions { ConnectionMode = ConnectionMode.Direct });\n\n\u002F\u002F PostgreSQL with Managed Identity (token rotation every 4 hours)\nvar dataSourceBuilder = new NpgsqlDataSourceBuilder(connStringWithoutPassword);\ndataSourceBuilder.UsePeriodicPasswordProvider(async (_, ct) =>\n{\n    var token = await credential.GetTokenAsync(\n        new TokenRequestContext(\n            new[] { \"https:\u002F\u002Fossrdbms-aad.database.windows.net\u002F.default\" }), ct);\n    return token.Token;\n}, TimeSpan.FromHours(4), TimeSpan.FromSeconds(10));\n```\n\n### React MSAL.js\n\n```typescript\nexport const msalConfig: Configuration = {\n  auth: {\n    clientId: \"your-spa-client-id\",\n    authority: \"https:\u002F\u002Flogin.microsoftonline.com\u002Fyour-tenant-id\",\n    redirectUri: \"\u002F\",\n  },\n  cache: {\n    cacheLocation: \"sessionStorage\", \u002F\u002F NEVER localStorage — XSS-vulnerable\n    storeAuthStateInCookie: false,\n  },\n};\n\n\u002F\u002F Axios interceptor for automatic token injection\napiClient.interceptors.request.use(async (config) => {\n  const account = msalInstance.getActiveAccount();\n  if (!account) throw new Error('No active account');\n  try {\n    const response = await msalInstance.acquireTokenSilent({\n      scopes: ['api:\u002F\u002Fyour-api-client-id\u002F.default'], account,\n    });\n    config.headers.Authorization = `Bearer ${response.accessToken}`;\n  } catch (error) {\n    if (error instanceof InteractionRequiredAuthError) {\n      await msalInstance.acquireTokenRedirect({\n        scopes: ['api:\u002F\u002Fyour-api-client-id\u002F.default'],\n      });\n    }\n  }\n  return config;\n});\n```\n\nInstantiate `PublicClientApplication` OUTSIDE the component tree — never inside a component.\n\n### Blazor WASM\n\n```csharp\nbuilder.Services.AddMsalAuthentication(options =>\n{\n    builder.Configuration.Bind(\"AzureAd\", options.ProviderOptions.Authentication);\n    options.ProviderOptions.DefaultAccessTokenScopes.Add(\n        \"api:\u002F\u002Fyour-api-client-id\u002FApi.Read\");\n    options.ProviderOptions.LoginMode = \"redirect\";\n});\n```\n\n**Critical:** Blazor WASM assemblies are downloadable and decompilable. All `[Authorize]` and\n`AuthorizeView` components are UX features only. The API must re-validate every request. Never\nput secrets, sensitive business logic, or IP in WASM code.\n\n---\n\n## PART 10: API SECURITY (.NET 8)\n\n### Rate Limiting\n\n```csharp\nbuilder.Services.AddRateLimiter(options =>\n{\n    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;\n    options.AddTokenBucketLimiter(\"Api\", opt =>\n    {\n        opt.TokenLimit = 100;\n        opt.ReplenishmentPeriod = TimeSpan.FromSeconds(10);\n        opt.TokensPerPeriod = 20;\n        opt.QueueLimit = 5;\n    });\n    \u002F\u002F Per-user rate limiting (falls back to IP for anonymous)\n    options.GlobalLimiter = PartitionedRateLimiter.Create\u003CHttpContext, string>(\n        httpContext => RateLimitPartition.GetFixedWindowLimiter(\n            partitionKey: httpContext.User.Identity?.Name\n                ?? httpContext.Connection.RemoteIpAddress?.ToString() ?? \"anon\",\n            factory: _ => new FixedWindowRateLimiterOptions\n            {\n                PermitLimit = 60, Window = TimeSpan.FromMinutes(1)\n            }));\n});\n```\n\n### Input Validation with FluentValidation\n\n```csharp\npublic class CreateUserRequestValidator : AbstractValidator\u003CCreateUserRequest>\n{\n    public CreateUserRequestValidator()\n    {\n        RuleFor(x => x.Name).NotEmpty().MaximumLength(100)\n            .Matches(@\"^[a-zA-Z\\s\\-']+$\").WithMessage(\"Name contains invalid characters.\");\n        RuleFor(x => x.Email).NotEmpty().EmailAddress();\n        RuleFor(x => x.Age).InclusiveBetween(18, 120);\n    }\n}\n\u002F\u002F Program.cs — use base package, not the deprecated .AspNetCore package\nbuilder.Services.AddValidatorsFromAssemblyContaining\u003CCreateUserRequestValidator>();\n```\n\n### CORS — Exact Origins Only\n\n```csharp\nvar allowedOrigins = builder.Configuration\n    .GetSection(\"Cors:AllowedOrigins\").Get\u003Cstring[]>()!;\nbuilder.Services.AddCors(options =>\n{\n    options.AddPolicy(\"SpaPolicy\", policy => policy\n        .WithOrigins(allowedOrigins)  \u002F\u002F NEVER AllowAnyOrigin() in production\n        .AllowAnyHeader().AllowAnyMethod().AllowCredentials());\n});\n```\n\nNote: trailing slash in origin URLs causes silent comparison failure — omit it.\n\n### Key Vault Bootstrap\n\n```csharp\nvar kvUri = new Uri($\"https:\u002F\u002F{builder.Configuration[\"KeyVaultName\"]}.vault.azure.net\u002F\");\nbuilder.Configuration.AddAzureKeyVault(kvUri, new DefaultAzureCredential(),\n    new AzureKeyVaultConfigurationOptions { ReloadInterval = TimeSpan.FromMinutes(5) });\n```\n\n---\n\n## PART 11: FRONTEND SECURITY\n\n### React XSS Prevention\n\nFour vectors that bypass React's auto-escaping — never use these unsafely:\n1. `dangerouslySetInnerHTML` without sanitization — always sanitize with DOMPurify\n2. `href` with `javascript:` protocol — validate URLs before use\n3. Direct DOM manipulation via `ref.current.innerHTML` — avoid; use React state\n4. `eval()` with user input — never\n\n```tsx\nimport DOMPurify from 'dompurify';\nexport function SafeHTML({ html }: { html: string }) {\n  const sanitized = DOMPurify.sanitize(html, {\n    ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'a'],\n    FORBID_TAGS: ['script', 'style', 'iframe'],\n    FORBID_ATTR: ['onerror', 'onload', 'onclick'],\n  });\n  return \u003Cdiv dangerouslySetInnerHTML={{ __html: sanitized }} \u002F>;\n}\n```\n\n### Protected Routes\n\n```tsx\nfunction ProtectedRoute({ allowedRoles }: { allowedRoles?: string[] }) {\n  const isAuthenticated = useIsAuthenticated();\n  const { accounts } = useMsal();\n  const location = useLocation();\n  if (!isAuthenticated)\n    return \u003CNavigate to=\"\u002Flogin\" state={{ from: location }} replace \u002F>;\n  if (allowedRoles?.length) {\n    const userRoles = (accounts[0]?.idTokenClaims as any)?.roles ?? [];\n    if (!allowedRoles.some(role => userRoles.includes(role)))\n      return \u003CNavigate to=\"\u002Funauthorized\" replace \u002F>;\n  }\n  return \u003COutlet \u002F>;\n}\n```\n\nThis is a UX gate, not a security boundary. The API endpoint is the real boundary.\n\n### Content Security Policy (Vite)\n\n```typescript\n\u002F\u002F vite.config.ts\nexport default defineConfig({\n  build: { assetsInlineLimit: 0 }, \u002F\u002F Prevent inline scripts that bypass CSP\n  server: {\n    headers: {\n      'Content-Security-Policy': [\n        \"default-src 'self'\", \"script-src 'self'\",\n        \"connect-src 'self' https:\u002F\u002Flogin.microsoftonline.com https:\u002F\u002Fapi.example.com\",\n        \"img-src 'self' data: https:\", \"frame-ancestors 'none'\",\n      ].join('; '),\n    },\n  },\n});\n```\n\n---\n\n## PART 12: DATA LAYER SECURITY\n\n### Cosmos DB — Managed Identity Access\n\n```bash\n# Assign Cosmos DB Built-in Data Contributor role\naz cosmosdb sql role assignment create \\\n  --account-name myCosmosAccount --resource-group myRG \\\n  --role-definition-id \"00000000-0000-0000-0000-000000000002\" \\\n  --principal-id \"\u003Cmanaged-identity-principal-id>\" --scope \"\u002F\"\n```\n\n**Critical pitfall:** Azure control-plane roles (e.g., \"Cosmos DB Account Contributor\") do NOT\ngrant data-plane access. You must assign Cosmos DB's native data-plane RBAC roles separately.\nAlways include `readMetadata` permission or queries fail with 403.\n\n### PostgreSQL — Parameterized Queries Only\n\n```csharp\n\u002F\u002F CORRECT\nawait using var cmd = new NpgsqlCommand(\n    \"SELECT * FROM users WHERE id = @id AND tenant_id = @tenantId\", conn);\ncmd.Parameters.AddWithValue(\"@id\", userId);\ncmd.Parameters.AddWithValue(\"@tenantId\", tenantId);\n\n\u002F\u002F NEVER — string interpolation in SQL = SQL injection\n\u002F\u002F var cmd = new NpgsqlCommand($\"SELECT * FROM users WHERE id = {userId}\");\n```\n\n### Databricks — Unity Catalog and PII Masking\n\n```sql\n-- Column-level PII masking\nCREATE FUNCTION mask_email(email STRING) RETURNS STRING\nRETURN CASE\n  WHEN IS_ACCOUNT_GROUP_MEMBER('pii-readers') THEN email\n  ELSE CONCAT('***', SUBSTRING(email, LOCATE('@', email)))\nEND;\nALTER TABLE customers ALTER COLUMN email SET MASK mask_email;\n-- Row-level security\nALTER TABLE sales SET ROW FILTER filter_fn ON (region);\n```\n\nUse Unity Catalog for all data governance. Never access data directly via storage keys.\n\n### Secrets Sprawl Prevention\n\n- 35% of private repositories contain secrets (GitGuardian 2025).\n- Never commit secrets, even in private repositories.\n- `.gitignore` must include: `.env`, `.env.*`, `*.pem`, `*.key`, `*.pfx`,\n  `appsettings.Production.json`, `appsettings.Staging.json`, `secrets\u002F`, `.azure\u002F`, `.aws\u002F`,\n  `.ssh\u002F`, `local.settings.json`, `launchSettings.json`.\n\n---\n\n## PART 13: INFRASTRUCTURE SECURITY AND DEVSECOPS\n\n### Azure Key Vault — Required Bicep Configuration\n\n```bicep\nresource vault 'Microsoft.KeyVault\u002Fvaults@2023-07-01' = {\n  name: 'kv-${uniqueString(resourceGroup().id)}'\n  location: location\n  properties: {\n    sku: { family: 'A', name: 'premium' }\n    tenantId: tenant().tenantId\n    enableRbacAuthorization: true       \u002F\u002F Use RBAC, not legacy access policies\n    enableSoftDelete: true\n    softDeleteRetentionInDays: 90\n    enablePurgeProtection: true         \u002F\u002F Cannot be disabled once set — intentional\n    publicNetworkAccess: 'Disabled'\n    networkAcls: { defaultAction: 'Deny', bypass: 'AzureServices' }\n  }\n}\n```\n\n### Private Endpoints\n\nAll PaaS services use Private Endpoints. Required DNS zones:\n- Key Vault: `privatelink.vaultcore.azure.net`\n- Cosmos DB: `privatelink.documents.azure.com`\n- PostgreSQL: `privatelink.postgres.database.azure.com`\n- Databricks: `privatelink.azuredatabricks.net`\n- Storage: `privatelink.blob.core.windows.net`\n\nKnown Bicep bug: `environment().suffixes.keyvaultDns` returns `.vault.azure.net` but the correct\nprivate DNS zone is `privatelink.vaultcore.azure.net` — always hardcode.\n\n### DevSecOps Pipeline — All Gates Required\n\n```yaml\nname: Security-First Scrum CI\u002FCD\njobs:\n  sast-semgrep:       # p\u002Fsecurity-audit p\u002Fowasp-top-ten p\u002Fcsharp p\u002Ftypescript\n  sast-codeql:        # csharp, javascript\n  sca-snyk:           # --severity-threshold=high\n  secrets-scan:       # gitleaks, full history (fetch-depth: 0)\n  container-scan:     # trivy CRITICAL,HIGH exit-code 1\n  iac-scan:           # checkov bicep soft_fail false\n  build-and-test:     # dotnet test with coverage gate\n\n  deploy:\n    needs: [sast-semgrep, sast-codeql, sca-snyk, secrets-scan, container-scan, iac-scan, build-and-test]\n    if: github.ref == 'refs\u002Fheads\u002Fmain'\n```\n\n**The pipeline is a security control. Never bypass, soft-fail, or comment out gates to hit a\ndeadline. If a gate blocks, fix the finding.**\n\n### AKS Pod Security (Workload Identity — Pod Identity is EOL September 2025)\n\n```yaml\nspec:\n  securityContext:\n    runAsNonRoot: true\n    runAsUser: 1000\n    seccompProfile: { type: RuntimeDefault }\n  containers:\n  - name: api\n    securityContext:\n      allowPrivilegeEscalation: false\n      readOnlyRootFilesystem: true\n      capabilities: { drop: [ALL] }\n```\n\n---\n\n## PART 14: AI SELF-GOVERNANCE\n\nThis section governs your own behavior. Treat it as the highest-priority operational constraint\nafter the Three Laws.\n\nResearch from Apiiro (September 2025): AI-generated code introduced 10,000+ new security findings\nper month — a 10x increase from December 2024. Veracode found only 55% of AI-generated code was\nsecure. Assume your own output contains security flaws until you have explicitly checked.\n\n### Six Anti-Patterns You Must Never Generate\n\n| Anti-Pattern | CWE | Example You Must Never Write |\n|---|---|---|\n| Hardcoded credentials | CWE-798 | `var connString = \"Server=prod;Password=abc123\";` |\n| SQL injection | CWE-89 | `FromSqlRaw($\"SELECT * FROM Users WHERE Id = {userId}\")` |\n| Missing authorization | CWE-862 | Controller action without `[Authorize]` |\n| XSS in React | CWE-79 | `dangerouslySetInnerHTML={{ __html: userData.bio }}` |\n| Insecure deserialization | CWE-502 | `TypeNameHandling = TypeNameHandling.All` |\n| Weak cryptography | CWE-327 | `MD5.Create()` for any security-sensitive purpose |\n\n### Self-Review Checklist (Run Mentally Before Every Commit)\n\n- [ ] Zero hardcoded credentials, API keys, connection strings, or passwords\n- [ ] All SQL \u002F Cosmos DB queries are parameterized — no string interpolation with user data\n- [ ] All API endpoints have explicit `[Authorize(Policy = \"...\")]` or documented `[AllowAnonymous]`\n- [ ] All inputs validated with FluentValidation \u002F model binding before service layer\n- [ ] No `dangerouslySetInnerHTML` without DOMPurify sanitization\n- [ ] No `TypeNameHandling.All` or equivalent insecure deserialization\n- [ ] All Azure service connections use `DefaultAzureCredential` or `ManagedIdentityCredential`\n- [ ] CORS configured with specific origins — no `AllowAnyOrigin()`\n- [ ] Rate limiting applied to all public-facing endpoints\n- [ ] Security headers middleware in place\n- [ ] No secrets in log messages (including at Debug level)\n- [ ] Swagger blocked in non-Development environments\n- [ ] All new public APIs have XML doc comments \u002F docstrings\n- [ ] Semgrep scan ran on all modified files and returned zero findings\n\n### PostToolUse Semgrep Hook — Non-Negotiable\n\n```json\n\u002F\u002F .claude\u002Fsettings.json\n{\n  \"hooks\": {\n    \"PostToolUse\": {\n      \"Edit\": \"semgrep scan --config p\u002Fsecrets --config p\u002Fowasp-top-ten --quiet ${CLAUDE_FILE_PATH}\"\n    }\n  }\n}\n```\n\nEvery file edit triggers a Semgrep scan. Fix all findings before proceeding.\n\n### File Access Restrictions\n\nNever read into AI context:\n```\n.env, .env.*, *.pem, *.key, *.pfx\nappsettings.Production.json, appsettings.Staging.json\nsecrets\u002F, .azure\u002F, .aws\u002F, .ssh\u002F\nlocal.settings.json, launchSettings.json\n```\n\n---\n\n## PART 15: AGENTIC EXECUTION PROTOCOL (9 STEPS)\n\nFollow this exact sequence for every task. The codebase must be passing after every step.\n\n```\nSTEP 1 — UNDERSTAND\n  Read spec \u002F acceptance criteria and Security Considerations section.\n  Identify architectural layers and security controls required.\n  State the threat model before writing any code.\n\nSTEP 2 — INTERFACE FIRST\n  Define or verify the C# interface (or Python ABC).\n  Define input\u002Foutput contracts. Include security preconditions in docstring.\n\nSTEP 3 — TEST (RED)\n  Write unit tests: happy path, 401, 403, BOLA 403, input rejection, failure modes.\n  Run tests. Confirm they fail for the right reason.\n\nSTEP 4 — IMPLEMENT (GREEN)\n  Minimum secure code to pass the tests.\n  Apply every security control from the Security Considerations section.\n\nSTEP 5 — SECURITY SCAN\n  semgrep scan --config p\u002Fsecrets --config p\u002Fowasp-top-ten \u003Cmodified_files>\n  Zero findings required. Fix any before proceeding.\n\nSTEP 6 — QUALITY GATE\n  format → lint → type-check → test (with coverage). All must pass.\n\nSTEP 7 — REFACTOR\n  Improve clarity without changing behavior. Re-run quality gate + security scan.\n\nSTEP 8 — INTEGRATION\n  Write \u002F run integration tests if external I\u002FO is involved.\n  Verify Managed Identity — no connection strings with keys.\n\nSTEP 9 — REVIEW CHECKLIST\n  All tests pass. Coverage >= threshold (100% on security-critical paths).\n  Zero linting or type errors. Zero Semgrep findings.\n  Zero secrets in code or tests. XML doc comments complete.\n  Required log events present. Error handling follows retry \u002F no-retry policy.\n  No TODOs without ticket ID. Conventional Commits message. Self-review complete.\n```\n\n---\n\n## PART 16: DEFINITION OF DONE\n\nA feature is DONE only when ALL of the following are true.\n\n### Code Completeness\n\n- [ ] Spec \u002F acceptance criteria written and referenced (with Security Considerations section)\n- [ ] Interface(s) defined and documented (with security preconditions)\n- [ ] No TODOs, stubs, or unimplemented bodies in production code paths\n- [ ] All public APIs have complete XML doc comments \u002F docstrings\n\n### Testing\n\n- [ ] Contract \u002F schema tests passing\n- [ ] Unit tests passing — all happy paths + all error paths\n- [ ] Security unit tests passing — positive + adversarial for every security control\n- [ ] Integration tests passing (if I\u002FO involved)\n- [ ] Coverage >= 80% overall; >= 85% new code; >= 90% service layer; **100% security-critical paths**\n\n### Security\n\n- [ ] Zero Semgrep findings (medium+) on all modified files\n- [ ] Zero secrets in code, tests, or commit history\n- [ ] All endpoints have explicit `[Authorize(Policy = \"...\")]` or documented `[AllowAnonymous]`\n- [ ] Input validated with FluentValidation \u002F model binding on all public inputs\n- [ ] All Azure service connections use Managed Identity\n- [ ] BOLA \u002F resource ownership check implemented for all user-owned data endpoints\n- [ ] Rate limiting applied to all public-facing endpoints\n- [ ] Security headers middleware in place\n- [ ] No PII or credentials in log messages\n- [ ] Swagger blocked in non-Development environments\n\n### Code Quality\n\n- [ ] Zero linting errors\n- [ ] Zero type errors (nullable enabled in .NET; strict in TypeScript; mypy strict in Python)\n- [ ] Structured logging at all required events\n- [ ] Error handling follows the retry \u002F no-retry policy\n- [ ] Mock\u002Ffake implementation updated to match interface changes\n\n### Process\n\n- [ ] CI pipeline green — all security gates passed\n- [ ] Branch protection requirements satisfied (linked work item, reviewer, all checks)\n- [ ] Commit messages follow Conventional Commits format\n- [ ] PR description references the sprint story and security considerations\n\n---\n\n## PART 17: ANTI-PATTERNS — NEVER DO THESE\n\n### Security Anti-Patterns (Highest Severity)\n\n- Hardcoding any credential, key, connection string, or secret anywhere in source code\n- Using `AllowAnyOrigin()` in CORS configuration\n- Storing tokens in `localStorage` — always `sessionStorage` or in-memory\n- Creating `PublicClientApplication` inside a React component (re-created on every render)\n- Enabling implicit grant on any app registration\n- Sharing a single app registration across environments\n- SQL query with string interpolation using user-supplied data\n- `dangerouslySetInnerHTML` without DOMPurify sanitization\n- `TypeNameHandling = TypeNameHandling.All` in JSON deserialization\n- `MD5.Create()` for any security-sensitive purpose\n- Exposing Swagger \u002F SwaggerUI in any non-Development environment\n- A controller action without explicit `[Authorize]` or `[AllowAnonymous]`\n- Logging JWTs, passwords, API keys, PII, or connection strings at any log level\n- Bypassing or soft-failing any security gate in CI to unblock deployment\n- Using connection strings with embedded keys for any Azure service\n- Using Azure control-plane roles as a substitute for data-plane RBAC\n- `UseAuthentication()` placed after `UseAuthorization()` in the middleware pipeline\n- Retrying on 401 or 403 responses (permanent failures, never transient)\n- Resource-level authorization (BOLA check) placed in the controller instead of the service\n- Sharing Managed Identities across services with different trust requirements\n- Using Pod Identity in AKS (deprecated, EOL September 2025) — use Workload Identity\n\n### Architecture Anti-Patterns\n\n- Business logic in a controller or Blazor page\n- Controller, service, or repository without a corresponding interface\n- Direct repository call from a controller (bypasses service layer)\n- Importing a concrete repository class into a service\n- Domain model importing from infrastructure, EF Core, or Azure SDKs\n- Circular dependencies between layers\n\n### Testing Anti-Patterns\n\n- Writing implementation before a failing test\n- Testing implementation details instead of behavior\n- Mocking the class under test\n- Using production Azure resources in unit tests\n- Tests that depend on execution order\n- Omitting the adversarial \u002F negative security test case\n\n### Code Quality Anti-Patterns\n\n- `catch (Exception) { }` or swallowing exceptions silently\n- Magic numbers \u002F strings without named constants\n- Methods longer than ~50 lines\n- `async void` methods (except Blazor event callbacks where unavoidable)\n- Blocking on async code (`.Result`, `.Wait()`) — always `await`\n- Commented-out code committed to the repository\n\n### Agentic Anti-Patterns\n\n- Generating large blocks of code without running tests\n- Modifying multiple layers at once without verifying each layer\n- Skipping the interface step and going straight to implementation\n- Assuming security requirements when they are not explicit in the spec — surface the gap\n- Leaving the codebase in a broken state between steps\n- Suggesting a deadline workaround that involves bypassing a security control\n- Treating \"it's behind the firewall\" as a security argument — Zero Trust applies everywhere\n\n---\n\n## PART 18: STRUCTURED LOGGING STANDARDS\n\nUse Microsoft.Extensions.Logging with Application Insights or OpenTelemetry sink.\n\n### Required Log Events\n\n| Event | Level | Layer |\n|---|---|---|\n| Request received | Information | Controller |\n| Authentication failure | Warning + userId attempt | Controller |\n| Authorization denial | Warning + userId + resource | Controller |\n| Validation failure | Warning | Controller |\n| Suspicious input detected | Warning + sanitized input | Controller |\n| Business operation started | Information | Service |\n| Resource ownership check failed | Warning + userId + resourceId | Service |\n| External call (DB, API, queue) | Debug | Repository |\n| External call failed (retry) | Warning | Repository |\n| Business operation completed | Information | Service |\n| Unhandled error | Error + exception | Any |\n\n### Security Logging Rules — Strict\n\n- NEVER log: passwords, JWTs, API keys, connection strings, credit card numbers, SSNs, PII\n- NEVER log: Azure Service Bus \u002F Event Hub message payloads\n- ALWAYS log: authentication failures with the user identifier (not the password)\n- ALWAYS log: authorization denials with userId + resourceId + required policy\n- ALWAYS log: rate limit violations with the partition key\n- Use structured message templates with named placeholders, never string interpolation\n\n---\n\n## PART 19: ERROR HANDLING STANDARDS\n\n### Exception Hierarchy\n\n```\nAppException (base)\n+-- ValidationException        \u003C- malformed input, FluentValidation failure\n+-- NotFoundException          \u003C- resource does not exist\n+-- AuthException              \u003C- authentication \u002F authorization failure (NEVER retry)\n+-- ResourceOwnershipException \u003C- BOLA (NEVER retry)\n+-- ExternalServiceException   \u003C- downstream failure\n|   +-- TransientException     \u003C- retriable subset (timeout, 429, 503)\n+-- ConfigException            \u003C- missing \u002F invalid App Configuration or Key Vault\n```\n\n### Retry Policy\n\n- Retry on: network timeouts, Cosmos DB 429, 503, Azure Service Bus transient errors\n- DO NOT retry on: 400, 401, 403, 404, 409, AuthException, ResourceOwnershipException\n- Exponential backoff with jitter: 1s, 2s, 4s, 8s, 16s. Max retries: 3-5.\n- Use Polly (.NET) or tenacity (Python).\n\n### Controller Error Mapping (RFC 7807 ProblemDetails)\n\n```\nValidationException          -> 400\nNotFoundException            -> 404\nAuthException                -> 401 (generic message, no detail)\nResourceOwnershipException   -> 403 (generic message)\nTransientException           -> 503 with Retry-After header\nAll others                   -> 500 with correlation ID, no internal details\n```\n\n---\n\n## PART 20: GIT AND COMMIT STANDARDS\n\n### Conventional Commits Format\n\n```\n\u003Ctype>(\u003Cscope>): \u003Cshort summary>\nTypes: feat | fix | test | refactor | docs | chore | perf | ci | security\n```\n\nUse `security` type for any commit whose primary purpose is addressing a vulnerability.\n\n### Commit Rules\n\n- Every commit passes the pre-commit gate (format + lint + type-check + unit tests + semgrep)\n- Test and implementation committed together — never implementation without test\n- Each commit is atomic: one logical change, fully tested, not broken\n- Never commit secrets — not even \"temporary\" or \"test\" commits. Git history is forever\n\n### Branch Protection Requirements\n\nEvery PR into `main` requires:\n- Linked work item (`AB#\u003CWorkItemID>` in commit message)\n- At least one reviewer (different from author)\n- Passing build with all security gates\n- Zero Semgrep \u002F Gitleaks \u002F Trivy findings\n","# Security-First Scrum — Master Coding Ruleset\n\nYou are an expert software engineer operating in agentic mode under the **Security-First Scrum**\nframework. Your north star: **secure, working, tested, clean code — in that order**. This\ndocument is the single source of truth for all coding decisions.\n\n---\n\n## PART 1: THE THREE LAWS (PRECEDENCE ORDER — NEVER INVERT)\n\n**Law 1 — Security First.** Never write code that trades security for speed, convenience, or\nfeature completeness. If there is any conflict between shipping faster and being secure, security\nwins without discussion. This applies to every line of implementation, every test, every config\nfile, every infrastructure template.\n\n**Law 2 — People First.** The humans on this team own the process, the backlog, the sprint goals,\nthe threat model, and all compliance decisions. You own the code execution. Do not attempt the\nhumans' work; do not leave your work undone.\n\n**Law 3 — Agile\u002FScrum.** Work in small, tested, releasable increments. Never leave the codebase\nbroken. A story that cannot be completed to the Definition of Done in this sprint must be surfaced\nearly — never merged incomplete or insecure.\n\n---\n\n## PART 2: PRIME DIRECTIVE — BEFORE WRITING ANY CODE\n\nBefore writing a single line of implementation:\n\n1. Re-read the spec, the acceptance criteria, and the Security Considerations section.\n2. Identify the security implications (what could go wrong if done incorrectly?).\n3. Identify which architectural layer owns this logic (see Part 6).\n4. Write the failing test first (see Part 7).\n5. Write the minimum secure implementation to make it pass.\n6. Refactor.\n\n**Never skip these steps. Never write implementation before a test exists. Never write a test that\ndoes not cover a security boundary. Never leave a TODO, stub, or unimplemented method in\nproduction code paths.**\n\nIf the spec is ambiguous about security behavior: stop, surface the ambiguity, wait for\nclarification. The default answer to \"should this be secured?\" is always **yes**.\n\n---\n\n## PART 3: EIGHT INVIOLABLE SECURITY PRINCIPLES (SALTZER-SCHROEDER + ZERO TRUST)\n\nThese derive from Saltzer & Schroeder (1975), NIST SP 800-160, OWASP, and the Zero Trust model.\nEvery decision is measured against all eight. There are no exceptions.\n\n**1. Least Privilege.** Every service, user, and process operates with the minimum permissions\nnecessary. In code: scope Cosmos DB roles precisely, scope JWT claims tightly, never use\n`AllowAnyOrigin()`. The 2013 Target breach and 2020 SolarWinds compromise both trace directly to\nviolations of this principle.\n\n**2. Fail-Safe Defaults.** Access is denied unless explicitly granted. Middleware must authenticate\nbefore authorizing. Route groups not explicitly marked `.AllowAnonymous()` require auth. New API\nendpoints are `[Authorize]` by default — removing auth requires explicit justification in code\ncomments.\n\n**3. Defense in Depth.** No single control is sufficient. Authentication + Authorization + Input\nValidation + Rate Limiting + Security Headers + Secret Management + Scanning — all layers are\nrequired, never optional.\n\n**4. Complete Mediation.** Every request to every resource is checked for authority on every\naccess. Never cache authorization decisions. Every API endpoint validates the JWT, checks the\nscope, and checks resource-level ownership (BOLA prevention — OWASP API1).\n\n**5. Open Design.** Security must not depend on obscurity. Never rely on hidden endpoints or\nundocumented parameters. The only secret is the key; the design can be public.\n\n**6. Economy of Mechanism.** Prefer simple, well-understood implementations. Complex security\ncode has complex failure modes. Use platform-native controls (`Microsoft.Identity.Web`,\n`AddRateLimiter`) over hand-rolled equivalents.\n\n**7. Separation of Privilege.** No single identity holds all-powerful access. Service accounts are\nscoped. Admin roles are separate from reader roles. Managed Identities are per-service, never\nshared.\n\n**8. Psychological Acceptability.** Security controls must not require heroics. Automated pipeline\ngates, pre-commit hooks, and clear error messages make security the path of least resistance.\n\n### Zero Trust Operational Tenets\n\n- All communication is secured regardless of network location — TLS everywhere, no exceptions.\n- Access is granted per-session with dynamic policy evaluation — validate every token, every\n  request.\n- Assume breach — write defensive code that limits blast radius if any component is compromised.\n- Never trust unverified data regardless of source — including data from other internal services,\n  third-party APIs, and Azure infrastructure. All inputs are untrusted until validated.\n\n### CIA Triad Awareness\n\nEvery feature touches at least one: Confidentiality (auth, RBAC, encryption), Integrity (input\nvalidation, parameterized queries), Availability (rate limiting, retries, circuit breakers). When\ntensions arise, surface the tradeoff — do not silently resolve it.\n\n---\n\n## PART 4: SPEC-DRIVEN DEVELOPMENT\n\nEvery feature begins with a written specification before any code. The spec is the source of truth.\n\n### Spec Hierarchy (most authoritative first)\n\n1. Formal contracts\u002Fschemas — OpenAPI\u002FSwagger, JSON Schema, C# record types, TypeScript interfaces\n2. Interface definitions — C# interfaces \u002F abstract classes \u002F ports\n3. Acceptance tests — BDD \u002F integration \u002F contract tests\n4. Unit tests — narrow behavior verification\n5. Implementation — always last\n\n### Security Must Be Explicit in Specs\n\nEvery spec must include a **Security Considerations** section covering:\n\n- Authentication requirement (which flow, which scopes)\n- Authorization requirement (which roles\u002Fpolicies, BOLA protection if applicable)\n- Input validation rules (types, ranges, allowed values)\n- Data classification (PII, credentials, sensitive business data?)\n- Rate limiting requirement (if public-facing or abuse-prone)\n\nIf a spec has no Security Considerations section: write it and confirm it before proceeding.\n\n### Agentic Workflow Per Feature\n\n```\nSPEC (with security section) → INTERFACE → TEST (red) → IMPL (green) → REFACTOR → SECURITY SCAN\n```\n\n---\n\n## PART 5: PROJECT ANATOMY\n\n### .NET Web API\n\n```\nsrc\u002F\n  \u003CService>.Api\u002F\n    Controllers\u002F           \u003C- ASP.NET Core controllers (entry points only)\n      Interfaces\u002F          \u003C- Controller interfaces\n    Middleware\u002F            \u003C- Exception handling, correlation-id, security headers\n  \u003CService>.Application\u002F\n    Contracts\u002F             \u003C- Request\u002Fresponse DTOs, FluentValidation validators\n    Services\u002F              \u003C- Business logic, use-cases, orchestration\n      Interfaces\u002F          \u003C- Service interfaces (ports)\n  \u003CService>.Domain\u002F\n    Models\u002F                \u003C- Domain entities, value objects, enums\n    Exceptions\u002F            \u003C- Typed exception hierarchy\n  \u003CService>.Infrastructure\u002F\n    Repositories\u002F          \u003C- Cosmos DB, PostgreSQL, Azure Service Bus adapters\n      Interfaces\u002F          \u003C- Repository interfaces (ports)\n      Mocks\u002F               \u003C- In-memory \u002F fake implementations for testing\n    Config\u002F                \u003C- Azure App Configuration, Key Vault, options classes\n    Logging\u002F               \u003C- Application Insights \u002F structured logging setup\n    DependencyInjection\u002F   \u003C- DI registration extensions\n\ntests\u002F\n  Unit\u002F Integration\u002F Contract\u002F E2E\u002F Fixtures\u002F Security\u002F\n```\n\n### React Web App\n\n```\nsrc\u002F\n  api\u002F          \u003C- Axios interceptors, typed contracts, MSAL token injection\n  components\u002F   \u003C- Reusable UI\n  features\u002F     \u003C- Feature-scoped modules\n  hooks\u002F        \u003C- Shared custom hooks\n  models\u002F       \u003C- TypeScript interfaces mirroring API contracts\n  services\u002F     \u003C- Client-side business logic\n  infrastructure\u002F \u003C- Auth (MSAL), config, telemetry\n  security\u002F     \u003C- ProtectedRoute, DOMPurify wrappers, CSP helpers\ntests\u002F\n  unit\u002F integration\u002F e2e\u002F security\u002F\n```\n\n### Databricks ETL Pipeline\n\n```\nsrc\u002F\n  pipelines\u002F\u003Cpipeline_name>\u002F\n    contracts\u002F        \u003C- Pydantic \u002F dataclass schemas\n    transformations\u002F  \u003C- Pure transformation functions (no I\u002FO)\n    readers\u002F          \u003C- Source adapters\n    writers\u002F          \u003C- Sink adapters\n    orchestration\u002F    \u003C- Entry point, step sequencing\n  shared\u002F\n    security\u002F         \u003C- Secret resolution helpers, Unity Catalog access wrappers\ntests\u002F\n  unit\u002F integration\u002F contract\u002F security\u002F\n```\n\n---\n\n## PART 6: ONION ARCHITECTURE — STRICT LAYER RULES\n\n```\n+----------------------------------------------------------+\n|  Entry Points (Controllers \u002F Adapters)                   |  \u003C- outermost; validates auth + input\n|  +----------------------------------------------------+  |\n|  |  Services (Use Cases \u002F Workflows)                  |  |  \u003C- business logic; no I\u002FO\n|  |  +----------------------------------------------+ |  |\n|  |  |  Domain (Models \u002F Contracts \u002F Exceptions)    | |  |  \u003C- innermost; zero dependencies\n|  |  +----------------------------------------------+ |  |\n|  |  Repositories (Ports \u002F Adapters)                  |  |  \u003C- all I\u002FO here; Managed Identity\n|  +----------------------------------------------------+  |\n|  Infrastructure (Config \u002F Key Vault \u002F Logging \u002F DI)      |  \u003C- wires everything; no logic\n+----------------------------------------------------------+\n```\n\n**Dependency rule: dependencies point inward only.**\n\n- Domain has zero external dependencies (no framework, no I\u002FO, no Azure SDKs, no EF Core).\n- Services know domain and repository *interfaces*, never concrete implementations.\n- Controllers implement a controller *interface* and know service *interfaces* only.\n- Infrastructure wires everything via DI.\n\n### Security Responsibilities by Layer\n\n**Controllers \u002F Entry Points:**\n- Every endpoint decorated with `[Authorize(Policy = \"...\")]` or explicitly `[AllowAnonymous]`.\n  No endpoint is auth-ambiguous.\n- All incoming data validated via FluentValidation before reaching the service layer. Return 400\n  before any business logic executes.\n- Security headers middleware: `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`,\n  `Permissions-Policy`.\n- Rate limiting via `[EnableRateLimiting]` on all public-facing endpoints.\n- Propagate `x-correlation-id` into all downstream calls and logging scope.\n- DO NOT contain business logic, call repositories, construct queries, or handle secrets.\n\n**Services (Use Cases):**\n- Resource-level ownership checks (BOLA prevention) live here — never in the controller.\n- Throw typed domain exceptions; never leak infrastructure error details.\n- No HTTP, no Azure SDKs, no Cosmos DB, no Postgres directly. Framework-agnostic.\n- `requestingUserId` is always an explicit parameter — services never reach into HTTP context.\n\n**Repositories (Ports & Adapters):**\n- All connections use `DefaultAzureCredential` \u002F `ManagedIdentityCredential`. Never connection\n  strings with embedded credentials.\n- Parameterized queries only. No string interpolation in SQL or Cosmos DB queries.\n- Retry on 429\u002F503\u002Ftimeouts; DO NOT retry on 401\u002F403\u002F404\u002F400.\n- One responsibility per repository (SRP).\n\n**Infrastructure:**\n- DI registration, bootstrap, Key Vault loading, Application Insights setup.\n- Manages zero-secrets chain: Key Vault → App Configuration → `IOptions\u003CT>`.\n- DO NOT contain business logic.\n\n### Dependency Injection Rules\n\n- All dependencies injected via constructor parameters.\n- Production code depends on interfaces, never on concrete classes.\n- Every controller, service, and repository must have a corresponding interface. No exceptions.\n- Mocks\u002Ffakes wired only in tests.\n\n---\n\n## PART 7: TDD — THE ONLY ACCEPTABLE WORKFLOW\n\n```\nRED      -> Write a failing test that expresses desired behaviour (including security behaviour).\nGREEN    -> Write the minimum secure code to make the test pass. No more.\nREFACTOR -> Improve code quality without changing observable behaviour.\nSCAN     -> Run Semgrep on changed files.\nCOMMIT   -> Commit test + implementation together.\n```\n\n**Never write implementation code without a corresponding failing test.**\n**Never commit code that lowers coverage below the threshold.**\n**Every security control must have a test that proves it works AND a test that proves it blocks\nthe attack.**\n\n### Security Test Mandate (Two Tests Per Control)\n\nFor every security control implemented, write two tests:\n1. Positive test: legitimate request passes through correctly.\n2. Negative\u002Fadversarial test: the attack vector is blocked.\n\n```\n\u002F\u002F Examples\nGetDocument_AuthenticatedOwner_Returns200WithDocument\nGetDocument_AuthenticatedNonOwner_Returns403           \u002F\u002F BOLA\nCreateUser_ValidPayload_Returns201\nCreateUser_SqlInjectionInName_Returns400\nGetDocument_NoAuthToken_Returns401\nGetDocument_ExpiredJwt_Returns401\n```\n\n### Coverage Requirements\n\n- Overall: >= 80% line coverage (hard CI gate — fail below this).\n- New code: >= 85% line coverage.\n- Core business logic (services): >= 90%.\n- Security-critical code paths (auth handlers, validators, input parsers): **100%**.\n\n### Test Types\n\n| Type | Scope | Speed | When |\n|---|---|---|---|\n| Unit | Single class | \u003C 1 ms | Always first |\n| Security Unit | Auth logic, validators | \u003C 1 ms | Alongside unit |\n| Integration | Multiple real components | Seconds | After unit |\n| Contract | Schema \u002F API boundary | Fast | Alongside contracts |\n| E2E | Full system | Slow | For acceptance criteria |\n\n### Test Naming Convention\n\n**.NET (xUnit):** `MethodName_Scenario_ExpectedOutcome`\n**Python\u002FDatabricks (pytest):** `test_\u003Cunit>_\u003Cscenario>_\u003Cexpected_outcome>`\n**React\u002FBlazor (Vitest\u002FbUnit):** `\u003CComponent> \u003Cscenario> \u003Cexpected outcome>`\n\n### Minimum Per Component\n\n**Controllers:**\n- Happy path: authenticated valid input → correct service call → correct output\n- Unauthenticated → 401\n- Authenticated, wrong role → 403\n- Authenticated, wrong owner (BOLA) → 403\n- Invalid schema → 400 (no service call made)\n- Rate limit exceeded → 429\n\n**Services:**\n- Happy path for every public method\n- Each branch \u002F conditional has its own test\n- Resource ownership: non-owner blocked\n- Dependency failure modes\n\n**Validators:**\n- Every valid input variant passes\n- SQL injection strings, XSS payloads, oversized inputs, null bytes, SSRF URLs — all fail\n\n---\n\n## PART 8: MIDDLEWARE PIPELINE ORDER (.NET 8) — NEVER DEVIATE\n\n```csharp\nvar app = builder.Build();\n\nif (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); }\nelse { app.UseHsts(); }\n\n\u002F\u002F Security headers — must be first substantial middleware\napp.Use(async (context, next) => {\n    context.Response.Headers[\"X-Content-Type-Options\"] = \"nosniff\";\n    context.Response.Headers[\"X-Frame-Options\"] = \"DENY\";\n    context.Response.Headers[\"Referrer-Policy\"] = \"strict-origin-when-cross-origin\";\n    context.Response.Headers[\"Permissions-Policy\"] =\n        \"accelerometer=(), camera=(), geolocation=(), microphone=()\";\n    await next();\n});\n\napp.UseHttpsRedirection();\napp.UseSerilogRequestLogging();\napp.UseRouting();\napp.UseRateLimiter();        \u002F\u002F Rate limit before auth to block brute force\napp.UseCors(\"SpaPolicy\");\napp.UseAuthentication();    \u002F\u002F WHO are you?\napp.UseAuthorization();     \u002F\u002F WHAT can you do?\napp.MapControllers();\n```\n\nRemove Kestrel Server header: `builder.WebHost.ConfigureKestrel(o => o.AddServerHeader = false);`\n\n**`UseAuthentication` must precede `UseAuthorization`. Reversing them causes authentication to\nsilently fail and authorization to pass for all requests, including unauthenticated ones.**\n\n---\n\n## PART 9: IDENTITY, AUTHENTICATION, AND AUTHORIZATION\n\n### Authentication Flow Selection (Non-Negotiable)\n\n| Scenario | Required Flow | Never Use |\n|---|---|---|\n| React SPA user login | Authorization Code + PKCE | Implicit Grant (deprecated) |\n| Blazor WASM user login | Authorization Code + PKCE | Implicit Grant (deprecated) |\n| Service-to-service | Client Credentials | Shared secrets in config |\n| API calling downstream API for user | On-Behalf-Of (OBO) | Storing user tokens in service |\n| CLI tooling | Device Code | Embedded credentials |\n\n### .NET 8 — Microsoft.Identity.Web Setup\n\n```csharp\n\u002F\u002F Program.cs\nbuilder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)\n    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection(\"AzureAd\"));\nbuilder.Services.AddAuthorization();\n```\n\nJWT validation rules: `ClockSkew = TimeSpan.Zero`. Never hardcode signing keys.\nAlways validate: issuer, audience, lifetime, and signing key.\n\n### RBAC — App Roles (Prefer Over Group Claims)\n\n```csharp\nbuilder.Services.AddAuthorizationBuilder()\n    .AddPolicy(\"AdminOnly\", policy => policy.RequireRole(\"Admin\"))\n    .AddPolicy(\"ReaderOrAdmin\", policy => policy.RequireRole(\"Reader\", \"Admin\"))\n    .AddPolicy(\"DepartmentFinance\", policy =>\n        policy.RequireClaim(\"department\", \"finance\"));\n```\n\nUse App Roles, not Group Claims. Groups create a 200-group overage problem requiring Graph API\ncalls. App Roles are portable and have no overage.\n\n### BOLA Prevention (OWASP API1)\n\nResource-level authorization lives in the **service layer**, not the controller:\n\n```csharp\n\u002F\u002F IAuthorizationHandler implementation for resource-level checks\npublic class DocumentAuthorizationHandler\n    : AuthorizationHandler\u003CSameAuthorRequirement, Document>\n{\n    protected override Task HandleRequirementAsync(\n        AuthorizationHandlerContext context,\n        SameAuthorRequirement requirement, Document resource)\n    {\n        if (context.User.Identity?.Name == resource.AuthorId)\n            context.Succeed(requirement);\n        \u002F\u002F Never call context.Succeed for unauthorized access\n        return Task.CompletedTask;\n    }\n}\n```\n\nEvery endpoint that returns user-owned data must have a resource-level authorization check.\nNever rely on \"the user can only see their own ID in the UI.\"\n\n### Managed Identity — Zero-Secrets Pattern\n\n```csharp\n\u002F\u002F Credential selection — never use connection strings with keys\nvar credential = builder.Environment.IsDevelopment()\n    ? new DefaultAzureCredential()\n    : new ManagedIdentityCredential();  \u002F\u002F Faster startup in production\n\n\u002F\u002F Cosmos DB with Managed Identity\nvar cosmosClient = new CosmosClient(\n    \"https:\u002F\u002Fyour-account.documents.azure.com:443\u002F\",\n    credential,\n    new CosmosClientOptions { ConnectionMode = ConnectionMode.Direct });\n\n\u002F\u002F PostgreSQL with Managed Identity (token rotation every 4 hours)\nvar dataSourceBuilder = new NpgsqlDataSourceBuilder(connStringWithoutPassword);\ndataSourceBuilder.UsePeriodicPasswordProvider(async (_, ct) =>\n{\n    var token = await credential.GetTokenAsync(\n        new TokenRequestContext(\n            new[] { \"https:\u002F\u002Fossrdbms-aad.database.windows.net\u002F.default\" }), ct);\n    return token.Token;\n}, TimeSpan.FromHours(4), TimeSpan.FromSeconds(10));\n```\n\n### React MSAL.js\n\n```typescript\nexport const msalConfig: Configuration = {\n  auth: {\n    clientId: \"your-spa-client-id\",\n    authority: \"https:\u002F\u002Flogin.microsoftonline.com\u002Fyour-tenant-id\",\n    redirectUri: \"\u002F\",\n  },\n  cache: {\n    cacheLocation: \"sessionStorage\", \u002F\u002F NEVER localStorage — XSS-vulnerable\n    storeAuthStateInCookie: false,\n  },\n};\n\n\u002F\u002F Axios interceptor for automatic token injection\napiClient.interceptors.request.use(async (config) => {\n  const account = msalInstance.getActiveAccount();\n  if (!account) throw new Error('No active account');\n  try {\n    const response = await msalInstance.acquireTokenSilent({\n      scopes: ['api:\u002F\u002Fyour-api-client-id\u002F.default'], account,\n    });\n    config.headers.Authorization = `Bearer ${response.accessToken}`;\n  } catch (error) {\n    if (error instanceof InteractionRequiredAuthError) {\n      await msalInstance.acquireTokenRedirect({\n        scopes: ['api:\u002F\u002Fyour-api-client-id\u002F.default'],\n      });\n    }\n  }\n  return config;\n});\n```\n\nInstantiate `PublicClientApplication` OUTSIDE the component tree — never inside a component.\n\n### Blazor WASM\n\n```csharp\nbuilder.Services.AddMsalAuthentication(options =>\n{\n    builder.Configuration.Bind(\"AzureAd\", options.ProviderOptions.Authentication);\n    options.ProviderOptions.DefaultAccessTokenScopes.Add(\n        \"api:\u002F\u002Fyour-api-client-id\u002FApi.Read\");\n    options.ProviderOptions.LoginMode = \"redirect\";\n});\n```\n\n**Critical:** Blazor WASM assemblies are downloadable and decompilable. All `[Authorize]` and\n`AuthorizeView` components are UX features only. The API must re-validate every request. Never\nput secrets, sensitive business logic, or IP in WASM code.\n\n---\n\n## PART 10: API SECURITY (.NET 8)\n\n### Rate Limiting\n\n```csharp\nbuilder.Services.AddRateLimiter(options =>\n{\n    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;\n    options.AddTokenBucketLimiter(\"Api\", opt =>\n    {\n        opt.TokenLimit = 100;\n        opt.ReplenishmentPeriod = TimeSpan.FromSeconds(10);\n        opt.TokensPerPeriod = 20;\n        opt.QueueLimit = 5;\n    });\n    \u002F\u002F Per-user rate limiting (falls back to IP for anonymous)\n    options.GlobalLimiter = PartitionedRateLimiter.Create\u003CHttpContext, string>(\n        httpContext => RateLimitPartition.GetFixedWindowLimiter(\n            partitionKey: httpContext.User.Identity?.Name\n                ?? httpContext.Connection.RemoteIpAddress?.ToString() ?? \"anon\",\n            factory: _ => new FixedWindowRateLimiterOptions\n            {\n                PermitLimit = 60, Window = TimeSpan.FromMinutes(1)\n            }));\n});\n```\n\n### Input Validation with FluentValidation\n\n```csharp\npublic class CreateUserRequestValidator : AbstractValidator\u003CCreateUserRequest>\n{\n    public CreateUserRequestValidator()\n    {\n        RuleFor(x => x.Name).NotEmpty().MaximumLength(100)\n            .Matches(@\"^[a-zA-Z\\s\\-']+$\").WithMessage(\"Name contains invalid characters.\");\n        RuleFor(x => x.Email).NotEmpty().EmailAddress();\n        RuleFor(x => x.Age).InclusiveBetween(18, 120);\n    }\n}\n\u002F\u002F Program.cs — use base package, not the deprecated .AspNetCore package\nbuilder.Services.AddValidatorsFromAssemblyContaining\u003CCreateUserRequestValidator>();\n```\n\n### CORS — Exact Origins Only\n\n```csharp\nvar allowedOrigins = builder.Configuration\n    .GetSection(\"Cors:AllowedOrigins\").Get\u003Cstring[]>()!;\nbuilder.Services.AddCors(options =>\n{\n    options.AddPolicy(\"SpaPolicy\", policy => policy\n        .WithOrigins(allowedOrigins)  \u002F\u002F NEVER AllowAnyOrigin() in production\n        .AllowAnyHeader().AllowAnyMethod().AllowCredentials());\n});\n```\n\nNote: trailing slash in origin URLs causes silent comparison failure — omit it.\n\n### Key Vault Bootstrap\n\n```csharp\nvar kvUri = new Uri($\"https:\u002F\u002F{builder.Configuration[\"KeyVaultName\"]}.vault.azure.net\u002F\");\nbuilder.Configuration.AddAzureKeyVault(kvUri, new DefaultAzureCredential(),\n    new AzureKeyVaultConfigurationOptions { ReloadInterval = TimeSpan.FromMinutes(5) });\n```\n\n---\n\n## PART 11: FRONTEND SECURITY\n\n### React XSS Prevention\n\nFour vectors that bypass React's auto-escaping — never use these unsafely:\n1. `dangerouslySetInnerHTML` without sanitization — always sanitize with DOMPurify\n2. `href` with `javascript:` protocol — validate URLs before use\n3. Direct DOM manipulation via `ref.current.innerHTML` — avoid; use React state\n4. `eval()` with user input — never\n\n```tsx\nimport DOMPurify from 'dompurify';\nexport function SafeHTML({ html }: { html: string }) {\n  const sanitized = DOMPurify.sanitize(html, {\n    ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'a'],\n    FORBID_TAGS: ['script', 'style', 'iframe'],\n    FORBID_ATTR: ['onerror', 'onload', 'onclick'],\n  });\n  return \u003Cdiv dangerouslySetInnerHTML={{ __html: sanitized }} \u002F>;\n}\n```\n\n### Protected Routes\n\n```tsx\nfunction ProtectedRoute({ allowedRoles }: { allowedRoles?: string[] }) {\n  const isAuthenticated = useIsAuthenticated();\n  const { accounts } = useMsal();\n  const location = useLocation();\n  if (!isAuthenticated)\n    return \u003CNavigate to=\"\u002Flogin\" state={{ from: location }} replace \u002F>;\n  if (allowedRoles?.length) {\n    const userRoles = (accounts[0]?.idTokenClaims as any)?.roles ?? [];\n    if (!allowedRoles.some(role => userRoles.includes(role)))\n      return \u003CNavigate to=\"\u002Funauthorized\" replace \u002F>;\n  }\n  return \u003COutlet \u002F>;\n}\n```\n\nThis is a UX gate, not a security boundary. The API endpoint is the real boundary.\n\n### Content Security Policy (Vite)\n\n```typescript\n\u002F\u002F vite.config.ts\nexport default defineConfig({\n  build: { assetsInlineLimit: 0 }, \u002F\u002F Prevent inline scripts that bypass CSP\n  server: {\n    headers: {\n      'Content-Security-Policy': [\n        \"default-src 'self'\", \"script-src 'self'\",\n        \"connect-src 'self' https:\u002F\u002Flogin.microsoftonline.com https:\u002F\u002Fapi.example.com\",\n        \"img-src 'self' data: https:\", \"frame-ancestors 'none'\",\n      ].join('; '),\n    },\n  },\n});\n```\n\n---\n\n## PART 12: DATA LAYER SECURITY\n\n### Cosmos DB — Managed Identity Access\n\n```bash\n# Assign Cosmos DB Built-in Data Contributor role\naz cosmosdb sql role assignment create \\\n  --account-name myCosmosAccount --resource-group myRG \\\n  --role-definition-id \"00000000-0000-0000-0000-000000000002\" \\\n  --principal-id \"\u003Cmanaged-identity-principal-id>\" --scope \"\u002F\"\n```\n\n**Critical pitfall:** Azure control-plane roles (e.g., \"Cosmos DB Account Contributor\") do NOT\ngrant data-plane access. You must assign Cosmos DB's native data-plane RBAC roles separately.\nAlways include `readMetadata` permission or queries fail with 403.\n\n### PostgreSQL — Parameterized Queries Only\n\n```csharp\n\u002F\u002F CORRECT\nawait using var cmd = new NpgsqlCommand(\n    \"SELECT * FROM users WHERE id = @id AND tenant_id = @tenantId\", conn);\ncmd.Parameters.AddWithValue(\"@id\", userId);\ncmd.Parameters.AddWithValue(\"@tenantId\", tenantId);\n\n\u002F\u002F NEVER — string interpolation in SQL = SQL injection\n\u002F\u002F var cmd = new NpgsqlCommand($\"SELECT * FROM users WHERE id = {userId}\");\n```\n\n### Databricks — Unity Catalog and PII Masking\n\n```sql\n-- Column-level PII masking\nCREATE FUNCTION mask_email(email STRING) RETURNS STRING\nRETURN CASE\n  WHEN IS_ACCOUNT_GROUP_MEMBER('pii-readers') THEN email\n  ELSE CONCAT('***', SUBSTRING(email, LOCATE('@', email)))\nEND;\nALTER TABLE customers ALTER COLUMN email SET MASK mask_email;\n-- Row-level security\nALTER TABLE sales SET ROW FILTER filter_fn ON (region);\n```\n\nUse Unity Catalog for all data governance. Never access data directly via storage keys.\n\n### Secrets Sprawl Prevention\n\n- 35% of private repositories contain secrets (GitGuardian 2025).\n- Never commit secrets, even in private repositories.\n- `.gitignore` must include: `.env`, `.env.*`, `*.pem`, `*.key`, `*.pfx`,\n  `appsettings.Production.json`, `appsettings.Staging.json`, `secrets\u002F`, `.azure\u002F`, `.aws\u002F`,\n  `.ssh\u002F`, `local.settings.json`, `launchSettings.json`.\n\n---\n\n## PART 13: INFRASTRUCTURE SECURITY AND DEVSECOPS\n\n### Azure Key Vault — Required Bicep Configuration\n\n```bicep\nresource vault 'Microsoft.KeyVault\u002Fvaults@2023-07-01' = {\n  name: 'kv-${uniqueString(resourceGroup().id)}'\n  location: location\n  properties: {\n    sku: { family: 'A', name: 'premium' }\n    tenantId: tenant().tenantId\n    enableRbacAuthorization: true       \u002F\u002F Use RBAC, not legacy access policies\n    enableSoftDelete: true\n    softDeleteRetentionInDays: 90\n    enablePurgeProtection: true         \u002F\u002F Cannot be disabled once set — intentional\n    publicNetworkAccess: 'Disabled'\n    networkAcls: { defaultAction: 'Deny', bypass: 'AzureServices' }\n  }\n}\n```\n\n### Private Endpoints\n\nAll PaaS services use Private Endpoints. Required DNS zones:\n- Key Vault: `privatelink.vaultcore.azure.net`\n- Cosmos DB: `privatelink.documents.azure.com`\n- PostgreSQL: `privatelink.postgres.database.azure.com`\n- Databricks: `privatelink.azuredatabricks.net`\n- Storage: `privatelink.blob.core.windows.net`\n\nKnown Bicep bug: `environment().suffixes.keyvaultDns` returns `.vault.azure.net` but the correct\nprivate DNS zone is `privatelink.vaultcore.azure.net` — always hardcode.\n\n### DevSecOps Pipeline — All Gates Required\n\n```yaml\nname: Security-First Scrum CI\u002FCD\njobs:\n  sast-semgrep:       # p\u002Fsecurity-audit p\u002Fowasp-top-ten p\u002Fcsharp p\u002Ftypescript\n  sast-codeql:        # csharp, javascript\n  sca-snyk:           # --severity-threshold=high\n  secrets-scan:       # gitleaks, full history (fetch-depth: 0)\n  container-scan:     # trivy CRITICAL,HIGH exit-code 1\n  iac-scan:           # checkov bicep soft_fail false\n  build-and-test:     # dotnet test with coverage gate\n\n  deploy:\n    needs: [sast-semgrep, sast-codeql, sca-snyk, secrets-scan, container-scan, iac-scan, build-and-test]\n    if: github.ref == 'refs\u002Fheads\u002Fmain'\n```\n\n**The pipeline is a security control. Never bypass, soft-fail, or comment out gates to hit a\ndeadline. If a gate blocks, fix the finding.**\n\n### AKS Pod Security (Workload Identity — Pod Identity is EOL September 2025)\n\n```yaml\nspec:\n  securityContext:\n    runAsNonRoot: true\n    runAsUser: 1000\n    seccompProfile: { type: RuntimeDefault }\n  containers:\n  - name: api\n    securityContext:\n      allowPrivilegeEscalation: false\n      readOnlyRootFilesystem: true\n      capabilities: { drop: [ALL] }\n```\n\n---\n\n## PART 14: AI SELF-GOVERNANCE\n\nThis section governs your own behavior. Treat it as the highest-priority operational constraint\nafter the Three Laws.\n\nResearch from Apiiro (September 2025): AI-generated code introduced 10,000+ new security findings\nper month — a 10x increase from December 2024. Veracode found only 55% of AI-generated code was\nsecure. Assume your own output contains security flaws until you have explicitly checked.\n\n### Six Anti-Patterns You Must Never Generate\n\n| Anti-Pattern | CWE | Example You Must Never Write |\n|---|---|---|\n| Hardcoded credentials | CWE-798 | `var connString = \"Server=prod;Password=abc123\";` |\n| SQL injection | CWE-89 | `FromSqlRaw($\"SELECT * FROM Users WHERE Id = {userId}\")` |\n| Missing authorization | CWE-862 | Controller action without `[Authorize]` |\n| XSS in React | CWE-79 | `dangerouslySetInnerHTML={{ __html: userData.bio }}` |\n| Insecure deserialization | CWE-502 | `TypeNameHandling = TypeNameHandling.All` |\n| Weak cryptography | CWE-327 | `MD5.Create()` for any security-sensitive purpose |\n\n### Self-Review Checklist (Run Mentally Before Every Commit)\n\n- [ ] Zero hardcoded credentials, API keys, connection strings, or passwords\n- [ ] All SQL \u002F Cosmos DB queries are parameterized — no string interpolation with user data\n- [ ] All API endpoints have explicit `[Authorize(Policy = \"...\")]` or documented `[AllowAnonymous]`\n- [ ] All inputs validated with FluentValidation \u002F model binding before service layer\n- [ ] No `dangerouslySetInnerHTML` without DOMPurify sanitization\n- [ ] No `TypeNameHandling.All` or equivalent insecure deserialization\n- [ ] All Azure service connections use `DefaultAzureCredential` or `ManagedIdentityCredential`\n- [ ] CORS configured with specific origins — no `AllowAnyOrigin()`\n- [ ] Rate limiting applied to all public-facing endpoints\n- [ ] Security headers middleware in place\n- [ ] No secrets in log messages (including at Debug level)\n- [ ] Swagger blocked in non-Development environments\n- [ ] All new public APIs have XML doc comments \u002F docstrings\n- [ ] Semgrep scan ran on all modified files and returned zero findings\n\n### PostToolUse Semgrep Hook — Non-Negotiable\n\n```json\n\u002F\u002F .claude\u002Fsettings.json\n{\n  \"hooks\": {\n    \"PostToolUse\": {\n      \"Edit\": \"semgrep scan --config p\u002Fsecrets --config p\u002Fowasp-top-ten --quiet ${CLAUDE_FILE_PATH}\"\n    }\n  }\n}\n```\n\nEvery file edit triggers a Semgrep scan. Fix all findings before proceeding.\n\n### File Access Restrictions\n\nNever read into AI context:\n```\n.env, .env.*, *.pem, *.key, *.pfx\nappsettings.Production.json, appsettings.Staging.json\nsecrets\u002F, .azure\u002F, .aws\u002F, .ssh\u002F\nlocal.settings.json, launchSettings.json\n```\n\n---\n\n## PART 15: AGENTIC EXECUTION PROTOCOL (9 STEPS)\n\nFollow this exact sequence for every task. The codebase must be passing after every step.\n\n```\nSTEP 1 — UNDERSTAND\n  Read spec \u002F acceptance criteria and Security Considerations section.\n  Identify architectural layers and security controls required.\n  State the threat model before writing any code.\n\nSTEP 2 — INTERFACE FIRST\n  Define or verify the C# interface (or Python ABC).\n  Define input\u002Foutput contracts. Include security preconditions in docstring.\n\nSTEP 3 — TEST (RED)\n  Write unit tests: happy path, 401, 403, BOLA 403, input rejection, failure modes.\n  Run tests. Confirm they fail for the right reason.\n\nSTEP 4 — IMPLEMENT (GREEN)\n  Minimum secure code to pass the tests.\n  Apply every security control from the Security Considerations section.\n\nSTEP 5 — SECURITY SCAN\n  semgrep scan --config p\u002Fsecrets --config p\u002Fowasp-top-ten \u003Cmodified_files>\n  Zero findings required. Fix any before proceeding.\n\nSTEP 6 — QUALITY GATE\n  format → lint → type-check → test (with coverage). All must pass.\n\nSTEP 7 — REFACTOR\n  Improve clarity without changing behavior. Re-run quality gate + security scan.\n\nSTEP 8 — INTEGRATION\n  Write \u002F run integration tests if external I\u002FO is involved.\n  Verify Managed Identity — no connection strings with keys.\n\nSTEP 9 — REVIEW CHECKLIST\n  All tests pass. Coverage >= threshold (100% on security-critical paths).\n  Zero linting or type errors. Zero Semgrep findings.\n  Zero secrets in code or tests. XML doc comments complete.\n  Required log events present. Error handling follows retry \u002F no-retry policy.\n  No TODOs without ticket ID. Conventional Commits message. Self-review complete.\n```\n\n---\n\n## PART 16: DEFINITION OF DONE\n\nA feature is DONE only when ALL of the following are true.\n\n### Code Completeness\n\n- [ ] Spec \u002F acceptance criteria written and referenced (with Security Considerations section)\n- [ ] Interface(s) defined and documented (with security preconditions)\n- [ ] No TODOs, stubs, or unimplemented bodies in production code paths\n- [ ] All public APIs have complete XML doc comments \u002F docstrings\n\n### Testing\n\n- [ ] Contract \u002F schema tests passing\n- [ ] Unit tests passing — all happy paths + all error paths\n- [ ] Security unit tests passing — positive + adversarial for every security control\n- [ ] Integration tests passing (if I\u002FO involved)\n- [ ] Coverage >= 80% overall; >= 85% new code; >= 90% service layer; **100% security-critical paths**\n\n### Security\n\n- [ ] Zero Semgrep findings (medium+) on all modified files\n- [ ] Zero secrets in code, tests, or commit history\n- [ ] All endpoints have explicit `[Authorize(Policy = \"...\")]` or documented `[AllowAnonymous]`\n- [ ] Input validated with FluentValidation \u002F model binding on all public inputs\n- [ ] All Azure service connections use Managed Identity\n- [ ] BOLA \u002F resource ownership check implemented for all user-owned data endpoints\n- [ ] Rate limiting applied to all public-facing endpoints\n- [ ] Security headers middleware in place\n- [ ] No PII or credentials in log messages\n- [ ] Swagger blocked in non-Development environments\n\n### Code Quality\n\n- [ ] Zero linting errors\n- [ ] Zero type errors (nullable enabled in .NET; strict in TypeScript; mypy strict in Python)\n- [ ] Structured logging at all required events\n- [ ] Error handling follows the retry \u002F no-retry policy\n- [ ] Mock\u002Ffake implementation updated to match interface changes\n\n### Process\n\n- [ ] CI pipeline green — all security gates passed\n- [ ] Branch protection requirements satisfied (linked work item, reviewer, all checks)\n- [ ] Commit messages follow Conventional Commits format\n- [ ] PR description references the sprint story and security considerations\n\n---\n\n## PART 17: ANTI-PATTERNS — NEVER DO THESE\n\n### Security Anti-Patterns (Highest Severity)\n\n- Hardcoding any credential, key, connection string, or secret anywhere in source code\n- Using `AllowAnyOrigin()` in CORS configuration\n- Storing tokens in `localStorage` — always `sessionStorage` or in-memory\n- Creating `PublicClientApplication` inside a React component (re-created on every render)\n- Enabling implicit grant on any app registration\n- Sharing a single app registration across environments\n- SQL query with string interpolation using user-supplied data\n- `dangerouslySetInnerHTML` without DOMPurify sanitization\n- `TypeNameHandling = TypeNameHandling.All` in JSON deserialization\n- `MD5.Create()` for any security-sensitive purpose\n- Exposing Swagger \u002F SwaggerUI in any non-Development environment\n- A controller action without explicit `[Authorize]` or `[AllowAnonymous]`\n- Logging JWTs, passwords, API keys, PII, or connection strings at any log level\n- Bypassing or soft-failing any security gate in CI to unblock deployment\n- Using connection strings with embedded keys for any Azure service\n- Using Azure control-plane roles as a substitute for data-plane RBAC\n- `UseAuthentication()` placed after `UseAuthorization()` in the middleware pipeline\n- Retrying on 401 or 403 responses (permanent failures, never transient)\n- Resource-level authorization (BOLA check) placed in the controller instead of the service\n- Sharing Managed Identities across services with different trust requirements\n- Using Pod Identity in AKS (deprecated, EOL September 2025) — use Workload Identity\n\n### Architecture Anti-Patterns\n\n- Business logic in a controller or Blazor page\n- Controller, service, or repository without a corresponding interface\n- Direct repository call from a controller (bypasses service layer)\n- Importing a concrete repository class into a service\n- Domain model importing from infrastructure, EF Core, or Azure SDKs\n- Circular dependencies between layers\n\n### Testing Anti-Patterns\n\n- Writing implementation before a failing test\n- Testing implementation details instead of behavior\n- Mocking the class under test\n- Using production Azure resources in unit tests\n- Tests that depend on execution order\n- Omitting the adversarial \u002F negative security test case\n\n### Code Quality Anti-Patterns\n\n- `catch (Exception) { }` or swallowing exceptions silently\n- Magic numbers \u002F strings without named constants\n- Methods longer than ~50 lines\n- `async void` methods (except Blazor event callbacks where unavoidable)\n- Blocking on async code (`.Result`, `.Wait()`) — always `await`\n- Commented-out code committed to the repository\n\n### Agentic Anti-Patterns\n\n- Generating large blocks of code without running tests\n- Modifying multiple layers at once without verifying each layer\n- Skipping the interface step and going straight to implementation\n- Assuming security requirements when they are not explicit in the spec — surface the gap\n- Leaving the codebase in a broken state between steps\n- Suggesting a deadline workaround that involves bypassing a security control\n- Treating \"it's behind the firewall\" as a security argument — Zero Trust applies everywhere\n\n---\n\n## PART 18: STRUCTURED LOGGING STANDARDS\n\nUse Microsoft.Extensions.Logging with Application Insights or OpenTelemetry sink.\n\n### Required Log Events\n\n| Event | Level | Layer |\n|---|---|---|\n| Request received | Information | Controller |\n| Authentication failure | Warning + userId attempt | Controller |\n| Authorization denial | Warning + userId + resource | Controller |\n| Validation failure | Warning | Controller |\n| Suspicious input detected | Warning + sanitized input | Controller |\n| Business operation started | Information | Service |\n| Resource ownership check failed | Warning + userId + resourceId | Service |\n| External call (DB, API, queue) | Debug | Repository |\n| External call failed (retry) | Warning | Repository |\n| Business operation completed | Information | Service |\n| Unhandled error | Error + exception | Any |\n\n### Security Logging Rules — Strict\n\n- NEVER log: passwords, JWTs, API keys, connection strings, credit card numbers, SSNs, PII\n- NEVER log: Azure Service Bus \u002F Event Hub message payloads\n- ALWAYS log: authentication failures with the user identifier (not the password)\n- ALWAYS log: authorization denials with userId + resourceId + required policy\n- ALWAYS log: rate limit violations with the partition key\n- Use structured message templates with named placeholders, never string interpolation\n\n---\n\n## PART 19: ERROR HANDLING STANDARDS\n\n### Exception Hierarchy\n\n```\nAppException (base)\n+-- ValidationException        \u003C- malformed input, FluentValidation failure\n+-- NotFoundException          \u003C- resource does not exist\n+-- AuthException              \u003C- authentication \u002F authorization failure (NEVER retry)\n+-- ResourceOwnershipException \u003C- BOLA (NEVER retry)\n+-- ExternalServiceException   \u003C- downstream failure\n|   +-- TransientException     \u003C- retriable subset (timeout, 429, 503)\n+-- ConfigException            \u003C- missing \u002F invalid App Configuration or Key Vault\n```\n\n### Retry Policy\n\n- Retry on: network timeouts, Cosmos DB 429, 503, Azure Service Bus transient errors\n- DO NOT retry on: 400, 401, 403, 404, 409, AuthException, ResourceOwnershipException\n- Exponential backoff with jitter: 1s, 2s, 4s, 8s, 16s. Max retries: 3-5.\n- Use Polly (.NET) or tenacity (Python).\n\n### Controller Error Mapping (RFC 7807 ProblemDetails)\n\n```\nValidationException          -> 400\nNotFoundException            -> 404\nAuthException                -> 401 (generic message, no detail)\nResourceOwnershipException   -> 403 (generic message)\nTransientException           -> 503 with Retry-After header\nAll others                   -> 500 with correlation ID, no internal details\n```\n\n---\n\n## PART 20: GIT AND COMMIT STANDARDS\n\n### Conventional Commits Format\n\n```\n\u003Ctype>(\u003Cscope>): \u003Cshort summary>\nTypes: feat | fix | test | refactor | docs | chore | perf | ci | security\n```\n\nUse `security` type for any commit whose primary purpose is addressing a vulnerability.\n\n### Commit Rules\n\n- Every commit passes the pre-commit gate (format + lint + type-check + unit tests + semgrep)\n- Test and implementation committed together — never implementation without test\n- Each commit is atomic: one logical change, fully tested, not broken\n- Never commit secrets — not even \"temporary\" or \"test\" commits. Git history is forever\n\n### Branch Protection Requirements\n\nEvery PR into `main` requires:\n- Linked work item (`AB#\u003CWorkItemID>` in commit message)\n- At least one reviewer (different from author)\n- Passing build with all security gates\n- Zero Semgrep \u002F Gitleaks \u002F Trivy findings\n",{"name":5,"description":7},"develop","ae32736a1aabddabca5d2c96d665aa0ebc7d8700","src\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fsecurity-first-dev\u002Fskills\u002Fsecurity-first-scrum",3,"https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey","https:\u002F\u002Fthe-vibey-project.github.io\u002Fvibey\u002F","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project","https:\u002F\u002Fvibewithadam.matthewsteinberger.com","freedom for software engineers","2026-11-15 05:47:42",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add the-vibey-project\u002Fvibey --skill security-first-scrum",{"tool":40,"command":41},"bunx","bunx skills add the-vibey-project\u002Fvibey --skill security-first-scrum",{"tool":43,"command":44},"pnpm","pnpm dlx skills add the-vibey-project\u002Fvibey --skill security-first-scrum","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fsecurity-first-dev\u002Fskills\u002Fsecurity-first-scrum\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7AT1FQJAE1FQYAMDTF490Y4","white-paper-writing","Use when writing white papers, technical reports, policy documents, thought leadership pieces, or any long-form authoritative document. Triggers on requests to write, structure, outline, or review white papers, technical reports, position papers, policy briefs, or evidence-driven arguments. Also use for B2B content marketing strategy, technical documentation requiring authority, academic-style reports, or any document that must educate while persuading. Use when someone asks \"how should I structure this\" for a long-form document.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fwhite-paper-writing\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7AT16BJRJJKK2MASXRZS76G","prose-technical-mechanics","Use when editing or writing prose at a technical\u002Fmechanical level: choosing between Anglo-Saxon and Latinate diction, placing information in topic vs stress positions, writing periodic vs cumulative sentences, handling sentence rhythm, punctuation as logic, transitions, paragraph structure, or phonesthetics. Use when someone wants to understand WHY prose works or doesn't, not just surface-level style advice. Triggers on word choice, sentence structure, emphasis, rhythm, diction, or any deep writing mechanics question.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fprose-technical-mechanics\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7AT0W9HT0ZZ9Y287NW99MR3","prose-mechanics","Use when writing, editing, or analyzing prose style; when trying to avoid generic AI-sounding writing; when applying specific prose styles such as journalistic, academic, narrative, KJV biblical, Hemingway plain, Latinate\u002FJamesian, Orwellian, Augustan, Victorian, Early Modern (Bacon, Browne, Milton), or free indirect discourse; or when coaching someone on writing voice and mechanics. Triggers on any request to improve, analyze, or write in a specific prose style, to fix \"AI-sounding\" writing, to make prose more vivid or concrete, to vary sentence rhythm, or to understand how a particular writer achieves their effects.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fprose-mechanics\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M7AT0KR635JX66X2X6F3E2CP","narrative-structure","Use when structuring stories, pitches, presentations, white papers, or any persuasive narrative; analyzing the hero's journey in fiction or non-fiction; applying StoryBrand for business communication; designing narrative arcs for thought leadership; or understanding Vogler, Snyder, Propp, or Campbell frameworks. Triggers on any narrative structure, storytelling, pitch structure, StoryBrand, hero's journey, three-act structure, Freytag, Save the Cat, narrative arc, or \"how should I structure this story\u002Fpitch\u002Fpresentation\" request.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fnarrative-structure\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M7AT0AKGW09NKKZDYBT8VRDE","legal-brief-writing","Use when writing legal briefs, motions, or any court filing; when analyzing judicial cognition and persuasion; when applying elite brief-writing techniques from Roberts, Clement, Kagan, Garner; or when structuring legal arguments for maximum persuasion. Also use for autistic\u002Fneurodivergent advocates who need to understand how their natural communication style maps to elite legal advocacy. Triggers on any legal writing, brief drafting, motion preparation, or legal argument structuring request.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Flegal-brief-writing\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M7AT00VWPS4Q8B5VEMXX9NQT","journal-publishability-criteria","Use whenever a research paper, article or preprint is being written, revised, reviewed or published, and specifically before every publication of docs\u002Fpaper.md. Covers what legitimate journals actually gate on, in order of gating — the editor's desk screen (scope, novelty, package problems), what reviewers judge (methodological soundness, claims the evidence can carry, statistical and qualitative reporting), EQUATOR reporting guidelines, the ICMJE authorship criteria, COPE's view of text recycling, the near-universal generative-AI policy (no AI author, disclosure, author responsibility), TOP 2025 transparency standards, how to verify a journal is legitimate, submitting without an institution, and a pre-submission checklist. Triggers on requests to evaluate, review, prepare or submit a paper, to judge publishability, to write a declarations or data-availability section, to disclose AI use, or to check a journal.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fjournal-publishability-criteria\u002FSKILL.md",[],[]]