# PRD implementation notes ## Decisions and safe defaults - “Top five” means **both** ranked sources and selected items. No personal profile or channel was assumed. This interpretation remains configurable/reviewable. - Daily CLI + archive-only weekly digest are available; no cron task is installed. - Profiles and percentage portfolios are optional and strictly local. Source requests do not depend on private allocations. Percentage portfolios affect ranking, watch eligibility and report-only review lenses; they never weaken safety gates. See [percentage portfolio context](portfolio.md) for the schema and privacy boundaries. Optional nested ETF/stock/bond breakdowns use percentages within a parent position; declared tags or literal public identifiers refine market-news overlap locally. They do not trigger identifier lookups, price requests or fund look-through. A [local CSV converter](csv-import.md) creates validated YAML without importing account/amount columns, fetching, or persisting inputs in the news archive. - Notifications are opt-in, dry by default, and cannot be enabled with synthetic data. - Source content is processed as inert text. Core analysis is deterministic; the optional `summarize` command uses Pi RPC with public item fields only and no tools or private portfolio context. There is no shell interpolation of source text, autonomous browsing of article links, or feed-controlled plugin selection. ## Milestone status | Milestone | Implemented | Boundary | | --- | --- | --- | | M1 | Ranked registry, shared RSS adapter serving ECB/AMF/press, public-JSON contract adapter, guarded legacy Reddit adapter, normalization, SQLite, resilient report | Six feeds enabled (ECB, ECB Statistics, AMF, Le Monde Économie, Moneyvox, World Gold Council); other candidates remain disabled; configuration is not a fresh access check | | M2 | Safety gate, classification, explainable scores, top resources, source scorecard | Reliability is configured, not inferred from popularity; topic interpretation is deterministic | | M3 | Horizon/direction/risk/security tags, change-of-mind checks, scoped numeric provenance/conflicts, reviewed educational facts, readings and growing glossary | Narrow numeric grammar, not general-purpose claim verification or full-article translation | | M4 | Major-event/threshold rules, fixed alert template, playbooks, deduplication, cooldown, quiet hours, append-only audit, opt-in local notification helper | Separate opt-in Telegram report publisher available; no channel activated automatically and no guaranteed real-time or complete incident coverage | | M5 | Archive-only weekly digest, sourced calendar export, fees theme, scam/hype detection | Calendar dates not prefilled without verified notices; no cross-product fee comparison or external blacklist database synchronization | | M6 / P2 / P3 | Not implemented | No balance/guarantee calculator, allocation recommendation, journal, semantic claim fact-checker, dashboard or Q&A | ## Data flow ```text config/sources.yaml -> robots + permitted adapter -> public RawItem -> SQLite | profile / portfolio (local only) ----------------> normalize + safety gate | topic/horizon interpretation + claim extraction | same metric + subject + unit + period verification | weighted scoring -> top eligible resources | event confidence/significance -> dedupe/cooldown -> optional helper | reviewed knowledge + seen history -> Markdown/data/audit output ``` SQLite tables: `items`, `sources`, `runs`, `events`, `seen_readings`, `glossary`, `metadata`. A state database is permanently bound to either live or synthetic mode. A POSIX exclusive run lock prevents overlapping collection/delivery. The archive contains public source excerpts and structured run payloads, never the profile. Run payloads retain the data used for an overwritten daily output. All links and figures are sourced; raw source instructions are quarantined before output. A live source's configured frequency is honored across invocations. A source that fails can retain its **own previously collected local data**, labeled with the original publication/fetch timestamps and a failure/cached caveat. This is not a request routed through any external cache, alternative scraper or archive. Blocked sources' retained items do not produce new alerts. Source-local caches do not turn undated or stale items into fresh publications. ## Scoring and selection All score components are in `data.json`, for auditability: ```text total = .25 reliability + .15 recency + .20 relevance + .25 materiality + .15 corroboration ``` - Reliability is the configured source weight. - Recency declines linearly across the freshness window. - Relevance uses affected areas and optional local buckets/horizon, or the non-double-counted matching fraction from a percentage portfolio; never balances. Portfolio review notes are transient and supplied only to the Markdown renderer, not structured archives. - Materiality is a conservative topic weight, reduced for a daily price move. - Corroboration requires an equal value with the same metric, subject, unit and explicit observation/effective period, from distinct configured independence groups. Community posts and low-reliability sources cannot inflate it. It remains a limited operational proxy, not proof that reporting was independently researched. The speculation gate precedes scoring. Noise is never selected regardless of votes, recency, corroboration or profile relevance. Undated, future-dated and old items are not selected. Duplicate canonical URLs cannot take multiple top slots. General news with no identified financial topic does not qualify as filler. ## Numeric evidence contract The extractor supports explicit percentages, index points and basis points for a small named set of rate, inflation, yield, index and spread metrics. It requires unambiguous context. Explicit ISO observation/effective periods are preferred; a publication date is never silently substituted for one. Claims include `source`, `url`, `published_at`, `value`, `unit`, `metric`, `subject`, `period`, `verified`, `verification_source`, `status`, and `conflicts`. Same-period conflicting primary evidence is preserved, lowers confidence and is displayed in Caveats even if the conflicting item did not enter the top resources. A primary source must be configured for the specific metric. An inflation quote without CPI/IPC versus HICP/IPCH identification is not cross-verified. Different indices are not interchangeable. Generic fonds en euros yields lack a uniquely identified insurer/contract/fee basis and remain unverified. Forecasts, approximate or negated numbers and ambiguous multiple-value sentences do not become verified observations. The extractor may miss real data rather than assert a wrong figure. `primary-reported` means traceability to an applicable official source, not a second independent confirmation. The report labels the distinction and preserves dates. No model-memory values, synthetic placeholder rates or market forecasts are used. ## Alert semantics and delivery Source quality, date, confidence and safety are hard gates. Major decisions are review items, not instructions to change products. Threshold-based alerts are watch rules, not a diagnosis of an economic regime or a forecast. The data model's low severities exist for watch items; they do not clear the push gate unless a held area matches. Percentage portfolios additionally apply the configurable `portfolio_watch_min_percent` threshold to watch-only events. Major events remain eligible without a direct match, and confidence/quality gates are unchanged. Community content never becomes an incident alert. The event key uses event type plus scoped numerical evidence when available, or publication day and theme otherwise. This deliberately groups same-day official headlines conservatively; detailed entity-level incident grouping is not implemented. Cooldown is per event type. A dry-run or quiet-hours observation does not count as a delivered notification and can be reconsidered later while fresh. A successful delivery timestamp is persistent. The command helper receives JSON on stdin with an argv list, no shell, bounded runtime and no raw profile. A durable reservation is saved before invoking it. If the process dies or the helper fails or times out, delivery becomes uncertain and is not automatically retried. This favors avoiding duplicate pushes over blindly retrying a message that may already have been delivered. Manually inspect the helper/audit before clearing that event in local state. No email or other credentials are stored by finance0. ## Telegram publication and summary provenance The send-only report publisher is separate from alert-helper delivery. It uses `state/telegram.sqlite` with its own nonblocking POSIX process lock, held across all message parts. Reservations are committed with SQLite synchronous FULL before network access. Records contain publication ID (hash of destination hash, run ID and content hash), destination hash, run ID, content hash, report day, status, attempt count and last-update time. Tokens, raw chat IDs and report text are not stored. Preserve this ledger across runs; it cannot discover historical sends. Delivered content is skipped across collection runs. By default, one successful publication per destination/report day is permitted, preventing repeated daily workflows from resending timestamp changes or regenerated model prose. Explicit `--allow-update` permits changed content, but never bypasses identical-content deduplication or an unresolved uncertain delivery. Different days/destinations remain eligible. Skips return structured reasons and the prior publication ID. An exception or process death makes delivery uncertain, not retryable. Pending reservations with no active lock holder are recovered as uncertain. All sends to that destination stop until `telegram-resolve` explicitly marks the complete publication delivered or clears it for retry. Review happens outside the app; there is no automatic partial-message resume or exactly-once API guarantee. Resolution sends nothing, and a later retry uses the then-current report snapshot. `run` binds the rendered report to `data.json` with `briefing_sha256`. The optional summary records run ID, exact input-data hash and summary hash in `llm_summary.meta.json`; if collection changes during generation, it refuses to publish the result. Artifact locks coordinate report/data writes, summary writes and publisher snapshot reads. The publisher ignores missing/stale/modified summary provenance and falls back to a hash-matched deterministic report. Legacy outputs without identity/integrity metadata must be regenerated. These hashes establish local consistency, not source truth, model accuracy or freshness relative to today. ## Configuration extensions - New public RSS source: add a registry entry with its own permitted URL, independence group, frequency, notes and reviewed permission. Do not enable a candidate homepage as if it were a feed. - Public JSON endpoint: use adapter `json_api`, method `api`, and the documented item-envelope contract. Source-provided fields cannot configure runtime commands. - Education: extend `config/knowledge.yaml` with checked English concepts, actual publication dates, source links and optional definitions. `published_at` may be a date-only string for a date-only source; no timestamp is invented. Glossary entries are defined once. Readings are not repeated after being surfaced. - Calendar: add `{id, title, date, url, published_at, verified: true}` entries with reviewed official notices. A recurring sourced reminder may replace `date` with `month` and `day`. Unverified/future-publication entries are omitted from export. Dates are not legal deadlines unless the cited source actually establishes them. - Filters/playbooks/alerts: edit the respective YAML files locally. Keep playbooks educational and avoid recommendations; output lint fails closed if unsafe prose would otherwise be published. ## Acceptance coverage `tests/test_finance0.py` covers the PRD acceptance categories: 1. All fixed report sections, JSON and per-source failures, including an entirely unavailable source set. 2. Five items when enough qualify; an explicit explanation otherwise. 3. Leveraged, meme, crypto-momentum and injected items excluded from selection/impact. 4. Every extracted numeric claim requires URL/source/date; percent/bps report lines carry dated citations; conflicting primary evidence is shown, not silently resolved. 5. Horizons, direction, risk/security tags and change-of-mind/review questions. 6. Livret A/ECB events clear the review threshold, while small daily moves do not. 7. Persistent dedupe, cooldown, dry-run and quiet-hours semantics; uncertain-delivery handling; same-run duplicate headlines do not produce duplicate alerts. 8. Blocks do not retry or select alternate endpoints; robots-denied and unapproved redirect paths are never requested; transient server errors have bounded retries. 9. Instruction injection is quarantined and absent from public report/data text. 10. Exact disclaimer in reports/alerts; runtime and test lint reject recommendations. 11. Strict profile validation, ignore rules and absence of raw profile fields in reports, data, logs and persisted run payloads. Additional tests cover adapters/Atom missing dates, source frequency, profile-only relevance, subject/period matching, forecast/negation handling, calendar export, SQLite run locking, glossary/seen history, scorecard accumulation and digest isolation. Legacy offline and Chromium-selector tests remain in `tests/test_mvp.py`. `tests/test_telegram.py` covers persistent duplicate/day gates, explicit updates, concurrent threads/processes, durable pre-send reservations, partial failures, crashed pending work, explicit review and private state. `tests/test_llm.py` covers summary provenance, changed collections during generation and safe fallback after a failed new summary. All delivery requests use mocks, never live Telegram. `tests/test_portfolio.py` additionally covers strict percentage validation, joint wrapper/asset matching, ranking by allocation size, local report lenses, watch thresholds, precedence, notification privacy and absence of allocation history. It also covers nested holding totals, exact parent/child arithmetic, region/sector and bond scoping, ambiguous-symbol avoidance, old-file compatibility and exclusion of raw names/identifiers/breakdowns from reports, JSON, SQLite and notification payloads. `tests/test_portfolio_csv.py` covers coarse/detailed CSV conversion, locale-friendly formatting, strict totals/precision/schema validation, private errors, no network, mode-0600 atomic output, no-clobber races, input/link protection, failure cleanup and the standalone entry point. ## Remaining limitations - Enabled sources are not yet a complete French financial information service. In particular, blocked/unverified regulated-rate, insurance and legal sources limit coverage. A lack of alerts never establishes that no incident occurred. - Registry access checks verify reachability, robots and public-feed scope, not a legal opinion about licensing; disabled candidates remain unverified. - English analysis is deterministic and cautious, not a semantic article summary. The baseline has no LLM dependency or outbound model call. The optional Pi RPC summary sends public selected item fields only, uses no tools and validates output against report safety rules. This is not semantic claim verification; simply quoting a prompt is not a safety guarantee. - There is no structured current-price API, full-text news crawler, investor-specific counterparty mapping, automatic insurer-yield comparison, or blacklist mirroring. - Calendar mechanism and fees/scam themes are implemented, but independently verified schedules, product tariffs and ongoing blacklist ingestion remain future data work.