返回 CodeWhale
setup_state.rs
根目录 / crates / config / src / setup_state.rs
1 //! Unified setup-state model for the v0.8.67 constitution-first setup lane
2 //! (#3403).
3 //!
4 //! This is the single record every setup step (#3404–#3412) reads and writes so
5 //! that "configured", "skipped", "verified", and "ready" mean the same thing
6 //! everywhere. It is persisted as a JSON sidecar (`setup_state.json`) under
7 //! `$CODEWHALE_HOME`, written atomically through [`crate::persistence`] so it is
8 //! independent of `config.toml`'s comment-preserving writes and can never leave
9 //! a half-written file.
10 //!
11 //! The record holds two things:
12 //!
13 //! 1. A per-[`SetupStep`] [`StepEntry`] (status, required, safe summary,
14 //! writing lane version).
15 //! 2. The constitution-first fields the wizard, the update checkpoint, and
16 //! `/constitution` all coordinate on.
17 //!
18 //! Readiness is a *derived* property ([`first_run_ready`](SetupState::first_run_ready)
19 //! / [`update_ready`](SetupState::update_ready)); it is never persisted, so the
20 //! rules can evolve without a migration.
21 //!
22 //! Secrets never appear here: [`StepEntry::result`] is a short human-facing
23 //! summary (provider name, model id, mode name), never a key.
24
25 use std::collections::BTreeMap;
26 use std::path::{Path, PathBuf};
27
28 use anyhow::{Context, Result};
29 use serde::{Deserialize, Serialize};
30
31 use crate::persistence;
32
33 /// Current schema version of the persisted setup-state record.
34 pub const SETUP_STATE_SCHEMA_VERSION: u32 = 1;
35
36 /// Filename of the setup-state sidecar under `$CODEWHALE_HOME`.
37 pub const SETUP_STATE_FILE_NAME: &str = "setup_state.json";
38
39 /// Version of the *telemetry notice content* — not the app version.
40 ///
41 /// The notice is owed whenever
42 /// [`SetupState::needs_telemetry_notice`] reports that it has not been shown.
43 /// Bumping it re-shows the disclosure to prior acceptors and unanswered users,
44 /// so it is bumped only
45 /// when the collection policy, schema, or disclosure materially changes. Prior
46 /// declines remain off. Keying it to the app version would re-prompt every
47 /// release, which is nagging with extra steps.
48 pub const TELEMETRY_NOTICE_VERSION: &str = "6";
49
50 pub use codewhale_protocol::setup::SetupStep;
51
52 /// Status of a single setup step. Shared vocabulary so `/setup`, `doctor`, and
53 /// the context report never invent their own meanings.
54 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
55 #[serde(rename_all = "snake_case")]
56 pub enum StepStatus {
57 /// Never visited.
58 NotStarted,
59 /// Suggested for a good first-run experience but not required.
60 Recommended,
61 /// Available but entirely optional.
62 Optional,
63 /// Intentionally postponed; surfaces in the report, does not block.
64 Deferred,
65 /// Currently being worked on.
66 InProgress,
67 /// A usable route is configured, but has not been checked with the provider.
68 Configured,
69 /// Completed and checked (e.g. key validated, mode confirmed).
70 Verified,
71 /// Reached a usable-but-incomplete state needing user action
72 /// (e.g. a key that failed validation). Does not block the ready screen.
73 NeedsAction,
74 /// Attempted and errored.
75 Failed,
76 /// Explicitly skipped by the user.
77 Skipped,
78 }
79
80 impl StepStatus {
81 /// True for statuses that count as "the user dealt with this step" for the
82 /// purpose of reaching the ready screen.
83 #[must_use]
84 pub fn is_settled(self) -> bool {
85 matches!(
86 self,
87 StepStatus::Configured
88 | StepStatus::Verified
89 | StepStatus::NeedsAction
90 | StepStatus::Deferred
91 | StepStatus::Optional
92 | StepStatus::Skipped
93 )
94 }
95 }
96
97 /// One persisted entry per setup step.
98 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
99 pub struct StepEntry {
100 pub status: StepStatus,
101 /// Whether this step blocks "ready" for the lane that owns it. First-run and
102 /// update lanes differ; see the readiness helpers on [`SetupState`].
103 #[serde(default)]
104 pub required: bool,
105 /// Short, safe human-facing summary — provider name, model id, mode name,
106 /// health. **Never a secret.**
107 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub result: Option<String>,
109 /// Lane (e.g. `"0.8.67"`) that last wrote this entry, so staleness is
110 /// visible to `/setup`, `doctor`, and the context report.
111 #[serde(default, skip_serializing_if = "Option::is_none")]
112 pub version: Option<String>,
113 }
114
115 impl StepEntry {
116 /// A freshly-visited entry written by `version`.
117 #[must_use]
118 pub fn new(status: StepStatus, required: bool, version: impl Into<String>) -> Self {
119 Self {
120 status,
121 required,
122 result: None,
123 version: Some(version.into()),
124 }
125 }
126
127 #[must_use]
128 pub fn with_result(mut self, result: impl Into<String>) -> Self {
129 self.result = Some(result.into());
130 self
131 }
132 }
133
134 /// The user's constitution decision. Every value except [`Unset`] counts as an
135 /// explicit choice for readiness.
136 ///
137 /// [`Unset`]: ConstitutionChoice::Unset
138 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
139 #[serde(rename_all = "snake_case")]
140 pub enum ConstitutionChoice {
141 /// No decision recorded yet.
142 #[default]
143 Unset,
144 /// Accepted the bundled/default constitution floor. Creates no custom file.
145 Bundled,
146 /// Created a guided structured user-global constitution.
147 GuidedCustom,
148 /// Expert full-Markdown override
149 /// (`$CODEWHALE_HOME/prompts/constitution.md` + opt-in env).
150 ExpertOverride,
151 /// Explicitly postponed; bundled law applies until the user returns.
152 Deferred,
153 }
154
155 impl ConstitutionChoice {
156 #[must_use]
157 pub const fn applies_user_global(self) -> bool {
158 !matches!(self, Self::Bundled | Self::Deferred | Self::ExpertOverride)
159 }
160
161 /// True for any value other than [`Unset`](ConstitutionChoice::Unset).
162 #[must_use]
163 pub fn is_explicit(self) -> bool {
164 !matches!(self, ConstitutionChoice::Unset)
165 }
166 }
167
168 /// How the active custom constitution was authored. Recorded alongside
169 /// [`ConstitutionChoice::GuidedCustom`] so `/setup`, `doctor`, and the report
170 /// can show provenance without parsing free-text step results.
171 ///
172 /// This is a *new optional field* rather than a new [`ConstitutionChoice`]
173 /// variant so records written by this lane still load in older binaries
174 /// (unknown fields are ignored on read; an unknown enum variant would fail the
175 /// whole parse and force the inherited-state fallback).
176 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
177 #[serde(rename_all = "snake_case")]
178 pub enum ConstitutionAuthoring {
179 /// Deterministically rendered from the guided answers.
180 Guided,
181 /// Drafted by the user's configured model from the guided answers, then
182 /// schema-validated, bounded, previewed, and ratified. Advisory authorship
183 /// only — the drafting model gains no authority from having written it.
184 ModelDrafted,
185 }
186
187 /// Which constitution surface is currently the active user-global law.
188 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
189 #[serde(rename_all = "snake_case")]
190 pub enum ConstitutionSource {
191 /// Only the bundled floor is active.
192 #[default]
193 Bundled,
194 /// A structured `constitution.json` under `$CODEWHALE_HOME`.
195 UserGlobal,
196 /// An expert full-Markdown override file.
197 ExpertOverride,
198 }
199
200 /// Validity of the active user-global constitution file, if any.
201 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
202 #[serde(rename_all = "snake_case")]
203 pub enum ConstitutionValidity {
204 /// No custom file, or validity not yet evaluated.
205 #[default]
206 Unknown,
207 /// Parsed and usable.
208 Valid,
209 /// Present but failed to parse / structurally invalid.
210 Invalid,
211 /// Present but carried no usable policy.
212 Empty,
213 /// Present but could not be read.
214 Unreadable,
215 }
216
217 /// Where the current runtime posture came from. Mirrors the rule that a
218 /// constitution may *recommend* posture but only an explicit config action
219 /// (#3406) applies it.
220 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
221 #[serde(rename_all = "snake_case")]
222 pub enum RuntimePostureSource {
223 /// Not yet reviewed.
224 #[default]
225 Unset,
226 /// Carried over from existing config without an explicit confirmation.
227 Inherited,
228 /// The user explicitly reviewed and confirmed the posture in setup.
229 Confirmed,
230 }
231
232 impl RuntimePostureSource {
233 /// True when posture has been inherited or confirmed (either satisfies
234 /// first-run readiness).
235 #[must_use]
236 pub fn is_reviewed(self) -> bool {
237 matches!(
238 self,
239 RuntimePostureSource::Inherited | RuntimePostureSource::Confirmed
240 )
241 }
242 }
243
244 /// The persisted, per-version setup-state record.
245 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
246 pub struct SetupState {
247 pub schema_version: u32,
248
249 /// Per-step status entries.
250 #[serde(default)]
251 pub steps: BTreeMap<SetupStep, StepEntry>,
252
253 // ── Constitution-first fields ───────────────────────────────────────
254 /// The user's constitution decision.
255 #[serde(default)]
256 pub constitution_choice: ConstitutionChoice,
257 /// Lane version (e.g. `"0.8.67"`) whose constitution checkpoint the user has
258 /// completed. Drives the once-per-version update checkpoint (#3794).
259 #[serde(default, skip_serializing_if = "Option::is_none")]
260 pub constitution_checkpoint_completed_for: Option<String>,
261 /// Language the constitution prose was authored/reviewed in.
262 #[serde(default, skip_serializing_if = "Option::is_none")]
263 pub constitution_language: Option<String>,
264 /// Which surface is the active user-global law.
265 #[serde(default)]
266 pub constitution_source: ConstitutionSource,
267 /// Validity of the active user-global constitution file.
268 #[serde(default)]
269 pub constitution_validity: ConstitutionValidity,
270 /// How the active custom constitution was authored (guided deterministic
271 /// vs model-drafted-then-ratified). `None` for bundled/deferred/inherited.
272 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub constitution_authoring: Option<ConstitutionAuthoring>,
274 /// Stable content hash of the most recently previewed/accepted rendered
275 /// constitution (see [`crate::user_constitution::UserConstitution::preview_hash`]).
276 #[serde(default, skip_serializing_if = "Option::is_none")]
277 pub constitution_preview_hash: Option<String>,
278 /// Monotonic counter bumped each time a custom constitution is saved, so the
279 /// report and `/constitution` can show which revision is live.
280 #[serde(default)]
281 pub constitution_preview_version: u32,
282 /// Where the current runtime posture came from.
283 #[serde(default)]
284 pub runtime_posture_source: RuntimePostureSource,
285
286 /// Host-enforced Workflow dispatch and terminal receipts have been proven
287 /// for this installation. Older records did not carry this proof and must
288 /// deserialize false even if their Operate/Fleet card was marked Verified.
289 #[serde(default, skip_serializing_if = "is_false")]
290 pub operate_receipts_verified: bool,
291
292 /// True when this record was *derived* from existing config rather than
293 /// persisted by an explicit setup run. Lets `/setup` and `doctor` explain
294 /// why an updating user is not treated as a broken fresh install.
295 #[serde(default, skip_serializing_if = "is_false")]
296 pub inherited: bool,
297
298 // ── Telemetry notice ────────────────────────────────────────────────
299 /// [`TELEMETRY_NOTICE_VERSION`] whose telemetry processor disclosure was explicitly accepted or declined.
300 /// `None` means no explicit preference was recorded. Usage defaults on;
301 /// presenting a disclosure never changes these preference fields.
302 ///
303 /// These are *fields* rather than a new [`SetupStep`] variant on purpose:
304 /// an unknown enum variant fails the whole record parse and silently drops
305 /// the user back to derived-inherited state — including their constitution
306 /// checkpoint — while unknown fields are ignored.
307 #[serde(default, skip_serializing_if = "Option::is_none")]
308 pub telemetry_notice_decided_for: Option<String>,
309 /// The privacy preference recorded with the notice. `false` with any
310 /// recorded notice version is a durable opt-out; `true` records that the
311 /// processor disclosure was explicitly accepted for that version.
312 #[serde(default, skip_serializing_if = "is_false")]
313 pub telemetry_opt_in: bool,
314 /// Most recent telemetry policy disclosure actually presented locally.
315 /// This is display bookkeeping, never evidence of human acceptance.
316 #[serde(default, skip_serializing_if = "Option::is_none")]
317 pub telemetry_notice_shown_for: Option<String>,
318 }
319
320 #[allow(clippy::trivially_copy_pass_by_ref)]
321 fn is_false(b: &bool) -> bool {
322 !*b
323 }
324
325 impl Default for SetupState {
326 fn default() -> Self {
327 Self {
328 schema_version: SETUP_STATE_SCHEMA_VERSION,
329 steps: BTreeMap::new(),
330 constitution_choice: ConstitutionChoice::default(),
331 constitution_checkpoint_completed_for: None,
332 constitution_language: None,
333 constitution_source: ConstitutionSource::default(),
334 constitution_validity: ConstitutionValidity::default(),
335 constitution_authoring: None,
336 constitution_preview_hash: None,
337 constitution_preview_version: 0,
338 runtime_posture_source: RuntimePostureSource::default(),
339 operate_receipts_verified: false,
340 inherited: false,
341 telemetry_notice_decided_for: None,
342 telemetry_opt_in: false,
343 telemetry_notice_shown_for: None,
344 }
345 }
346 }
347
348 /// Observable, secret-free facts about existing config used to derive a safe
349 /// inherited setup-state for users who upgrade without a `setup_state.json`.
350 ///
351 /// The caller (TUI/CLI) gathers these from `ConfigToml`, the trust marker, and
352 /// the constitution files; keeping them as plain data keeps this module pure and
353 /// unit-testable.
354 #[derive(Debug, Clone, Default)]
355 pub struct InheritedConfigFacts {
356 /// A provider/model route is configured.
357 pub has_provider_route: bool,
358 /// A key or local runtime is available (presence only — never the value).
359 pub has_credentials_or_local_runtime: bool,
360 /// The user has previously made a trust/approval decision.
361 pub trust_chosen: bool,
362 /// Onboarding language, if known.
363 pub language: Option<String>,
364 /// A structured user-global `constitution.json` exists.
365 pub has_user_constitution: bool,
366 /// An expert full-Markdown override is active.
367 pub has_expert_override: bool,
368 /// Validity of the user-global constitution, if present.
369 pub user_constitution_validity: ConstitutionValidity,
370 }
371
372 impl SetupState {
373 /// Status for a step, defaulting to [`StepStatus::NotStarted`].
374 #[must_use]
375 pub fn status(&self, step: SetupStep) -> StepStatus {
376 self.steps
377 .get(&step)
378 .map_or(StepStatus::NotStarted, |e| e.status)
379 }
380
381 /// Record (insert or replace) an entry for `step`.
382 pub fn set_step(&mut self, step: SetupStep, entry: StepEntry) -> &mut Self {
383 self.steps.insert(step, entry);
384 self
385 }
386
387 #[must_use]
388 fn step_verified(&self, step: SetupStep) -> bool {
389 self.status(step) == StepStatus::Verified
390 }
391
392 /// Provider/model is acceptable for first-run readiness when configured,
393 /// verified or in an actionable needs-action state (the failed-key path
394 /// still reaches the ready screen).
395 #[must_use]
396 fn provider_model_ready_or_needs_action(&self) -> bool {
397 matches!(
398 self.status(SetupStep::ProviderModel),
399 StepStatus::Configured | StepStatus::Verified | StepStatus::NeedsAction
400 )
401 }
402
403 /// First-run "ready": language verified, provider/model ready-or-needs-action,
404 /// runtime posture inherited/confirmed, and an explicit constitution choice.
405 #[must_use]
406 pub fn first_run_ready(&self) -> bool {
407 self.step_verified(SetupStep::Language)
408 && self.provider_model_ready_or_needs_action()
409 && self.runtime_posture_source.is_reviewed()
410 && self.constitution_choice.is_explicit()
411 }
412
413 /// Operate/Fleet "ready": provider credentials are verified, runtime
414 /// posture has been reviewed, and the user has explicitly reviewed the
415 /// Fleet/Operate on-ramp. This is intentionally separate from
416 /// [`first_run_ready`](Self::first_run_ready): a local-first user can be
417 /// ready for ordinary first use before enabling durable multi-worker work.
418 #[must_use]
419 pub fn operate_ready(&self) -> bool {
420 self.first_run_ready()
421 && self.step_verified(SetupStep::ProviderModel)
422 && self.step_verified(SetupStep::OperateFleet)
423 && self.operate_receipts_verified
424 }
425
426 /// Update "ready" for `version`: the constitution checkpoint for that lane is
427 /// complete. Everything else is inherited from existing config.
428 #[must_use]
429 pub fn update_ready(&self, version: &str) -> bool {
430 self.constitution_checkpoint_completed_for.as_deref() == Some(version)
431 }
432
433 /// Whether the once-per-version update checkpoint should still be shown.
434 #[must_use]
435 pub fn needs_constitution_checkpoint(&self, version: &str) -> bool {
436 !self.update_ready(version)
437 }
438
439 /// Mark the constitution checkpoint complete for `version` (the bundled /
440 /// default path is a valid completion).
441 pub fn complete_constitution_checkpoint(
442 &mut self,
443 version: impl Into<String>,
444 choice: ConstitutionChoice,
445 ) -> &mut Self {
446 self.constitution_checkpoint_completed_for = Some(version.into());
447 self.constitution_choice = choice;
448 self
449 }
450
451 /// True when the telemetry notice for `version` has not been shown.
452 ///
453 /// A decision recorded against a *different* notice version does not
454 /// count: the content changed, so the disclosure is owed again.
455 #[must_use]
456 pub fn needs_telemetry_notice(&self, version: &str) -> bool {
457 self.telemetry_notice_shown_for.as_deref() != Some(version)
458 && self.telemetry_notice_decided_for.as_deref() != Some(version)
459 }
460
461 /// Record presentation without inventing a privacy preference.
462 pub fn record_telemetry_notice_shown(&mut self, version: impl Into<String>) -> &mut Self {
463 self.telemetry_notice_shown_for = Some(version.into());
464 self
465 }
466
467 /// Update fields from the latest readable sidecar under the shared lock.
468 ///
469 /// Startup configuration receipts, disclosure bookkeeping and explicit
470 /// privacy writes share this lock so none can erase a concurrent decision.
471 /// Missing state is fresh; corrupt state is never replaced with defaults.
472 pub fn update_at(path: &Path, update: impl FnOnce(&mut Self)) -> Result<()> {
473 let parent = path.parent().context("setup-state path has no parent")?;
474 std::fs::create_dir_all(parent)?;
475 let file = std::fs::OpenOptions::new()
476 .create(true)
477 .truncate(false)
478 .read(true)
479 .write(true)
480 // Keep the released lock path for concurrent older processes.
481 .open(path.with_extension("telemetry.lock"))?;
482 let mut lock = fd_lock::RwLock::new(file);
483 let _guard = lock.try_write()?;
484 let mut state = if path.try_exists()? {
485 Self::load_from(path).context("setup state could not be read")?
486 } else {
487 Self::default()
488 };
489 update(&mut state);
490 state.save_to(path)
491 }
492
493 /// Record the privacy preference associated with the telemetry notice.
494 ///
495 /// Acceptance is recorded only after an explicit choice to share counts;
496 /// an explicit opt-out may also arrive from Settings. Deferral,
497 /// skip-onboarding, and non-interactive surfaces leave it untouched.
498 pub fn record_telemetry_notice(
499 &mut self,
500 version: impl Into<String>,
501 opt_in: bool,
502 ) -> &mut Self {
503 self.telemetry_notice_decided_for = Some(version.into());
504 self.telemetry_opt_in = opt_in;
505 self
506 }
507
508 /// True when the current processor disclosure was explicitly accepted.
509 #[must_use]
510 pub fn telemetry_accepted(&self, version: &str) -> bool {
511 self.telemetry_notice_decided_for.as_deref() == Some(version) && self.telemetry_opt_in
512 }
513
514 /// True when the current notice record contains an explicit opt-out.
515 ///
516 /// Distinct from "never shown": only a recorded decline is an opt-out, and
517 /// only an opt-out may be acted on destructively.
518 #[must_use]
519 pub fn telemetry_declined(&self, version: &str) -> bool {
520 self.telemetry_notice_decided_for.as_deref() == Some(version) && !self.telemetry_opt_in
521 }
522
523 /// Whether any recorded telemetry notice was explicitly declined.
524 ///
525 /// Declines recorded by any former notice remain durable opt-outs. A notice-version bump may explain a
526 /// changed policy, but it must never erase a user's earlier "no".
527 #[must_use]
528 pub fn telemetry_opted_out(&self) -> bool {
529 self.telemetry_notice_decided_for.is_some() && !self.telemetry_opt_in
530 }
531
532 /// Derive a safe inherited state for an existing user with no persisted
533 /// `setup_state.json`. Surfaces they already configured become
534 /// settled; a provider route is only [`StepStatus::Configured`] until checked.
535 /// The constitution checkpoint is intentionally left incomplete so
536 /// updating users still see it once.
537 #[must_use]
538 pub fn derive_inherited(facts: &InheritedConfigFacts) -> Self {
539 let mut state = SetupState {
540 inherited: true,
541 ..SetupState::default()
542 };
543 let inherited = "inherited";
544
545 if facts.language.is_some() {
546 state.set_step(
547 SetupStep::Language,
548 StepEntry::new(StepStatus::Verified, true, inherited),
549 );
550 state.constitution_language = facts.language.clone();
551 }
552
553 if facts.has_provider_route && facts.has_credentials_or_local_runtime {
554 state.set_step(
555 SetupStep::ProviderModel,
556 StepEntry::new(StepStatus::Configured, true, inherited),
557 );
558 } else if facts.has_provider_route {
559 state.set_step(
560 SetupStep::ProviderModel,
561 StepEntry::new(StepStatus::NeedsAction, true, inherited),
562 );
563 }
564
565 if facts.trust_chosen {
566 state.set_step(
567 SetupStep::TrustSandbox,
568 StepEntry::new(StepStatus::Verified, true, inherited),
569 );
570 state.runtime_posture_source = RuntimePostureSource::Inherited;
571 }
572
573 // Constitution: classify the active surface, but never auto-complete the
574 // checkpoint — the update lane requires the user to acknowledge it once.
575 if facts.has_expert_override {
576 state.constitution_source = ConstitutionSource::ExpertOverride;
577 state.constitution_choice = ConstitutionChoice::ExpertOverride;
578 } else if facts.has_user_constitution {
579 state.constitution_source = ConstitutionSource::UserGlobal;
580 state.constitution_validity = facts.user_constitution_validity;
581 if facts.user_constitution_validity == ConstitutionValidity::Valid {
582 state.constitution_choice = ConstitutionChoice::GuidedCustom;
583 }
584 } else {
585 state.constitution_source = ConstitutionSource::Bundled;
586 }
587
588 state
589 }
590
591 /// Path to the setup-state sidecar under `$CODEWHALE_HOME`.
592 pub fn path() -> Result<PathBuf> {
593 Ok(crate::codewhale_home()?.join(SETUP_STATE_FILE_NAME))
594 }
595
596 /// Load the persisted setup-state from the home sidecar.
597 ///
598 /// Returns `Ok(None)` when the file is missing **or** unreadable/corrupt, so
599 /// callers fall back to [`derive_inherited`](Self::derive_inherited) rather
600 /// than forcing a fresh wizard. A corrupt record is logged, never fatal.
601 pub fn load() -> Result<Option<Self>> {
602 Ok(Self::load_from(&Self::path()?))
603 }
604
605 /// Load from an explicit path (testable). See [`load`](Self::load) for the
606 /// missing/corrupt fallback contract.
607 #[must_use]
608 pub fn load_from(path: &Path) -> Option<Self> {
609 let raw = match std::fs::read_to_string(path) {
610 Ok(raw) => raw,
611 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None,
612 Err(e) => {
613 tracing::warn!(
614 target: "config::setup_state",
615 "could not read {} ({e}); deriving status from existing config",
616 path.display()
617 );
618 return None;
619 }
620 };
621 match serde_json::from_str::<SetupState>(&raw) {
622 Ok(state) => Some(state),
623 Err(e) => {
624 tracing::warn!(
625 target: "config::setup_state",
626 "{} is not a valid setup-state record ({e}); deriving status from existing config",
627 path.display()
628 );
629 None
630 }
631 }
632 }
633
634 /// Atomically persist this record to the home sidecar.
635 pub fn save(&self) -> Result<()> {
636 let path = Self::path()?;
637 self.save_to(&path)
638 }
639
640 /// Atomically persist to an explicit path (testable).
641 pub fn save_to(&self, path: &Path) -> Result<()> {
642 persistence::atomic_write_json(path, self)
643 .with_context(|| format!("failed to persist setup state to {}", path.display()))
644 }
645 }
646
647 #[cfg(test)]
648 mod tests {
649 use super::*;
650
651 fn verified(version: &str) -> StepEntry {
652 StepEntry::new(StepStatus::Verified, true, version)
653 }
654
655 #[test]
656 fn default_is_not_first_run_ready() {
657 let state = SetupState::default();
658 assert!(!state.first_run_ready());
659 assert_eq!(state.constitution_choice, ConstitutionChoice::Unset);
660 }
661
662 #[test]
663 fn persistence_is_optional_before_verification() {
664 let persistence_index = SetupStep::ALL
665 .iter()
666 .position(|step| *step == SetupStep::Persistence)
667 .expect("persistence step");
668 let verification_index = SetupStep::ALL
669 .iter()
670 .position(|step| *step == SetupStep::Verification)
671 .expect("verification step");
672
673 assert!(persistence_index < verification_index);
674
675 let mut state = SetupState::default();
676 state.set_step(SetupStep::Language, verified("0.8.67"));
677 state.set_step(SetupStep::ProviderModel, verified("0.8.67"));
678 state.runtime_posture_source = RuntimePostureSource::Confirmed;
679 state.constitution_choice = ConstitutionChoice::Bundled;
680 assert!(state.first_run_ready());
681
682 state.set_step(
683 SetupStep::Persistence,
684 StepEntry::new(StepStatus::NeedsAction, false, "0.8.67"),
685 );
686 assert!(state.first_run_ready());
687 assert!(!state.operate_ready());
688 }
689
690 #[test]
691 fn first_run_ready_requires_all_pillars() {
692 let mut state = SetupState::default();
693 state.set_step(SetupStep::Language, verified("0.8.67"));
694 state.set_step(SetupStep::ProviderModel, verified("0.8.67"));
695 state.runtime_posture_source = RuntimePostureSource::Confirmed;
696 // Still missing an explicit constitution choice.
697 assert!(!state.first_run_ready());
698 state.constitution_choice = ConstitutionChoice::Bundled;
699 assert!(state.first_run_ready());
700 }
701
702 #[test]
703 fn operate_ready_is_separate_from_first_run_ready() {
704 let mut state = SetupState::default();
705 state.set_step(SetupStep::Language, verified("0.8.67"));
706 state.set_step(SetupStep::ProviderModel, verified("0.8.67"));
707 state.runtime_posture_source = RuntimePostureSource::Confirmed;
708 state.constitution_choice = ConstitutionChoice::Bundled;
709 assert!(state.first_run_ready());
710 assert!(!state.operate_ready());
711
712 state.set_step(SetupStep::OperateFleet, verified("0.8.67"));
713 assert!(
714 !state.operate_ready(),
715 "a legacy Verified card is not receipt proof"
716 );
717 state.operate_receipts_verified = true;
718 assert!(state.operate_ready());
719 }
720
721 #[test]
722 fn legacy_verified_operate_card_without_receipt_proof_fails_closed() {
723 let mut legacy = SetupState::default();
724 legacy.set_step(SetupStep::Language, verified("0.8.67"));
725 legacy.set_step(SetupStep::ProviderModel, verified("0.8.67"));
726 legacy.set_step(SetupStep::OperateFleet, verified("0.8.67"));
727 legacy.runtime_posture_source = RuntimePostureSource::Confirmed;
728 legacy.constitution_choice = ConstitutionChoice::Bundled;
729 let raw = serde_json::to_string(&legacy).expect("serialize legacy-style state");
730 assert!(!raw.contains("operate_receipts_verified"), "{raw}");
731
732 let loaded: SetupState = serde_json::from_str(&raw).expect("load legacy-style state");
733
734 assert_eq!(loaded.status(SetupStep::OperateFleet), StepStatus::Verified);
735 assert!(!loaded.operate_receipts_verified);
736 assert!(!loaded.operate_ready());
737 }
738
739 #[test]
740 fn operate_ready_requires_verified_provider_not_needs_action() {
741 let mut state = SetupState::default();
742 state.set_step(
743 SetupStep::ProviderModel,
744 StepEntry::new(StepStatus::NeedsAction, true, "0.8.67"),
745 );
746 state.runtime_posture_source = RuntimePostureSource::Confirmed;
747 state.set_step(SetupStep::OperateFleet, verified("0.8.67"));
748
749 assert!(!state.operate_ready());
750 }
751
752 #[test]
753 fn configured_provider_settles_first_run_without_verifying_operate() {
754 let mut state = SetupState::default();
755 state.set_step(SetupStep::Language, verified("test"));
756 state.set_step(
757 SetupStep::ProviderModel,
758 StepEntry::new(StepStatus::Configured, true, "test"),
759 );
760 state.set_step(SetupStep::OperateFleet, verified("test"));
761 state.runtime_posture_source = RuntimePostureSource::Confirmed;
762 state.constitution_choice = ConstitutionChoice::Bundled;
763 state.operate_receipts_verified = true;
764 assert!(state.first_run_ready());
765 assert!(!state.operate_ready());
766 state.set_step(SetupStep::ProviderModel, verified("test"));
767 assert!(state.operate_ready());
768 }
769
770 #[test]
771 fn needs_action_provider_still_reaches_ready() {
772 let mut state = SetupState::default();
773 state.set_step(SetupStep::Language, verified("0.8.67"));
774 state.set_step(
775 SetupStep::ProviderModel,
776 StepEntry::new(StepStatus::NeedsAction, true, "0.8.67"),
777 );
778 state.runtime_posture_source = RuntimePostureSource::Inherited;
779 state.constitution_choice = ConstitutionChoice::Deferred;
780 assert!(state.first_run_ready());
781 }
782
783 #[test]
784 fn deferred_constitution_counts_as_explicit_choice() {
785 assert!(ConstitutionChoice::Deferred.is_explicit());
786 assert!(ConstitutionChoice::Bundled.is_explicit());
787 assert!(!ConstitutionChoice::Unset.is_explicit());
788 }
789
790 #[test]
791 fn update_ready_tracks_checkpoint_version() {
792 let mut state = SetupState::default();
793 assert!(state.needs_constitution_checkpoint("0.8.67"));
794 state.complete_constitution_checkpoint("0.8.67", ConstitutionChoice::Bundled);
795 assert!(state.update_ready("0.8.67"));
796 assert!(!state.needs_constitution_checkpoint("0.8.67"));
797 // A later lane re-arms the checkpoint.
798 assert!(state.needs_constitution_checkpoint("0.8.68"));
799 }
800
801 #[test]
802 fn derive_inherited_marks_existing_user_safe() {
803 let facts = InheritedConfigFacts {
804 has_provider_route: true,
805 has_credentials_or_local_runtime: true,
806 trust_chosen: true,
807 language: Some("en".to_string()),
808 has_user_constitution: false,
809 has_expert_override: false,
810 user_constitution_validity: ConstitutionValidity::Unknown,
811 };
812 let state = SetupState::derive_inherited(&facts);
813 assert!(state.inherited);
814 assert_eq!(state.status(SetupStep::Language), StepStatus::Verified);
815 assert_eq!(
816 state.status(SetupStep::ProviderModel),
817 StepStatus::Configured
818 );
819 assert_eq!(state.status(SetupStep::TrustSandbox), StepStatus::Verified);
820 assert_eq!(state.constitution_source, ConstitutionSource::Bundled);
821 // The update checkpoint must still be shown to an upgrading user.
822 assert!(state.needs_constitution_checkpoint("0.8.67"));
823 }
824
825 #[test]
826 fn derive_inherited_classifies_provider_without_key_as_needs_action() {
827 let facts = InheritedConfigFacts {
828 has_provider_route: true,
829 has_credentials_or_local_runtime: false,
830 ..InheritedConfigFacts::default()
831 };
832 let state = SetupState::derive_inherited(&facts);
833 assert_eq!(
834 state.status(SetupStep::ProviderModel),
835 StepStatus::NeedsAction
836 );
837 }
838
839 #[test]
840 fn derive_inherited_picks_up_existing_user_constitution() {
841 let facts = InheritedConfigFacts {
842 has_user_constitution: true,
843 user_constitution_validity: ConstitutionValidity::Valid,
844 ..InheritedConfigFacts::default()
845 };
846 let state = SetupState::derive_inherited(&facts);
847 assert_eq!(state.constitution_source, ConstitutionSource::UserGlobal);
848 assert_eq!(state.constitution_choice, ConstitutionChoice::GuidedCustom);
849 assert_eq!(state.constitution_validity, ConstitutionValidity::Valid);
850 }
851
852 #[test]
853 fn round_trips_through_json_sidecar() {
854 let tmp = tempfile::tempdir().unwrap();
855 let path = tmp.path().join(SETUP_STATE_FILE_NAME);
856
857 let mut state = SetupState::default();
858 state.set_step(
859 SetupStep::ProviderModel,
860 verified("0.8.67").with_result("openai · mimo-ultraspeed"),
861 );
862 state.constitution_choice = ConstitutionChoice::GuidedCustom;
863 state.constitution_preview_version = 3;
864 state.save_to(&path).unwrap();
865
866 let loaded = SetupState::load_from(&path).expect("record should load");
867 assert_eq!(loaded, state);
868 // Enum keys serialize as snake_case strings.
869 let raw = std::fs::read_to_string(&path).unwrap();
870 assert!(raw.contains("\"provider_model\""), "{raw}");
871 assert!(raw.contains("openai · mimo-ultraspeed"));
872 }
873
874 #[test]
875 fn constitution_authoring_round_trips_and_stays_optional() {
876 let tmp = tempfile::tempdir().unwrap();
877 let path = tmp.path().join(SETUP_STATE_FILE_NAME);
878
879 let state = SetupState {
880 constitution_choice: ConstitutionChoice::GuidedCustom,
881 constitution_authoring: Some(ConstitutionAuthoring::ModelDrafted),
882 ..Default::default()
883 };
884 state.save_to(&path).unwrap();
885
886 let loaded = SetupState::load_from(&path).expect("record should load");
887 assert_eq!(
888 loaded.constitution_authoring,
889 Some(ConstitutionAuthoring::ModelDrafted)
890 );
891 let raw = std::fs::read_to_string(&path).unwrap();
892 assert!(raw.contains("\"model_drafted\""), "{raw}");
893 }
894
895 #[test]
896 fn record_without_authoring_field_still_loads() {
897 // Records written before the model-drafting lane carry no
898 // constitution_authoring key; they must load with None, not fail.
899 let tmp = tempfile::tempdir().unwrap();
900 let path = tmp.path().join(SETUP_STATE_FILE_NAME);
901 std::fs::write(
902 &path,
903 r#"{"schema_version":1,"constitution_choice":"guided_custom"}"#,
904 )
905 .unwrap();
906 let loaded = SetupState::load_from(&path).expect("legacy record should load");
907 assert_eq!(loaded.constitution_authoring, None);
908 assert_eq!(loaded.constitution_choice, ConstitutionChoice::GuidedCustom);
909 }
910
911 #[test]
912 fn corrupt_record_falls_back_to_none() {
913 let tmp = tempfile::tempdir().unwrap();
914 let path = tmp.path().join(SETUP_STATE_FILE_NAME);
915 std::fs::write(&path, "{ not valid json").unwrap();
916 assert!(SetupState::load_from(&path).is_none());
917 }
918
919 #[test]
920 fn missing_record_is_none_not_error() {
921 let tmp = tempfile::tempdir().unwrap();
922 let path = tmp.path().join("does-not-exist.json");
923 assert!(SetupState::load_from(&path).is_none());
924 }
925
926 #[test]
927 fn step_result_carries_no_secret_by_construction() {
928 // The result field is a caller-supplied safe summary; this documents the
929 // contract that callers pass names, not keys.
930 let entry = verified("0.8.67").with_result("provider: openai, model: mimo");
931 let json = serde_json::to_string(&entry).unwrap();
932 assert!(!json.to_lowercase().contains("sk-"));
933 }
934 }
935
935 lines RUST