# Architecture
The project is a single Cargo package, `aoc-toolkit`, with library `aoc_toolkit` and global executable `aoc`. Internal Rust modules and additive Cargo features separate responsibilities. The core-only build must not require external dependencies.
- `core`: Rust solver contracts, registry and execution primitives; always available.
- `client`: optional authentication, HTTP and account-specific global input cache.
- `runner`: local Rust solver execution; independent of the client feature.
- `application`: use cases independent of presentation.
- `project`: configuration and project discovery.
- `adapters`: language-specific execution and scaffolding.
- `scaffold`: template rendering, filesystem planning and safe application.
- `cli`: argument parsing and terminal presentation.
- Future TUI: a Ratatui frontend using the same application use cases.
The global CLI discovers a project through aoc.toml and invokes its configured language adapter. The Rust adapter invokes Cargo; the local runner is compiled with the user's solutions. No dynamic Rust plugin ABI is required.
## Runner execution protocol
The global CLI orchestrates execution through the configured language adapter:
1. Planning: invoke the local runner with the internal `run --plan` flag. The runner resolves its registry and returns JSON year/day pairs.
2. Preparation: resolve the active session and account once, then ensure the required inputs exist in the account-specific cache. The `fetch` command uses the same acquisition logic independently of any project.
3. Execution: invoke the local runner with the prepared account-specific `--input-dir`. The runner reads the input files, executes solvers, and reports results.
The Rust adapter currently invokes Cargo twice. The second invocation can reuse compilation artifacts. The protocol is internal and may change before v0.1.0; the CLI and runner must use compatible versions. Input preparation currently fails fast if any planned input cannot be acquired.
The runner does not depend on HTTP, credential storage, session management, or the `client` feature. The Rust adapter removes `SESSION_ID` from subprocess environments. This is a responsibility boundary, not a sandbox for arbitrary solver code.
## Input storage
Use the platform cache directory with a `kyrboforge/aoc-toolkit` suffix, or an explicit absolute `AOC_TOOLKIT_CACHE_DIR` override. Store inputs under `inputs/<account-id>/<year>/<day>.txt` and verified account associations under `sessions/<session-fingerprint>.txt`. The session fingerprint is SHA-256; raw tokens are never used as file names. Session tokens are resolved from the process environment, then the nearest `.env`, then the OS credential store. `.env` is read without mutating the process environment. Invalid overrides or malformed configuration fail closed. All session consumers share this resolution policy; `auth status` reports the effective source, and `setup` refuses to replace an expired override with a stored credential that would remain inactive. Cached inputs can be reused after session rotation once the new session has been associated with the same account.
Session-to-account bindings are immutable for a given token fingerprint: writes acquire `sessions.lock`, check the existing mapping, and reject conflicting identities or malformed mappings instead of silently overwriting them. A rotated token may be associated with the same account. Writes use a temporary file in the destination directory followed by atomic replacement. There is no project-local input cache or migration fallback.
## Session verification
Session verification requests the fixed AoC settings endpoint without following redirects, requires HTTP 200 with a `text/html` response and valid UTF-8, and parses the document with `scraper`. It requires an actual logout anchor and exactly one anonymous display-name radio option with its adjacent span containing a positive numeric account ID. Unrelated display-name text and duplicate options are not accepted as identity evidence. A markup change may cause verification to fail closed. The HTML parser is gated behind the `client` feature and is not included in the runner.
## CLI presentation
Commands parse arguments, coordinate use cases and determine exit status. Application services return typed results and reports, while `cli/output` renders terminal messages. Interactive input remains in the command layer. The global terminal presentation is centralized in `cli/output` for authentication, browser registration, setup, fetch, scaffold reports and top-level errors. The local runner has its own output layer; a future TUI should consume application results rather than terminal strings.
The fetch use case resolves the requested unlocked puzzles through the edition calendar before accessing credentials. Bulk acquisition is sequential, stops on the first error and shares the same cache and download path as run. A persistent `download.lock` file at the cache root coordinates downloads across accounts and processes using the same cache. Cache hits bypass the lock; misses recheck the cache after acquiring it, then download and atomically persist the input if still absent. Settings verification acquires the same lock. Both paths hold it during the operation and for a two-second cooldown after completion, including errors. This does not coordinate different cache roots, other devices, or cooldowns interrupted by process termination.
## Architectural constraints
- Keep dependencies optional and gated by the features that need them.
- No direct dependencies on consumer solution repositories.
- Keep shared application and project logic language-independent. Prefer concrete adapters until a second language establishes real abstraction needs.
- Do not use shell string interpolation to invoke project runners; pass arguments as separate values.
- Treat project configuration and templates as potentially untrusted inputs; prevent accidental overwrites and directory traversal.
- Keep puzzle input private, cache it, and avoid unnecessary network requests. Network clients must identify themselves and respect service limits.
- Do not assume macOS for authentication or filesystem paths. Credentials belong in OS-backed secure storage where available (macOS Keychain, Windows Credential Manager, Linux Secret Service or equivalent). Desktop macOS, Windows and Linux are the authentication support targets. Headless servers are not a supported target; an explicit environment-variable override may be retained for development and CI. Do not silently fall back to plaintext. Never log the session cookie.
- Generated AGENTS.md and CLAUDE.md apply to consumer projects, not the toolkit repository.
The current execution protocol and authentication backend are implemented but remain subject to hardening before v0.1.0. The TUI and additional language adapters are planned.
## Integration qualification
Generated Rust project integration tests exercise initialization, solver registration, explicit and default execution, individual parts, per-year and multi-year execution, nested project discovery, the internal JSON planning protocol, and cached single/bulk fetches. Failure-path coverage includes unregistered days and years, solver panics and mixed-success executions, missing prepared input directories and files, invalid selectors, session override precedence, dotenv resolution, and rejection of invalid overrides without exposing tokens. Tests use synthetic inputs, a temporary cache and a local toolkit dependency with Cargo offline mode. They do not require live credentials or real AoC inputs. A rejecting proxy is used for HTTP requests in these tests; this is not an operating-system network sandbox.
## Planned progress export (P3)
Progress tracking will distinguish local solver registration and execution from stars verified by Advent of Code. The planned `aoc progress --sync` explicitly refreshes remote progress. An opt-in README export will render a year/day/star matrix and totals from stored progress, updating only a bounded managed Markdown section. Repeated exports must be idempotent and preserve unrelated user content. Preview/stdout and explicit update modes are planned; no puzzle inputs, answers, tokens, or account identifiers will be exported. A normal `aoc run` must not silently overwrite README files or trigger a remote sync.