Coverage for app / common / settings.py: 98%
81 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1from functools import lru_cache
2from enum import Enum
3from pydantic_settings import BaseSettings
4from pathlib import Path
7class AppEnv(str, Enum):
8 LOCAL = "local"
9 DEV = "dev"
10 STAGING = "staging"
11 PROD = "prod"
14class Settings(BaseSettings):
15 # General app
16 APP_NAME: str
17 APP_ENV: AppEnv = AppEnv.LOCAL
18 APP_VERSION: str
19 LOG_LEVEL: str = "INFO"
21 # Postgres
22 POSTGRES_USER: str
23 POSTGRES_PASSWORD: str
24 POSTGRES_HOST: str
25 POSTGRES_DB: str
27 # Internal services
28 SVC_AI_URL: str = "http://modules-svc-ai-1:5000"
30 # Internal service-to-service auth (audience-bound short-lived JWTs).
31 # svc-core verifies tokens minted by svc-bff (aud=svc-core) and mints its
32 # own tokens for svc-ai (aud=svc-ai). When the secret is unset, verification
33 # falls back to trusting forwarded identity headers (legacy / migration).
34 INTERNAL_JWT_SECRET: str | None = None
35 # Previous secret, accepted during a rotation overlap (zero-downtime).
36 INTERNAL_JWT_SECRET_PREVIOUS: str | None = None
37 INTERNAL_JWT_ISSUER: str = "svc-core"
38 INTERNAL_JWT_VERIFY_AUDIENCE: str = "svc-core" # tokens we accept
39 INTERNAL_JWT_AI_AUDIENCE: str = "svc-ai" # tokens we mint for svc-ai
40 INTERNAL_JWT_TTL: int = 120 # seconds
42 # CORS. svc-core is an *internal* service reached only over the private
43 # backend network (svc-bff -> svc-core, server to server); no browser calls
44 # it directly, so the allowlist is empty by default. This is an escape hatch
45 # only — comma-separated browser origins, should a deployment ever expose it.
46 CORS_ALLOWED_ORIGINS: str = ""
48 # Neo4j
49 NEO4J_URI: str = "bolt://neo4j:7687"
50 NEO4J_AUTH: str = "neo4j/chainr_dev"
52 # Dashboard feed widgets (weather, RSS). svc-core reaches the internet for
53 # these on the dedicated feed-egress-network. Comma-separated domains
54 # restrict which publishers may be fetched; empty means any public host is
55 # allowed (private/loopback/link-local addresses are always refused).
56 FEED_ALLOWED_DOMAINS: str = ""
57 #: The built-in News repository: provisioned, and crawled hourly while an
58 #: agent has it granted. Off, it is neither provisioned nor crawled — the
59 #: platform then makes no outbound fetches no user asked for.
60 BUILT_IN_NEWS_ENABLED: bool = True
61 #: Every other built-in repository read from a publisher's website
62 #: (``system_resources.knowledge``): provisioned, and crawled while an
63 #: agent has it granted. Off, as for News. Knowledge CHAIN-R writes itself
64 #: fetches nothing and has no switch.
65 BUILT_IN_WEB_KNOWLEDGE_ENABLED: bool = True
66 #: Scenario runs (``app/services/scenarios``, ``/app/scenario-runs``):
67 #: scripted agent chats a developer runs and exports for review. Off by
68 #: default, so no deployment has them unless it says so; the deployed dev
69 #: host runs as ``prod``, so this, not ``APP_ENV``, is what turns them on
70 #: there (SSM ``features/``). Each route also needs the ``developer``
71 #: platform role. See docs/guides/scenario-runs.md.
72 SCENARIO_RUNS_ENABLED: bool = False
73 #: Swarms (``app/services/swarms``, ``/app/swarms``): teams of agents in
74 #: a shape, sent on a long task under a budget and a time cap. Off by
75 #: default until verified live, switched on as scenario runs are (SSM
76 #: ``features/``). See docs/guides/swarms.md.
77 SWARMS_ENABLED: bool = False
78 #: The most one swarm run may be given to spend, whatever its dispatch
79 #: asks for.
80 SWARM_MAX_BUDGET_USD: float = 25.0
82 # Market data for the dashboard `market` widget. No properly-licensed
83 # keyless source exists for equities, so this needs a provider key. Without
84 # one the widget still saves — it renders a setup prompt instead of data.
85 MARKET_DATA_PROVIDER: str = "alphavantage" # alphavantage | finnhub
86 MARKET_DATA_API_KEY: str = ""
88 # Background scheduler. Runs in svc-core's own process, with one replica
89 # elected leader by a Postgres advisory lock — see
90 # app/services/scheduler/runner.py for why it is not its own container.
91 # Disabled in tests, where a loop ticking against a mock session would be
92 # noise; the opportunistic paths (refresh-on-view, purge-on-read) remain
93 # in place wherever it is off.
94 SCHEDULER_ENABLED: bool = True
95 #: How often the loop wakes. Bounds every job's resolution: a job asking
96 #: for 10s on a 60s tick runs every 60s, and the status page says so.
97 SCHEDULER_TICK_SECONDS: int = 60
98 #: Days a background_events row (a tile refreshed, a site re-crawled) is
99 #: kept before the ``background_retention`` job deletes it. A tile on a
100 #: 60-second interval writes 1,440 rows a day, so this is what bounds the
101 #: table. 0 keeps them forever.
102 BACKGROUND_EVENT_RETENTION_DAYS: int = 30
103 #: How long the retrieval record keeps a person's words — the request as
104 #: searched, the gaps, the files named (``knowledge_turns``); the counts
105 #: stay (``KnowledgeTurnRetentionJob``).
106 KNOWLEDGE_TURN_TEXT_RETENTION_DAYS: int = 180
108 # Platform benchmark (app/services/evaluation/benchmark.py): CHAINR Bot
109 # and each maker's strongest built-in model, scored on every gold dataset by the
110 # ``platform_benchmark`` job. It runs per deploy — the bot again on each
111 # one, a model only when its result on the current dataset version and
112 # judge is missing — so it needs to know which deploy this is.
113 #: The image tag this process was deployed from. Set by the ECR compose
114 #: overlay (docker-compose.ecr.yml); empty locally and in CI, where the
115 #: benchmark therefore never runs.
116 DEPLOY_ID: str = ""
117 #: Off switch. On, it still runs only where DEPLOY_ID is set.
118 PLATFORM_BENCHMARK_ENABLED: bool = True
119 #: The most the benchmark may spend per calendar month (UTC), in US
120 #: dollars, measured; it resets on the 1st. A target's round starts only
121 #: when what it cost last time fits what is left, and nothing starts once
122 #: it is spent (the run in progress finishes). What waits runs in next
123 #: month's round, on whatever is live then — never as a backlog. A month
124 #: rather than a rolling 30 days, which re-spent each dollar the moment it
125 #: aged out; and not per deploy, which grew with how often one deployed.
126 PLATFORM_BENCHMARK_BUDGET_USD: float = 50.0
127 #: Days after which a built-in model's result is measured again, though
128 #: nothing about the dataset or the judge changed: a provider can change
129 #: what an unversioned name (``claude-sonnet-5``) answers with. A pinned
130 #: version — a dated snapshot (``claude-haiku-4-5-20251001``) or a
131 #: versioned Bedrock id (svc-ai's ``version_pinned``) — cannot change and
132 #: is never re-run for age. 0: never.
133 PLATFORM_BENCHMARK_MODEL_REFRESH_DAYS: int = 30
134 #: The models that may grade benchmark runs, first choice first, as
135 #: comma-separated "provider/model": the first the catalogue has available
136 #: grades. Every score is relative to its judge, so a change of judge
137 #: re-runs every baseline. Not the deployment's default model: that is the
138 #: model CHAINR Bot runs on, so the bot would grade itself. Sonnet 4.6 is
139 #: strong, and — unlike the generation-5 Claude models — still takes
140 #: temperature 0, so a verdict repeats. gpt-oss-120b grades on a Bedrock
141 #: deployment without Anthropic access (BEDROCK_MODEL_ACCESS), where the
142 #: default is Qwen3 235B. None available: the default model, with a
143 #: warning, and every result names the judge that graded it.
144 PLATFORM_BENCHMARK_JUDGE: str = "anthropic/claude-sonnet-4-6,openai/gpt-oss-120b"
146 #: A native sibling for agents whose model cannot decode a reply to a
147 #: schema (Claude 5.x on Bedrock): the same maker's model, in the same
148 #: region, that can, makes the structured system steps of their turns —
149 #: triage, planning, retrieval's judging, the quality check, memory
150 #: extraction (app/services/native_sibling.py). Off by default: the only
151 #: such sibling in the EU is Claude Haiku 4.5, about ten times Haiku 5.5's
152 #: price per token, whose Bedrock end of life may now come at any time
153 #: (listed as no sooner than 16 October 2026). Changing it re-runs
154 #: CHAINR Bot's benchmark (it changes what shapes the bot's answers).
155 NATIVE_STRUCTURED_SIBLING: bool = False
157 # Platform allowances (app/services/budgets/allowance.py): what CHAIN-R
158 # lets each workspace spend on models per calendar month (UTC), in US
159 # dollars, whatever its own budgets say. Enforced like a cost cap that
160 # nobody in the workspace can edit. Empty, "off" or "none": no allowance —
161 # none applies until an amount is chosen.
162 #: Each person's Personal workspace, with their personal projects.
163 PLATFORM_ALLOWANCE_PERSONAL_USD: str = ""
164 #: Each organisation, with every project in it: one allowance for the lot.
165 PLATFORM_ALLOWANCE_ORGANISATION_USD: str = ""
167 # Plan prices (app/services/plans.py): what a workspace pays CHAIN-R a
168 # calendar month, in US dollars — a platform fee, plus its model usage
169 # past an included amount at cost plus a markup — so a statement shows
170 # the charges to invoice by hand and the economics export the revenue a
171 # gross margin is measured against. One price per kind of workspace,
172 # projects counted with their parent. All three empty, "off" or "none":
173 # no plan, and no charges are shown.
174 PLAN_PERSONAL_FEE_USD: str = ""
175 PLAN_PERSONAL_USAGE_MARKUP_PERCENT: str = ""
176 PLAN_PERSONAL_INCLUDED_USAGE_USD: str = ""
177 PLAN_ORGANISATION_FEE_USD: str = ""
178 PLAN_ORGANISATION_USAGE_MARKUP_PERCENT: str = ""
179 PLAN_ORGANISATION_INCLUDED_USAGE_USD: str = ""
181 # Daily economics export (app/services/economics): each finished UTC
182 # day's model spend by workspace, source and model, and what it bought,
183 # written as files the compose host ships to S3 for Athena and to
184 # CloudWatch (infra/aws/economics). svc-core never reaches AWS itself.
185 #: Where the ``economics_export`` job writes. Empty: off, as locally and in
186 #: CI. The prod compose overlay sets it to the directory the host ships.
187 ECONOMICS_EXPORT_DIR: str = ""
188 #: How many days back a missing day is still written, and how long a
189 #: written one is kept before the job deletes it (the host ships each
190 #: within the hour).
191 ECONOMICS_EXPORT_LOOKBACK_DAYS: int = 30
193 # Feature flags
194 RUN_MIGRATIONS: bool = True
196 class Config:
197 env_file = Path(__file__).parent.parent.parent / "dev.creds.env"
198 env_file_encoding = "utf-8"
200 @property
201 def internal_auth_active(self) -> bool:
202 return bool(self.INTERNAL_JWT_SECRET)
204 @property
205 def NEO4J_USER(self) -> str:
206 return self.NEO4J_AUTH.split("/")[0]
208 @property
209 def NEO4J_PASSWORD(self) -> str:
210 return self.NEO4J_AUTH.split("/", 1)[1]
212 # Computed properties
213 @property
214 def POSTGRES_URL_FULL(self) -> str:
215 return f"postgresql+psycopg2://{self.POSTGRES_USER}:{self.POSTGRES_PASSWORD}@{self.POSTGRES_HOST}/{self.POSTGRES_DB}"
218@lru_cache()
219def get_settings():
220 settings = Settings()
221 if settings.APP_ENV in (AppEnv.STAGING, AppEnv.PROD):
222 # Internal service-to-service auth is mandatory outside local/dev.
223 if not settings.INTERNAL_JWT_SECRET:
224 raise ValueError(
225 "INTERNAL_JWT_SECRET must be set outside local/dev for "
226 "service-to-service authentication"
227 )
228 if len(settings.INTERNAL_JWT_SECRET) < 32:
229 raise ValueError("INTERNAL_JWT_SECRET must be at least 32 characters")
230 return settings