[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M786KZZH2PF102493X32659T":3,"skill-same:01M786KZZH2PF102493X32659T":55},{"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":29,"commitSha":30,"skillDirectory":31,"forksCount":32,"repositoryHtmlUrl":33,"repositoryHomepageUrl":6,"ownerHtmlUrl":34,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":35,"install":36,"resources":48},"01M786KZZH2PF102493X32659T","service-layout",null,"MANDATORY normative standard for how a company Python service MUST look: canonical package layout, import borders, domain models, mappings, ports\u002FDI, errors, settings\u002Fsecrets, persistence\u002FUoW, lifecycle, observability — ruling ids L\u002FI\u002FD\u002FM\u002FP\u002FE\u002FS\u002FT\u002FY\u002FO. Use when designing a new service, scaffolding greenfield code, or reviewing an existing service. On activation the FULL standard applies in every scenario; every violation is reported by ruling id.","kalaverin\u002Fskills","kalaverin","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6841312?v=4","01M786EMXK5R6A138KWFAS33T1","Alex Kalaverin","01M786EMYBQEDP3548REZHRX2Q",1,"BSD-3-Clause","https:\u002F\u002Fgithub.com\u002Fkalaverin\u002Fskills\u002Fblob\u002Fmain\u002F_on_demand\u002Fservice-layout\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: service-layout\ndescription: \"MANDATORY normative standard for how a company Python service MUST look: canonical package layout, import borders, domain models, mappings, ports\u002FDI, errors, settings\u002Fsecrets, persistence\u002FUoW, lifecycle, observability — ruling ids L\u002FI\u002FD\u002FM\u002FP\u002FE\u002FS\u002FT\u002FY\u002FO. Use when designing a new service, scaffolding greenfield code, or reviewing an existing service. On activation the FULL standard applies in every scenario; every violation is reported by ruling id.\"\ntriggers:\n  request: \"service layout, service structure, структура сервиса, лейаут сервиса, как должен выглядеть сервис, новый сервис, создай сервис, создаём сервис, проектируем сервис, спроектируй сервис, проектирование сервиса, каркас сервиса, service scaffold, scaffolding, greenfield service, service design, company service standard, service standard, ревью сервиса, проверь сервис, service review, layout review, composition root, порты и адаптеры, hexagonal service\"\n  reason: \"Design, greenfield development, and review of company services must conform to the Company Service Layout Standard.\"\nruntime: true\nversion: 0.1.0\n---\n\n# SKILL: Company Service Layout Standard\n\nNormative standard for how every company service MUST look: layout, layering, domain models, mappings, ports\u002FDI, errors, settings, persistence, lifecycle, observability.\nRuling ids: one letter per dimension plus a number — **L** layout, **I** imports, **D** domain models, **M** mappings, **P** ports\u002FDI, **E** errors, **S** settings, **T** persistence\u002Fstorage, **Y** lifecycle, **O** observability.\nNormative keywords (`MUST`, `SHOULD`, `MAY`) follow RFC 2119 \u002F RFC 8174 (by `read-for-comments`).\n\n## Skill Boundary\n\n[ref: #sly-boundary]\n\n- This skill owns the normative STRUCTURE of a service: package layout, import direction and borders, domain model shapes, mapping rules, ports and DI, error taxonomy, settings and secrets, persistence and UoW, entrypoint and lifecycle, observability wiring.\n- This skill does NOT own Python code style (→ `python-lang`), the review workflow and report format (→ `code-review`), API resource design (→ `api-design`), or protobuf schema style (→ `protobuf-lang`). Those load alongside via their own triggers.\n- The standard is anchored to Python services (gRPC and FastAPI). For another language, apply the structural rulings and ask the user about idiomatic mapping.\n\n## Activation Scenarios\n\n[ref: #sly-scenarios]\n\n- On activation the ENTIRE standard is in force. Selective application is FORBIDDEN: in every scenario you check ALL rulings (L\u002FI\u002FD\u002FM\u002FP\u002FE\u002FS\u002FT\u002FY\u002FO; profile-conditional ones per the detected profile) and the WHOLE anti-pattern registry, and you MUST detect and report EVERY violation found, each cited by its ruling id.\n- **Design:** propose service skeletons only per the canonical layout; every proposed element cites the ruling ids it satisfies.\n- **Greenfield development:** scaffold per the profile tree; the Conformance Checklist is the definition of done.\n- **Code review:** check the changeset or service against every ruling and the registry; findings cite ruling ids; the Conformance Checklist is the final gate.\n- The scenario changes ONLY the output shape (proposal, scaffold plan, findings list) — never the set of rules applied.\n\n## Profile Detection\n\n[ref: #sly-profiles]\n\n- Before applying profile-conditional rulings, classify the service at hand. The profile is the decision criterion for what applies — you make this classification yourself.\n- **Profile A — gRPC resource service (stateful):** owns a Postgres DB, serves gRPC.\n- **Profile B — REST gateway \u002F BFF (stateless):** FastAPI over downstream gRPC\u002FHTTP\u002FTemporal, no local DB.\n- The primary classification signal is DB ownership: the service owns a Postgres DB (`migrations\u002F` + `storages\u002F`) → A; no local DB, FastAPI over downstream gRPC\u002FHTTP\u002FTemporal → B. Upstream clients under `services\u002F` appear in both profiles and never decide alone; serving REST alongside gRPC does not change A while the service owns its DB.\n- Legacy non-conformant services exist (3-tier with ORM-as-domain, bespoke adapters without `core\u002F`\u002F`storages\u002F`); the migration target is Profile A — never invent a third profile (L5).\n- Profile-conditional rulings: L4, T1, P4, M4, and the layout trees; L5 applies only to legacy services. Every other ruling applies unconditionally to both profiles.\n- On ambiguous classification, ask the user — never guess the profile.\n- Out of scope of this standard: Temporal workers, shared libraries, GitOps configs.\n\n## Canonical Layout\n\n[ref: #sly-layout]\n\n- The layout exists to keep `domain\u002F` and `core\u002F` unit-testable without infrastructure: ports accept fake implementations, so tests never touch network or DB.\n\n### Package roots\n\n[ref: #sly-package-roots]\n\n- `app\u002F` — the application code (L1, MUST).\n- `src\u002F\u003Cmodule>\u002F` — isolated project-specific component packages (e.g. a client module for some API), at project root. One-way isolation: `app\u002F` MAY import from `src\u002F`; `src\u002F` MUST NEVER import from `app\u002F` (enforced, I4).\n- `sdk\u002F\u003Cprovider>\u002F` — general, extractable third-party\u002Fprovider toolkits, at project root (L3). `sdk\u002F` imports nothing project-side. The split: `src\u002F` is project-specific, `sdk\u002F` is general\u002Freusable.\n\n### Profile A tree\n\n[ref: #sly-profile-a-tree]\n\n```text\n\u003Cservice>\u002F\n├── app\u002F\n│   ├── domain\u002F                 # pure: frozen dataclasses + StrEnum, stdlib imports only\n│   ├── core\u002F                   # use cases + ports (the hexagon)\n│   │   ├── \u003Caggregate>.py      #   business logic over ports\n│   │   ├── repo.py             #   @runtime_checkable Protocol repos (one per aggregate)\n│   │   ├── storage.py          #   Storage Protocol aggregating the repos\n│   │   └── transaction_manager.py  # TransactionManager Protocol (UoW)\n│   ├── storages\u002F\u003Cbackend>\u002F     # persistence adapters (postgres\u002F, object storage, ...); skip if stateless\n│   ├── services\u002F               # outbound adapters: grpc\u002F\u003Cupstream>\u002F, http\u002F\u003Cthirdparty>\u002F (only if used)\n│   ├── api\u002F                    # the ONLY delivery package\n│   │   ├── errors\u002F             # edge concerns defined ONCE, shared by all transports\n│   │   ├── health\u002F\n│   │   ├── auth\u002F\n│   │   ├── grpc\u002F\u003Centity>\u002F      # servicers.py (thin) + models.py (view assembly) + views.py (pb2 serializers)\n│   │   │   └── interceptors\u002F   # logging, exception mapping\n│   │   └── http\u002F               # only when the service truly serves REST too\n│   ├── bootstrap.py            # composition root: build_provider(config)\n│   ├── server.py               # entrypoint: sentry, settings, secrets, bootstrap, serve; owns shutdown\n│   ├── settings.py             # pydantic-settings; grows into settings\u002F package per concern\n│   ├── secrets.py              # vault resolution, fail-fast at startup\n│   ├── errors.py               # ApplicationError hierarchy\n│   └── version.py              # single version source\n├── src\u002F\u003Cmodule>\u002F               # isolated project-specific modules (optional)\n├── sdk\u002F\u003Cprovider>\u002F             # general provider toolkits (optional)\n├── migrations\u002F                 # alembic (only when the service owns a DB)\n├── tests\u002F\n└── etc\u002F                        # lint configs\n```\n\n### Profile B tree\n\n[ref: #sly-profile-b-tree]\n\nSame skeleton minus `storages\u002F` and `migrations\u002F` (stateless, T1); `app\u002Fservices\u002Fgrpc|http\u002F\u003Cupstream>\u002F` is MANDATORY and carries the anti-corruption mappers (`mappers.py` next to the client code); delivery is `app\u002Fapi\u002Fhttp\u002Fv1\u002F\u003Cdomain>\u002F{handlers,schemas,models}.py` — handlers thin, `schemas.py` = input contracts, `models.py` = output contracts. Note: `models.py` is per-transport vocabulary — view assembly in Profile A gRPC, the output contract in Profile B REST.\n\n### Naming rulings\n\n[ref: #sly-naming-rulings]\n\n- `api\u002F` is the only legal delivery package; a top-level `grpc_api\u002F` is FORBIDDEN (L2, MUST NOT) — `\u003Cservice>\u002Fgrpc_api\u002F` at the repository root is the canonical violation.\n- Transports are siblings inside `api\u002F`: `api\u002Fgrpc\u002F`, `api\u002Fhttp\u002F`; shared edge concerns live once at the `api\u002F` root (L2).\n- One backend = one technology-named adapter package (`storages\u002Fpostgres\u002F`, never ORM-named) (L3, T1).\n- Profile B keeps the Profile A skeleton minus `storages\u002F` (stateless); `services\u002Fgrpc|http\u002F\u003Cupstream>\u002F` is obligatory for upstream calls (L4, MUST).\n- Legacy non-conformant services migrate toward Profile A; a third profile is MUST NOT (L5).\n\n## Rulings\n\n[ref: #sly-rulings]\n\n### Import direction and borders (I1–I4)\n\n[ref: #sly-ruling-imports]\n\n- **I1 (MUST)** Import direction: `api\u002F → core\u002F → domain\u002F`; adapters (`storages\u002F`, `services\u002F`) import `core\u002F` ports and `domain\u002F` models; `domain\u002F` imports stdlib ONLY. `app\u002F → src\u002F` is one-way; `sdk\u002F` imports nothing project-side.\n- **I2 (MUST)** Anti-corruption: pb2 \u002F ORM \u002F HTTP-client types live and convert only at their own boundary — pb2 in `api\u002Fgrpc\u002F\u003Centity>\u002Fviews.py` and `services\u002Fgrpc\u002F\u003Cupstream>\u002Fmappers.py`, ORM in `storages\u002F\u003Cbackend>\u002F`, HTTP types in `services\u002Fhttp\u002F`. A pb2 import inside `domain\u002F` is a blocking defect.\n- **I3 (MUST NOT)** Reverse imports: `services\u002F` never imports `api\u002F`; `core\u002F` never imports adapters.\n- **I4 (MUST)** Enforcement: import-linter in `pyproject.toml` `[tool.importlinter]` — `root_packages`, an exhaustive layered contract (a forgotten package = hard failure), `forbidden` contracts (`src ⇏ app`, `sdk ⇏ app, src`), `independence` contracts, forbidden external modules per layer; Ruff TID251 bans configured named imports (layer direction stays with import-linter); a pre-commit hook runs `lint-imports`. Reference shape:\n\n```toml\n[tool.importlinter]\nroot_packages = [\"app\", \"src\", \"sdk\"]\ninclude_external_packages = true\n\n[[tool.importlinter.contracts]]\nname = \"Layered: delivery and adapters over core over domain\"\ntype = \"layers\"\nlayers = [\"api | storages | services\", \"core\", \"domain\"]\ncontainers = [\"app\"]\nexhaustive = true\nexhaustive_ignores = [\"bootstrap\", \"server\", \"settings\", \"secrets\", \"errors\", \"version\"]\n\n[[tool.importlinter.contracts]]\nname = \"adapters are independent\"\ntype = \"independence\"\nmodules = [\"app.storages\", \"app.services\"]\n\n[[tool.importlinter.contracts]]\nname = \"src never imports app\"\ntype = \"forbidden\"\nsource_modules = [\"src\"]\nforbidden_modules = [\"app\"]\n\n[[tool.importlinter.contracts]]\nname = \"sdk imports nothing project-side\"\ntype = \"forbidden\"\nsource_modules = [\"sdk\"]\nforbidden_modules = [\"app\", \"src\"]\n\n[[tool.importlinter.contracts]]\nname = \"domain imports stdlib only\"\ntype = \"forbidden\"\nsource_modules = [\"app.domain\"]\nforbidden_modules = [\"grpc\", \"sqlalchemy\", \"httpx\", \"fastapi\", \"pydantic\"]\n```\n\n### Domain models and enums (D1–D4)\n\n[ref: #sly-ruling-domain-models]\n\n- **D1 (MUST)** Domain models are `@dataclass(frozen=True, slots=True)` — frozen AND slots by default, always. Mutability is a strict exception with a documented reason in the docstring; the exception covers data-carrier shapes only — business-state transitions still follow D3.\n- **D2 (MUST)** Text constants → `StrEnum`, numeric → `IntEnum`, members ALWAYS via `auto()`. Plain `str` statuses and plain `Enum` are MUST NOT.\n- **D3 (MUST)** State transitions are domain-object methods returning new instances (`dataclasses.replace`); external mutation from the service layer is MUST NOT. No `**` kwargs wiring in model conversions — field-by-field slot-to-slot only.\n- **D4 (MUST)** Three model families stay separate forever: ORM models (persistence) ≠ domain models (business) ≠ HTTP\u002Fpydantic IO schemas (REST validation). ORM-as-domain is MUST NOT.\n\n### Mappings (M1–M5)\n\n[ref: #sly-ruling-mappings]\n\n- **M1 (MUST)** Inbound pb2→domain: mapper functions in the transport layer build domain objects field-by-field. `from_pb2` ON domain models is MUST NOT (violates I2).\n- **M2 (MUST)** Outbound domain→pb2: `to_pb2`\u002F`views.py` helpers in the transport layer; handlers never build pb2 inline; the dict-splat response pattern is MUST NOT.\n- **M3 (MUST)** ORM↔domain: explicit mapper functions (`orm_to_domain` \u002F `domain_to_orm`) in a mapper module inside `storages\u002F\u003Cbackend>\u002F`; `to_domain()` on the ORM model is MUST NOT — the dependency stays one-directional and visible.\n- **M4 (MUST)** Profile B: `schemas.py` (input) validates and converts to domain via an explicit api-layer mapper; `models.py` (output) is built from domain field-by-field; domain objects are NEVER returned to FastAPI directly; `response_model` is always an IO model.\n- **M5 (MUST NOT)** `**`-unpacking in any conversion; `model_dump()` is legal only for wire serialization at the boundary itself. Automated mapping libraries (introspection-based, mapstruct-style) are MUST NOT: they break silently on field renames, while explicit field-by-field mapping is caught by mypy and IDE refactoring.\n\n### Ports and DI (P1–P4)\n\n[ref: #sly-ruling-ports-di]\n\n- **P1 (MUST)** Ports are `typing.Protocol` with `@runtime_checkable`. ABC ports are MUST NOT.\n- **P2 (MUST)** Composition root: `app\u002Fbootstrap.py` builds a `Provider` (storage + clients + sdks) at startup and threads it into servicers\u002Fhandlers via constructors. Module-level singletons (factory globals, stub registries, service-locator globals) are MUST NOT. The only sanctioned global is the read-only `config`. DI containers\u002Fframeworks (`punq`, `dependency-injector`) are MUST NOT without explicit user approval — manual constructor injection is the default.\n- **P3 (MUST NOT)** Per-request service instantiation. Services are built once in bootstrap.\n- **P4 (MUST)** Profile B: the `Provider` is built in the FastAPI lifespan, stored on `app.state`, threaded via `Depends` factories. `Depends` factories live in one `dependencies.py` module per transport package — never inside routes or bootstrap — to avoid circular imports.\n- **P5 (MUST)** Injected dependencies live at least as long as their consumers: singletons (config, connection pools, stateless services) NEVER receive per-request objects (DB sessions, transactions). A short-lived object captured by a long-lived one is a captive dependency and a blocking defect.\n\n### Errors (E1–E4)\n\n[ref: #sly-ruling-errors]\n\n- **E1 (MUST)** One hierarchy in `app\u002Ferrors.py`: `ApplicationError` root → `ClientError`\u002F`ServerError`; class names end with `Error`. Per-service custom roots are MUST NOT. Few types; a new class exists only with differentiated handling.\n- **E2 (MUST)** One central mapping place: gRPC interceptor \u002F FastAPI exception handler with an EXHAUSTIVE `ERROR_MAP`; an unmapped error is a bug. Local try\u002Fexcept only where behavior genuinely differs. The mapping distinguishes transient from permanent failures: a permanent failure gets a precise status code so the client knows NOT to retry.\n- **E3 (MUST)** Errors carry a reason enum serialized in exactly one place; stringly-typed matching and parsing `grpc.detail()` strings are MUST NOT. On the wire the reason travels as gRPC Rich Error Details (`ErrorInfo`), never packed into the message string.\n- **E4 (MUST)** Crash-loud at startup: config\u002Fsecrets\u002Fconnections fail loudly; no cleanup theater before the process starts.\n\n### Settings and secrets (S1–S4)\n\n[ref: #sly-ruling-settings]\n\n- **S1 (MUST)** pydantic-settings, one root `Settings` object; config is formed once at initialization from a single source. Swappable infra flavors are DISCRIMINATED UNIONS selected by a `type` discriminant. Flat `os.getenv` modules are MUST NOT. The root settings declare `SettingsConfigDict(env_prefix=\"\u003CSERVICE>_\", extra=\"ignore\")`: one env namespace per service, and unknown env vars are TOLERATED — orchestrators inject their own variables, `extra=\"forbid\"` would break deploys. Reference shape:\n\n```python\nclass VaultEnvConfig(BaseSettings):\n    type: Literal[\"env\"]  # every variant declares its discriminant\n    # fields...\n\nVaultConfig = Annotated[\n    VaultEnvConfig | VaultKubernetesConfig | VaultTokenConfig | VaultJWTConfig,  # Python ≥3.10 union syntax\n    Field(discriminator=\"type\"),\n]\n```\n\n- **S2 (MUST)** No defaults for secrets\u002Fpasswords\u002Ftokens, ever; required vars crash at startup naming the variable. Hardcoded vault tokens \u002F encryption keys are MUST NOT. Secret-typed fields use `pydantic.SecretStr` so values stay masked in logs and tracebacks.\n- **S3 (MUST)** `secrets.py` resolves vault secrets at startup BEFORE any client connects; failure = the process does not start.\n- **S4 (MUST)** `.env.example` is committed and documents every variable; the service boots locally without infrastructure (literals \u002F no-op implementations); dev opt-in is always explicit.\n\n### Persistence and UoW (T1–T4)\n\n[ref: #sly-ruling-persistence]\n\n- **T1 (MUST)** A stateful Profile-A service has alembic migrations + `storages\u002Fpostgres\u002F`; a stateless service MUST NOT grow a local DB. Multi-backend is legal — one package per backend.\n- **T2 (MUST)** UoW via the `TransactionManager` Protocol (`async with tm.transaction() as storage:`) WITH mandatory per-aggregate repository Protocols (`core\u002Frepo.py`). Handler-passed sessions are MUST NOT. A single `AsyncEngine` is created once at startup; the session factory is scoped per transaction; the UoW context manager MUST guarantee session closure even on exceptions.\n- **T3 (MUST NOT)** Manual `rollback()`\u002F`commit()` inside the `with session.begin():` context manager — the context manager owns commit\u002Frollback.\n- **T4 (MUST)** The migration version check is ACTIVE at startup and fails fast BEFORE serving traffic — the DB revision (`alembic.runtime.migration.MigrationContext.get_current_revision()`) is compared with the alembic head revision (`ScriptDirectory.get_current_head()`), and any mismatch aborts startup (a commented-out check is MUST NOT). On shutdown the engine is disposed (`await engine.dispose()`) so pooled idle connections do not leak.\n\n### Entrypoint and lifecycle (Y1–Y5)\n\n[ref: #sly-ruling-lifecycle]\n\n- **Y1 (MUST)** `main.py` is a thin entry, no CLI magic; `docker-entrypoint.sh` help text tells the truth — a help\u002Fcase mismatch is MUST NOT.\n- **Y2 (MUST)** Symmetric lifecycle: every `connect_*` has a paired close registered in `shutdown()`; shutdown is total and awaited (engine, channels, Temporal clients, HTTP sessions) and drains in-flight work with an explicit grace period (`server.stop(grace=N)`) before force-terminating. Long-running background `asyncio` tasks MUST receive cancellation (`asyncio.Event` \u002F `task.cancel()`) during shutdown and MUST be awaited there. No-op shutdown is MUST NOT.\n- **Y3 (MUST)** Single teardown owner: shutdown lives once in `server.py`\u002Flifespan; servicer `on_exit` teardown hooks are MUST NOT.\n- **Y4 (MUST)** Startup order: sentry → settings → secrets (vault) → bootstrap (`build_provider`) → serve; any failure before serve = the process does not start.\n- **Y5 (MUST)** Signal propagation: the container entrypoint uses the `exec` form (`ENTRYPOINT [\"python\", \"-m\", \"app.main\"]`) so the Python process receives `SIGTERM` directly — a shell-wrapped entrypoint swallows signals and the container dies by kill timeout, which is MUST NOT; an init shim (`tini`) is REQUIRED when the app is not PID 1.\n\n### Observability (O1–O7)\n\n[ref: #sly-ruling-observability]\n\n- **O1 (MUST)** Sentry is initialized at startup before clients connect (see Y4); DSN comes from settings with no hardcoded default. An empty DSN is ALLOWED for development, but startup MUST log a warning that Sentry is not initialized; silent disable is MUST NOT.\n- **O2 (MUST)** Sentry integrations match the transport: async gRPC services use `AsyncioIntegration` + `LoggingIntegration` + `GRPCIntegration`; REST services use `FastApiIntegration` + `LoggingIntegration`. PII is off globally (`send_default_pii=False` — no IPs, cookies, or POST bodies) AND `before_send` is a shared scrubber from a shared library; hand-copied per-service `sentry.py` filters are MUST NOT.\n- **O3 (MUST)** Logging goes through one shared configuration (from the org's shared logging library): plain + JSON formatters, level and format from settings, static fields (`service`, `version`, `environment`, k8s metadata) with the correct service name. Dumping the full config to logs at startup is MUST NOT. Copy-pasted logging config with a foreign env prefix or wrong service name is MUST NOT.\n- **O4 (SHOULD)** Request\u002Fcorrelation IDs propagated across gRPC metadata \u002F HTTP headers when a flow needs cross-service tracing — the W3C `traceparent` header is the canonical carrier; extraction\u002Finjection happens in transport middleware (FastAPI middleware, gRPC client\u002Fserver interceptors), never in business logic.\n- **O5 (SHOULD)** Prometheus metrics endpoint — optional but desirable. When present, metric names follow `namespace_subsystem_name_unit` (e.g. `grpc_server_duration_seconds`) and label values MUST be cardinality-bounded (`endpoint`, `method`, `status_code`); unbounded label values (`user_id`, full URLs, request parameters) are MUST NOT — high cardinality degrades Prometheus itself.\n- **O6 (out of scope)** Distributed tracing is not regulated by this standard; it is a separate per-team decision.\n- **O7 (out of scope)** Health-probe semantics are governed outside this standard; this standard only requires that the endpoints exist (gRPC services expose `startup`\u002F`readiness`\u002F`liveness` via grpc_health.v1, REST services `\u002Flivez` + `\u002Freadyz`); dependency-check depth is a per-team decision — with one hard warning: liveness MUST stay shallow (process alive only), because a deep liveness check turns a transient dependency outage into an orchestrator restart loop; dependency depth belongs to readiness.\n\nRationale: observability scaffolding is the most copy-pasted code in a service fleet; the fixes are cheap and uniform, while tracing and probe depth are separate per-team activities.\n\n## Anti-Pattern Registry\n\n[ref: #sly-anti-patterns]\n\nBanned patterns, each with the ruling that forbids it:\n\n1. Module-global mutable factories\u002Fregistries as DI (factory singletons, stub registries, service-locator globals) → composition root (P2).\n2. Per-request service instantiation → P3.\n3. Asymmetric\u002Fno-op shutdown → Y2.\n4. Servicer `on_exit` teardown → Y3.\n5. pb2 imports in `domain\u002F` → I2.\n6. Reverse imports `services\u002F` → `api\u002F` → I3.\n7. SQLAlchemy in business modules → I2.\n8. Mutable domain dataclasses as default → D1.\n9. Plain `str`\u002Fplain `Enum` statuses → D2.\n10. Domain mutation in the service layer → D3.\n11. `from_pb2` on domain models → M1.\n12. Dict-splat pb2 responses → M2.\n13. Domain objects as FastAPI responses → M4.\n14. `**`-unpacking in conversions → M5.\n15. ABC ports → P1.\n16. Per-service custom error roots → E1.\n17. Unmapped errors (missing `ERROR_MAP` entries, `ServerError` falling through to INTERNAL) → E2.\n18. Stringly-typed error matching → E3.\n19. Flat `os.getenv` settings → S1.\n20. Hardcoded secret defaults → S2.\n21. Missing `.env.example` → S4.\n22. Manual rollback\u002Fcommit inside `session.begin()` → T3.\n23. Commented-out migration version check → T4.\n24. `docker-entrypoint.sh` help\u002Fcase mismatch → Y1.\n25. Copy-paste residue: foreign service names in settings\u002Fconfigs, wrong `pyproject.toml` name, template READMEs, placeholder test scaffolding (a misnamed `tests\u002Fcontest.py` instead of `conftest.py`, `test_fake.py`, missing test env configuration) → forbidden outright.\n26. Silent Sentry disable on empty DSN → O1.\n27. Transport-mismatched Sentry integrations (gRPC service without `GRPCIntegration`, REST service without transport coverage) → O2.\n28. Hand-copied `sentry.py` noisy-filter without PII scrubbing → O2.\n29. Wrong service name \u002F foreign env prefix in logging config → O3.\n30. Full config dump to startup logs → O3.\n31. Shell-form Docker entrypoint swallowing SIGTERM → Y5.\n32. Background `asyncio` tasks left uncancelled at shutdown → Y2.\n33. Unbounded Prometheus label values (`user_id`, full URLs) → O5.\n\n## Reference Implementations\n\n[ref: #sly-references]\n\nCanonical patterns to imitate when unsure (anonymized; find services in your fleet that exhibit them):\n\n- **Symmetric lifecycle (Y2):** every `connect_*` paired with a close in one `shutdown()`, engine disposed, all upstream clients awaited closed.\n- **Composition root (P2\u002FP4):** `bootstrap.py` `build_provider` for gRPC; lifespan-built `Provider` on `app.state` with `Depends` factories for FastAPI.\n- **Settings discipline (S1\u002FS4):** pydantic-settings with nested groups, discriminated-union infra flavors, committed `.env.example`.\n- **Observability wiring (O1–O3):** Sentry init before clients with transport-matched integrations and a shared `before_send` scrubber; shared logging config with the correct service name; readiness probes that actually check dependencies.\n\n## Conformance Checklist\n\n[ref: #sly-conformance]\n\nA service conforms when ALL of the following hold:\n\n1. Layout: `app\u002F` root; delivery only under `api\u002F` (`api\u002Fgrpc\u002F`, `api\u002Fhttp\u002F`); no top-level `grpc_api\u002F`; isolated modules in `src\u002F`, general toolkits in root `sdk\u002F`.\n2. Imports: import-linter contracts green in CI; `domain\u002F` imports stdlib only; no pb2\u002FORM\u002FHTTP types across boundaries; no reverse imports.\n3. Domain: `@dataclass(frozen=True, slots=True)`; `StrEnum`\u002F`IntEnum` with `auto()`; behavior as model methods; ORM ≠ domain ≠ IO schemas.\n4. Mappings: transport-layer mappers field-by-field; no `from_pb2` on domain; no dict-splat responses; no `**` conversion; FastAPI `response_model` is an IO model.\n5. DI: Protocol ports; `bootstrap.py` composition root; no module-level factory singletons; no per-request service instantiation.\n6. Errors: `ApplicationError` hierarchy in `app\u002Ferrors.py`; one central exhaustive mapping; no stringly-typed matching.\n7. Settings: pydantic-settings root object; discriminated-union infra flavors; no secret defaults; `.env.example` committed; local boot without infra.\n8. Persistence: alembic + UoW + repository ports (stateful) or provably stateless; no manual rollback\u002Fcommit inside `session.begin()`; active migration version check.\n9. Lifecycle: thin `main.py`; truthful `docker-entrypoint.sh`; exec-form entrypoint that propagates SIGTERM (Y5); symmetric total awaited shutdown with an explicit grace period and cancelled background tasks, owned once; fail-fast startup order (sentry → settings → secrets → bootstrap → serve, E4, Y4); engine disposed on shutdown (T4).\n10. Observability: Sentry init before clients with transport-matched integrations and a shared `before_send` scrubber; empty DSN logs a startup warning; logging via shared config with the correct service name; no config dumps to logs (O1–O3). Correlation IDs and metrics per O4\u002FO5; tracing and probe depth per O6\u002FO7.\n\n## Violation Protocol\n\n[ref: #sly-violations]\n\nIf you design, scaffold, or review a service while violating these rulings — or you detect a violation and stay silent — halt immediately, discard the offending output, reload the violated section by its `sly-` anchor, and redo the work correctly. Every detected violation is reported to the user with its ruling id, even when the task's scope is narrower. Repeated bypasses are recorded in Serena memory under `bugs\u002Fproject\u002Fservice_layout_bypass`.\n","# SKILL: Company Service Layout Standard\n\nNormative standard for how every company service MUST look: layout, layering, domain models, mappings, ports\u002FDI, errors, settings, persistence, lifecycle, observability.\nRuling ids: one letter per dimension plus a number — **L** layout, **I** imports, **D** domain models, **M** mappings, **P** ports\u002FDI, **E** errors, **S** settings, **T** persistence\u002Fstorage, **Y** lifecycle, **O** observability.\nNormative keywords (`MUST`, `SHOULD`, `MAY`) follow RFC 2119 \u002F RFC 8174 (by `read-for-comments`).\n\n## Skill Boundary\n\n[ref: #sly-boundary]\n\n- This skill owns the normative STRUCTURE of a service: package layout, import direction and borders, domain model shapes, mapping rules, ports and DI, error taxonomy, settings and secrets, persistence and UoW, entrypoint and lifecycle, observability wiring.\n- This skill does NOT own Python code style (→ `python-lang`), the review workflow and report format (→ `code-review`), API resource design (→ `api-design`), or protobuf schema style (→ `protobuf-lang`). Those load alongside via their own triggers.\n- The standard is anchored to Python services (gRPC and FastAPI). For another language, apply the structural rulings and ask the user about idiomatic mapping.\n\n## Activation Scenarios\n\n[ref: #sly-scenarios]\n\n- On activation the ENTIRE standard is in force. Selective application is FORBIDDEN: in every scenario you check ALL rulings (L\u002FI\u002FD\u002FM\u002FP\u002FE\u002FS\u002FT\u002FY\u002FO; profile-conditional ones per the detected profile) and the WHOLE anti-pattern registry, and you MUST detect and report EVERY violation found, each cited by its ruling id.\n- **Design:** propose service skeletons only per the canonical layout; every proposed element cites the ruling ids it satisfies.\n- **Greenfield development:** scaffold per the profile tree; the Conformance Checklist is the definition of done.\n- **Code review:** check the changeset or service against every ruling and the registry; findings cite ruling ids; the Conformance Checklist is the final gate.\n- The scenario changes ONLY the output shape (proposal, scaffold plan, findings list) — never the set of rules applied.\n\n## Profile Detection\n\n[ref: #sly-profiles]\n\n- Before applying profile-conditional rulings, classify the service at hand. The profile is the decision criterion for what applies — you make this classification yourself.\n- **Profile A — gRPC resource service (stateful):** owns a Postgres DB, serves gRPC.\n- **Profile B — REST gateway \u002F BFF (stateless):** FastAPI over downstream gRPC\u002FHTTP\u002FTemporal, no local DB.\n- The primary classification signal is DB ownership: the service owns a Postgres DB (`migrations\u002F` + `storages\u002F`) → A; no local DB, FastAPI over downstream gRPC\u002FHTTP\u002FTemporal → B. Upstream clients under `services\u002F` appear in both profiles and never decide alone; serving REST alongside gRPC does not change A while the service owns its DB.\n- Legacy non-conformant services exist (3-tier with ORM-as-domain, bespoke adapters without `core\u002F`\u002F`storages\u002F`); the migration target is Profile A — never invent a third profile (L5).\n- Profile-conditional rulings: L4, T1, P4, M4, and the layout trees; L5 applies only to legacy services. Every other ruling applies unconditionally to both profiles.\n- On ambiguous classification, ask the user — never guess the profile.\n- Out of scope of this standard: Temporal workers, shared libraries, GitOps configs.\n\n## Canonical Layout\n\n[ref: #sly-layout]\n\n- The layout exists to keep `domain\u002F` and `core\u002F` unit-testable without infrastructure: ports accept fake implementations, so tests never touch network or DB.\n\n### Package roots\n\n[ref: #sly-package-roots]\n\n- `app\u002F` — the application code (L1, MUST).\n- `src\u002F\u003Cmodule>\u002F` — isolated project-specific component packages (e.g. a client module for some API), at project root. One-way isolation: `app\u002F` MAY import from `src\u002F`; `src\u002F` MUST NEVER import from `app\u002F` (enforced, I4).\n- `sdk\u002F\u003Cprovider>\u002F` — general, extractable third-party\u002Fprovider toolkits, at project root (L3). `sdk\u002F` imports nothing project-side. The split: `src\u002F` is project-specific, `sdk\u002F` is general\u002Freusable.\n\n### Profile A tree\n\n[ref: #sly-profile-a-tree]\n\n```text\n\u003Cservice>\u002F\n├── app\u002F\n│   ├── domain\u002F                 # pure: frozen dataclasses + StrEnum, stdlib imports only\n│   ├── core\u002F                   # use cases + ports (the hexagon)\n│   │   ├── \u003Caggregate>.py      #   business logic over ports\n│   │   ├── repo.py             #   @runtime_checkable Protocol repos (one per aggregate)\n│   │   ├── storage.py          #   Storage Protocol aggregating the repos\n│   │   └── transaction_manager.py  # TransactionManager Protocol (UoW)\n│   ├── storages\u002F\u003Cbackend>\u002F     # persistence adapters (postgres\u002F, object storage, ...); skip if stateless\n│   ├── services\u002F               # outbound adapters: grpc\u002F\u003Cupstream>\u002F, http\u002F\u003Cthirdparty>\u002F (only if used)\n│   ├── api\u002F                    # the ONLY delivery package\n│   │   ├── errors\u002F             # edge concerns defined ONCE, shared by all transports\n│   │   ├── health\u002F\n│   │   ├── auth\u002F\n│   │   ├── grpc\u002F\u003Centity>\u002F      # servicers.py (thin) + models.py (view assembly) + views.py (pb2 serializers)\n│   │   │   └── interceptors\u002F   # logging, exception mapping\n│   │   └── http\u002F               # only when the service truly serves REST too\n│   ├── bootstrap.py            # composition root: build_provider(config)\n│   ├── server.py               # entrypoint: sentry, settings, secrets, bootstrap, serve; owns shutdown\n│   ├── settings.py             # pydantic-settings; grows into settings\u002F package per concern\n│   ├── secrets.py              # vault resolution, fail-fast at startup\n│   ├── errors.py               # ApplicationError hierarchy\n│   └── version.py              # single version source\n├── src\u002F\u003Cmodule>\u002F               # isolated project-specific modules (optional)\n├── sdk\u002F\u003Cprovider>\u002F             # general provider toolkits (optional)\n├── migrations\u002F                 # alembic (only when the service owns a DB)\n├── tests\u002F\n└── etc\u002F                        # lint configs\n```\n\n### Profile B tree\n\n[ref: #sly-profile-b-tree]\n\nSame skeleton minus `storages\u002F` and `migrations\u002F` (stateless, T1); `app\u002Fservices\u002Fgrpc|http\u002F\u003Cupstream>\u002F` is MANDATORY and carries the anti-corruption mappers (`mappers.py` next to the client code); delivery is `app\u002Fapi\u002Fhttp\u002Fv1\u002F\u003Cdomain>\u002F{handlers,schemas,models}.py` — handlers thin, `schemas.py` = input contracts, `models.py` = output contracts. Note: `models.py` is per-transport vocabulary — view assembly in Profile A gRPC, the output contract in Profile B REST.\n\n### Naming rulings\n\n[ref: #sly-naming-rulings]\n\n- `api\u002F` is the only legal delivery package; a top-level `grpc_api\u002F` is FORBIDDEN (L2, MUST NOT) — `\u003Cservice>\u002Fgrpc_api\u002F` at the repository root is the canonical violation.\n- Transports are siblings inside `api\u002F`: `api\u002Fgrpc\u002F`, `api\u002Fhttp\u002F`; shared edge concerns live once at the `api\u002F` root (L2).\n- One backend = one technology-named adapter package (`storages\u002Fpostgres\u002F`, never ORM-named) (L3, T1).\n- Profile B keeps the Profile A skeleton minus `storages\u002F` (stateless); `services\u002Fgrpc|http\u002F\u003Cupstream>\u002F` is obligatory for upstream calls (L4, MUST).\n- Legacy non-conformant services migrate toward Profile A; a third profile is MUST NOT (L5).\n\n## Rulings\n\n[ref: #sly-rulings]\n\n### Import direction and borders (I1–I4)\n\n[ref: #sly-ruling-imports]\n\n- **I1 (MUST)** Import direction: `api\u002F → core\u002F → domain\u002F`; adapters (`storages\u002F`, `services\u002F`) import `core\u002F` ports and `domain\u002F` models; `domain\u002F` imports stdlib ONLY. `app\u002F → src\u002F` is one-way; `sdk\u002F` imports nothing project-side.\n- **I2 (MUST)** Anti-corruption: pb2 \u002F ORM \u002F HTTP-client types live and convert only at their own boundary — pb2 in `api\u002Fgrpc\u002F\u003Centity>\u002Fviews.py` and `services\u002Fgrpc\u002F\u003Cupstream>\u002Fmappers.py`, ORM in `storages\u002F\u003Cbackend>\u002F`, HTTP types in `services\u002Fhttp\u002F`. A pb2 import inside `domain\u002F` is a blocking defect.\n- **I3 (MUST NOT)** Reverse imports: `services\u002F` never imports `api\u002F`; `core\u002F` never imports adapters.\n- **I4 (MUST)** Enforcement: import-linter in `pyproject.toml` `[tool.importlinter]` — `root_packages`, an exhaustive layered contract (a forgotten package = hard failure), `forbidden` contracts (`src ⇏ app`, `sdk ⇏ app, src`), `independence` contracts, forbidden external modules per layer; Ruff TID251 bans configured named imports (layer direction stays with import-linter); a pre-commit hook runs `lint-imports`. Reference shape:\n\n```toml\n[tool.importlinter]\nroot_packages = [\"app\", \"src\", \"sdk\"]\ninclude_external_packages = true\n\n[[tool.importlinter.contracts]]\nname = \"Layered: delivery and adapters over core over domain\"\ntype = \"layers\"\nlayers = [\"api | storages | services\", \"core\", \"domain\"]\ncontainers = [\"app\"]\nexhaustive = true\nexhaustive_ignores = [\"bootstrap\", \"server\", \"settings\", \"secrets\", \"errors\", \"version\"]\n\n[[tool.importlinter.contracts]]\nname = \"adapters are independent\"\ntype = \"independence\"\nmodules = [\"app.storages\", \"app.services\"]\n\n[[tool.importlinter.contracts]]\nname = \"src never imports app\"\ntype = \"forbidden\"\nsource_modules = [\"src\"]\nforbidden_modules = [\"app\"]\n\n[[tool.importlinter.contracts]]\nname = \"sdk imports nothing project-side\"\ntype = \"forbidden\"\nsource_modules = [\"sdk\"]\nforbidden_modules = [\"app\", \"src\"]\n\n[[tool.importlinter.contracts]]\nname = \"domain imports stdlib only\"\ntype = \"forbidden\"\nsource_modules = [\"app.domain\"]\nforbidden_modules = [\"grpc\", \"sqlalchemy\", \"httpx\", \"fastapi\", \"pydantic\"]\n```\n\n### Domain models and enums (D1–D4)\n\n[ref: #sly-ruling-domain-models]\n\n- **D1 (MUST)** Domain models are `@dataclass(frozen=True, slots=True)` — frozen AND slots by default, always. Mutability is a strict exception with a documented reason in the docstring; the exception covers data-carrier shapes only — business-state transitions still follow D3.\n- **D2 (MUST)** Text constants → `StrEnum`, numeric → `IntEnum`, members ALWAYS via `auto()`. Plain `str` statuses and plain `Enum` are MUST NOT.\n- **D3 (MUST)** State transitions are domain-object methods returning new instances (`dataclasses.replace`); external mutation from the service layer is MUST NOT. No `**` kwargs wiring in model conversions — field-by-field slot-to-slot only.\n- **D4 (MUST)** Three model families stay separate forever: ORM models (persistence) ≠ domain models (business) ≠ HTTP\u002Fpydantic IO schemas (REST validation). ORM-as-domain is MUST NOT.\n\n### Mappings (M1–M5)\n\n[ref: #sly-ruling-mappings]\n\n- **M1 (MUST)** Inbound pb2→domain: mapper functions in the transport layer build domain objects field-by-field. `from_pb2` ON domain models is MUST NOT (violates I2).\n- **M2 (MUST)** Outbound domain→pb2: `to_pb2`\u002F`views.py` helpers in the transport layer; handlers never build pb2 inline; the dict-splat response pattern is MUST NOT.\n- **M3 (MUST)** ORM↔domain: explicit mapper functions (`orm_to_domain` \u002F `domain_to_orm`) in a mapper module inside `storages\u002F\u003Cbackend>\u002F`; `to_domain()` on the ORM model is MUST NOT — the dependency stays one-directional and visible.\n- **M4 (MUST)** Profile B: `schemas.py` (input) validates and converts to domain via an explicit api-layer mapper; `models.py` (output) is built from domain field-by-field; domain objects are NEVER returned to FastAPI directly; `response_model` is always an IO model.\n- **M5 (MUST NOT)** `**`-unpacking in any conversion; `model_dump()` is legal only for wire serialization at the boundary itself. Automated mapping libraries (introspection-based, mapstruct-style) are MUST NOT: they break silently on field renames, while explicit field-by-field mapping is caught by mypy and IDE refactoring.\n\n### Ports and DI (P1–P4)\n\n[ref: #sly-ruling-ports-di]\n\n- **P1 (MUST)** Ports are `typing.Protocol` with `@runtime_checkable`. ABC ports are MUST NOT.\n- **P2 (MUST)** Composition root: `app\u002Fbootstrap.py` builds a `Provider` (storage + clients + sdks) at startup and threads it into servicers\u002Fhandlers via constructors. Module-level singletons (factory globals, stub registries, service-locator globals) are MUST NOT. The only sanctioned global is the read-only `config`. DI containers\u002Fframeworks (`punq`, `dependency-injector`) are MUST NOT without explicit user approval — manual constructor injection is the default.\n- **P3 (MUST NOT)** Per-request service instantiation. Services are built once in bootstrap.\n- **P4 (MUST)** Profile B: the `Provider` is built in the FastAPI lifespan, stored on `app.state`, threaded via `Depends` factories. `Depends` factories live in one `dependencies.py` module per transport package — never inside routes or bootstrap — to avoid circular imports.\n- **P5 (MUST)** Injected dependencies live at least as long as their consumers: singletons (config, connection pools, stateless services) NEVER receive per-request objects (DB sessions, transactions). A short-lived object captured by a long-lived one is a captive dependency and a blocking defect.\n\n### Errors (E1–E4)\n\n[ref: #sly-ruling-errors]\n\n- **E1 (MUST)** One hierarchy in `app\u002Ferrors.py`: `ApplicationError` root → `ClientError`\u002F`ServerError`; class names end with `Error`. Per-service custom roots are MUST NOT. Few types; a new class exists only with differentiated handling.\n- **E2 (MUST)** One central mapping place: gRPC interceptor \u002F FastAPI exception handler with an EXHAUSTIVE `ERROR_MAP`; an unmapped error is a bug. Local try\u002Fexcept only where behavior genuinely differs. The mapping distinguishes transient from permanent failures: a permanent failure gets a precise status code so the client knows NOT to retry.\n- **E3 (MUST)** Errors carry a reason enum serialized in exactly one place; stringly-typed matching and parsing `grpc.detail()` strings are MUST NOT. On the wire the reason travels as gRPC Rich Error Details (`ErrorInfo`), never packed into the message string.\n- **E4 (MUST)** Crash-loud at startup: config\u002Fsecrets\u002Fconnections fail loudly; no cleanup theater before the process starts.\n\n### Settings and secrets (S1–S4)\n\n[ref: #sly-ruling-settings]\n\n- **S1 (MUST)** pydantic-settings, one root `Settings` object; config is formed once at initialization from a single source. Swappable infra flavors are DISCRIMINATED UNIONS selected by a `type` discriminant. Flat `os.getenv` modules are MUST NOT. The root settings declare `SettingsConfigDict(env_prefix=\"\u003CSERVICE>_\", extra=\"ignore\")`: one env namespace per service, and unknown env vars are TOLERATED — orchestrators inject their own variables, `extra=\"forbid\"` would break deploys. Reference shape:\n\n```python\nclass VaultEnvConfig(BaseSettings):\n    type: Literal[\"env\"]  # every variant declares its discriminant\n    # fields...\n\nVaultConfig = Annotated[\n    VaultEnvConfig | VaultKubernetesConfig | VaultTokenConfig | VaultJWTConfig,  # Python ≥3.10 union syntax\n    Field(discriminator=\"type\"),\n]\n```\n\n- **S2 (MUST)** No defaults for secrets\u002Fpasswords\u002Ftokens, ever; required vars crash at startup naming the variable. Hardcoded vault tokens \u002F encryption keys are MUST NOT. Secret-typed fields use `pydantic.SecretStr` so values stay masked in logs and tracebacks.\n- **S3 (MUST)** `secrets.py` resolves vault secrets at startup BEFORE any client connects; failure = the process does not start.\n- **S4 (MUST)** `.env.example` is committed and documents every variable; the service boots locally without infrastructure (literals \u002F no-op implementations); dev opt-in is always explicit.\n\n### Persistence and UoW (T1–T4)\n\n[ref: #sly-ruling-persistence]\n\n- **T1 (MUST)** A stateful Profile-A service has alembic migrations + `storages\u002Fpostgres\u002F`; a stateless service MUST NOT grow a local DB. Multi-backend is legal — one package per backend.\n- **T2 (MUST)** UoW via the `TransactionManager` Protocol (`async with tm.transaction() as storage:`) WITH mandatory per-aggregate repository Protocols (`core\u002Frepo.py`). Handler-passed sessions are MUST NOT. A single `AsyncEngine` is created once at startup; the session factory is scoped per transaction; the UoW context manager MUST guarantee session closure even on exceptions.\n- **T3 (MUST NOT)** Manual `rollback()`\u002F`commit()` inside the `with session.begin():` context manager — the context manager owns commit\u002Frollback.\n- **T4 (MUST)** The migration version check is ACTIVE at startup and fails fast BEFORE serving traffic — the DB revision (`alembic.runtime.migration.MigrationContext.get_current_revision()`) is compared with the alembic head revision (`ScriptDirectory.get_current_head()`), and any mismatch aborts startup (a commented-out check is MUST NOT). On shutdown the engine is disposed (`await engine.dispose()`) so pooled idle connections do not leak.\n\n### Entrypoint and lifecycle (Y1–Y5)\n\n[ref: #sly-ruling-lifecycle]\n\n- **Y1 (MUST)** `main.py` is a thin entry, no CLI magic; `docker-entrypoint.sh` help text tells the truth — a help\u002Fcase mismatch is MUST NOT.\n- **Y2 (MUST)** Symmetric lifecycle: every `connect_*` has a paired close registered in `shutdown()`; shutdown is total and awaited (engine, channels, Temporal clients, HTTP sessions) and drains in-flight work with an explicit grace period (`server.stop(grace=N)`) before force-terminating. Long-running background `asyncio` tasks MUST receive cancellation (`asyncio.Event` \u002F `task.cancel()`) during shutdown and MUST be awaited there. No-op shutdown is MUST NOT.\n- **Y3 (MUST)** Single teardown owner: shutdown lives once in `server.py`\u002Flifespan; servicer `on_exit` teardown hooks are MUST NOT.\n- **Y4 (MUST)** Startup order: sentry → settings → secrets (vault) → bootstrap (`build_provider`) → serve; any failure before serve = the process does not start.\n- **Y5 (MUST)** Signal propagation: the container entrypoint uses the `exec` form (`ENTRYPOINT [\"python\", \"-m\", \"app.main\"]`) so the Python process receives `SIGTERM` directly — a shell-wrapped entrypoint swallows signals and the container dies by kill timeout, which is MUST NOT; an init shim (`tini`) is REQUIRED when the app is not PID 1.\n\n### Observability (O1–O7)\n\n[ref: #sly-ruling-observability]\n\n- **O1 (MUST)** Sentry is initialized at startup before clients connect (see Y4); DSN comes from settings with no hardcoded default. An empty DSN is ALLOWED for development, but startup MUST log a warning that Sentry is not initialized; silent disable is MUST NOT.\n- **O2 (MUST)** Sentry integrations match the transport: async gRPC services use `AsyncioIntegration` + `LoggingIntegration` + `GRPCIntegration`; REST services use `FastApiIntegration` + `LoggingIntegration`. PII is off globally (`send_default_pii=False` — no IPs, cookies, or POST bodies) AND `before_send` is a shared scrubber from a shared library; hand-copied per-service `sentry.py` filters are MUST NOT.\n- **O3 (MUST)** Logging goes through one shared configuration (from the org's shared logging library): plain + JSON formatters, level and format from settings, static fields (`service`, `version`, `environment`, k8s metadata) with the correct service name. Dumping the full config to logs at startup is MUST NOT. Copy-pasted logging config with a foreign env prefix or wrong service name is MUST NOT.\n- **O4 (SHOULD)** Request\u002Fcorrelation IDs propagated across gRPC metadata \u002F HTTP headers when a flow needs cross-service tracing — the W3C `traceparent` header is the canonical carrier; extraction\u002Finjection happens in transport middleware (FastAPI middleware, gRPC client\u002Fserver interceptors), never in business logic.\n- **O5 (SHOULD)** Prometheus metrics endpoint — optional but desirable. When present, metric names follow `namespace_subsystem_name_unit` (e.g. `grpc_server_duration_seconds`) and label values MUST be cardinality-bounded (`endpoint`, `method`, `status_code`); unbounded label values (`user_id`, full URLs, request parameters) are MUST NOT — high cardinality degrades Prometheus itself.\n- **O6 (out of scope)** Distributed tracing is not regulated by this standard; it is a separate per-team decision.\n- **O7 (out of scope)** Health-probe semantics are governed outside this standard; this standard only requires that the endpoints exist (gRPC services expose `startup`\u002F`readiness`\u002F`liveness` via grpc_health.v1, REST services `\u002Flivez` + `\u002Freadyz`); dependency-check depth is a per-team decision — with one hard warning: liveness MUST stay shallow (process alive only), because a deep liveness check turns a transient dependency outage into an orchestrator restart loop; dependency depth belongs to readiness.\n\nRationale: observability scaffolding is the most copy-pasted code in a service fleet; the fixes are cheap and uniform, while tracing and probe depth are separate per-team activities.\n\n## Anti-Pattern Registry\n\n[ref: #sly-anti-patterns]\n\nBanned patterns, each with the ruling that forbids it:\n\n1. Module-global mutable factories\u002Fregistries as DI (factory singletons, stub registries, service-locator globals) → composition root (P2).\n2. Per-request service instantiation → P3.\n3. Asymmetric\u002Fno-op shutdown → Y2.\n4. Servicer `on_exit` teardown → Y3.\n5. pb2 imports in `domain\u002F` → I2.\n6. Reverse imports `services\u002F` → `api\u002F` → I3.\n7. SQLAlchemy in business modules → I2.\n8. Mutable domain dataclasses as default → D1.\n9. Plain `str`\u002Fplain `Enum` statuses → D2.\n10. Domain mutation in the service layer → D3.\n11. `from_pb2` on domain models → M1.\n12. Dict-splat pb2 responses → M2.\n13. Domain objects as FastAPI responses → M4.\n14. `**`-unpacking in conversions → M5.\n15. ABC ports → P1.\n16. Per-service custom error roots → E1.\n17. Unmapped errors (missing `ERROR_MAP` entries, `ServerError` falling through to INTERNAL) → E2.\n18. Stringly-typed error matching → E3.\n19. Flat `os.getenv` settings → S1.\n20. Hardcoded secret defaults → S2.\n21. Missing `.env.example` → S4.\n22. Manual rollback\u002Fcommit inside `session.begin()` → T3.\n23. Commented-out migration version check → T4.\n24. `docker-entrypoint.sh` help\u002Fcase mismatch → Y1.\n25. Copy-paste residue: foreign service names in settings\u002Fconfigs, wrong `pyproject.toml` name, template READMEs, placeholder test scaffolding (a misnamed `tests\u002Fcontest.py` instead of `conftest.py`, `test_fake.py`, missing test env configuration) → forbidden outright.\n26. Silent Sentry disable on empty DSN → O1.\n27. Transport-mismatched Sentry integrations (gRPC service without `GRPCIntegration`, REST service without transport coverage) → O2.\n28. Hand-copied `sentry.py` noisy-filter without PII scrubbing → O2.\n29. Wrong service name \u002F foreign env prefix in logging config → O3.\n30. Full config dump to startup logs → O3.\n31. Shell-form Docker entrypoint swallowing SIGTERM → Y5.\n32. Background `asyncio` tasks left uncancelled at shutdown → Y2.\n33. Unbounded Prometheus label values (`user_id`, full URLs) → O5.\n\n## Reference Implementations\n\n[ref: #sly-references]\n\nCanonical patterns to imitate when unsure (anonymized; find services in your fleet that exhibit them):\n\n- **Symmetric lifecycle (Y2):** every `connect_*` paired with a close in one `shutdown()`, engine disposed, all upstream clients awaited closed.\n- **Composition root (P2\u002FP4):** `bootstrap.py` `build_provider` for gRPC; lifespan-built `Provider` on `app.state` with `Depends` factories for FastAPI.\n- **Settings discipline (S1\u002FS4):** pydantic-settings with nested groups, discriminated-union infra flavors, committed `.env.example`.\n- **Observability wiring (O1–O3):** Sentry init before clients with transport-matched integrations and a shared `before_send` scrubber; shared logging config with the correct service name; readiness probes that actually check dependencies.\n\n## Conformance Checklist\n\n[ref: #sly-conformance]\n\nA service conforms when ALL of the following hold:\n\n1. Layout: `app\u002F` root; delivery only under `api\u002F` (`api\u002Fgrpc\u002F`, `api\u002Fhttp\u002F`); no top-level `grpc_api\u002F`; isolated modules in `src\u002F`, general toolkits in root `sdk\u002F`.\n2. Imports: import-linter contracts green in CI; `domain\u002F` imports stdlib only; no pb2\u002FORM\u002FHTTP types across boundaries; no reverse imports.\n3. Domain: `@dataclass(frozen=True, slots=True)`; `StrEnum`\u002F`IntEnum` with `auto()`; behavior as model methods; ORM ≠ domain ≠ IO schemas.\n4. Mappings: transport-layer mappers field-by-field; no `from_pb2` on domain; no dict-splat responses; no `**` conversion; FastAPI `response_model` is an IO model.\n5. DI: Protocol ports; `bootstrap.py` composition root; no module-level factory singletons; no per-request service instantiation.\n6. Errors: `ApplicationError` hierarchy in `app\u002Ferrors.py`; one central exhaustive mapping; no stringly-typed matching.\n7. Settings: pydantic-settings root object; discriminated-union infra flavors; no secret defaults; `.env.example` committed; local boot without infra.\n8. Persistence: alembic + UoW + repository ports (stateful) or provably stateless; no manual rollback\u002Fcommit inside `session.begin()`; active migration version check.\n9. Lifecycle: thin `main.py`; truthful `docker-entrypoint.sh`; exec-form entrypoint that propagates SIGTERM (Y5); symmetric total awaited shutdown with an explicit grace period and cancelled background tasks, owned once; fail-fast startup order (sentry → settings → secrets → bootstrap → serve, E4, Y4); engine disposed on shutdown (T4).\n10. Observability: Sentry init before clients with transport-matched integrations and a shared `before_send` scrubber; empty DSN logs a startup warning; logging via shared config with the correct service name; no config dumps to logs (O1–O3). Correlation IDs and metrics per O4\u002FO5; tracing and probe depth per O6\u002FO7.\n\n## Violation Protocol\n\n[ref: #sly-violations]\n\nIf you design, scaffold, or review a service while violating these rulings — or you detect a violation and stay silent — halt immediately, discard the offending output, reload the violated section by its `sly-` anchor, and redo the work correctly. Every detected violation is reported to the user with its ruling id, even when the task's scope is narrower. Repeated bypasses are recorded in Serena memory under `bugs\u002Fproject\u002Fservice_layout_bypass`.\n",{"name":5,"runtime":24,"version":25,"triggers":26,"description":7},true,"0.1.0",{"reason":27,"request":28},"Design, greenfield development, and review of company services must conform to the Company Service Layout Standard.","service layout, service structure, структура сервиса, лейаут сервиса, как должен выглядеть сервис, новый сервис, создай сервис, создаём сервис, проектируем сервис, спроектируй сервис, проектирование сервиса, каркас сервиса, service scaffold, scaffolding, greenfield service, service design, company service standard, service standard, ревью сервиса, проверь сервис, service review, layout review, composition root, порты и адаптеры, hexagonal service","main","7da8c355f6e99dcb88d8bb9f6ff27b3cb35bae47","_on_demand\u002Fservice-layout",0,"https:\u002F\u002Fgithub.com\u002Fkalaverin\u002Fskills","https:\u002F\u002Fgithub.com\u002Fkalaverin","2026-11-15 01:37:57",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":24},[38,41,44],{"tool":39,"command":40},"npx","npx skills add kalaverin\u002Fskills --skill service-layout",{"tool":42,"command":43},"bunx","bunx skills add kalaverin\u002Fskills --skill service-layout",{"tool":45,"command":46},"pnpm","pnpm dlx skills add kalaverin\u002Fskills --skill service-layout","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fkalaverin\u002Fskills\u002Fblob\u002Fmain\u002F_on_demand\u002Fservice-layout\u002FSKILL.md",[49],{"path":50,"resourceType":51,"resourceTypeDesc":52,"sizeBytes":53,"sourceHtmlUrl":54},"README.md","REFERENCE","参考文档",1327,"https:\u002F\u002Fgithub.com\u002Fkalaverin\u002Fskills\u002Fblob\u002Fmain\u002F_on_demand\u002Fservice-layout\u002FREADME.md",[56,63,70,77,84,91],{"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},"01M786R9KK7RP1J8EB7X9TC9KR","todo-protocol","Mandatory protocol for using the SetTodoList tool. Governs when to create a todo list, how to update it without violating immutability rules, how to synchronize item status after every tool call, and the forbidden mutations. Always active.","https:\u002F\u002Fgithub.com\u002Fkalaverin\u002Fskills\u002Fblob\u002Fmain\u002Ftodo-protocol\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},"01M786QZTC43FBK3A251NTY62Y","subagents-protocol","Mandatory protocol for delegating work to built-in subagents (coder, explore, plan), also called our bots by users. Always active. Owns the context-hygiene delegation test (material vs answer, cost balance, warm-instance reuse), launch parameters (mandatory explicit `model`), the single-source model-selection table, answer budgets, degradation handling, the launch checklist, and the role library for delegated review\u002Faudit with intent routing (`references\u002Froles.md`).","https:\u002F\u002Fgithub.com\u002Fkalaverin\u002Fskills\u002Fblob\u002Fmain\u002Fsubagents-protocol\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},"01M786QSXFDM550NCC4PQXN26X","serena-protocol","MANDATORY skill for Serena (MCP) memory, knowledge base, and symbolic code exploration operations. Use whenever the agent needs to: read or write Serena memories, mutate or persist memory, explore code via symbolic MCP tools, resolve contradictions in stored knowledge, or follow memory metadata, naming, and routing conventions.","https:\u002F\u002Fgithub.com\u002Fkalaverin\u002Fskills\u002Fblob\u002Fmain\u002Fserena-protocol\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},"01M786QMXA58XD5DJZ2AZER5ZP","read-for-comments","Mandatory local standards library and archive. Before fetching any standard from the internet, the agent MUST check the Serena `standard\u002F` archive and this skill's `references\u002F` seed; after ANY standard-body download, the agent MUST archive it per the event-bound Archival Rule. Governs standard lookup, fetch, archival, and the family and full-body rules.","https:\u002F\u002Fgithub.com\u002Fkalaverin\u002Fskills\u002Fblob\u002Fmain\u002Fread-for-comments\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},"01M786QD59A2R2JK1NJTK7MADP","python-lang","MANDATORY skill for Python code. Use when writing, editing, refactoring, or reviewing Python files, modules, packages, classes, functions, type annotations, imports, exceptions, comprehensions, decorators, or docstrings. Enforces Google Python Style Guide and a mandatory, unconditional Ruff format+check pipeline scoped strictly to the agent's own changes.","https:\u002F\u002Fgithub.com\u002Fkalaverin\u002Fskills\u002Fblob\u002Fmain\u002Fpython-lang\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M786Q683RHDC93NWABY7XKQN","preflight-checklist","Mandatory session-initialization closer and Startup Gate audit. Always loaded. Runs EXACTLY ONCE at session start, after all skill loading completes: verifies Startup Gate completion with evidence (mirror sync, forced import, discovery, activation, memory priming, MCP declaration, think block), runs dynamic session checks derived from the active skill set (mode states, delegation readiness), and reports a compact evidence-backed verdict table to the user before the first task output. Any FAIL is fixed before proceeding.","https:\u002F\u002Fgithub.com\u002Fkalaverin\u002Fskills\u002Fblob\u002Fmain\u002Fpreflight-checklist\u002FSKILL.md",[],[]]