Doc system test

State file

The .cyan_state.yaml file - the only record of a project - its fields, who writes each one, and the rules a reader can rely on.

Meta block front matter of this doc
namespaces
  • durian.cloud/cyanprint/project-lifecycle
  • durian.cloud/cyanprint/composition
  • durian.cloud/cyanprint/prompting
type
format
issues
  • https://github.com/AtomiCloud/sulfone.iridium/issues?q=TBD+deterministic-state-not-saved
  • https://github.com/AtomiCloud/sulfone.iridium/issues?q=TBD+update-drops-history

What it is. .cyan_state.yaml sits at the root of a target folder. It is the whole client-side state of a project: which templates were installed, at which versions, with which answers.

What problem it solves. Every create and update rebuilds what the templates wrote last time by replaying them. This file holds exactly the inputs for that replay, and nothing else: no copy of old files.

What newcomers get wrong. There is no templates: key: each template record is a top-level key. And deterministic_states is always empty today, so it does not do what its name promises.

Shape

The file is YAML. Here is ./shop after step 3 of the shop example, with every field that can appear.

yamlyaml
atomi/web: # template record, key = <user>/<template>
active: true
history: # history entries, oldest first, never removed
- version: 5 # version number (not the version id)
time: 2026-03-01T10:00:00Z # UTC, when this entry was saved
answers: # every answer the template's whole tree used
node_version: { type: String, value: "22" }
module_type: { type: String, value: esm }
name: { type: String, value: shop }
port: { type: String, value: "3000" }
features: { type: StringArray, value: [docker] }
deterministic_states: {} # always written empty today
files: [.dockerignore, .editorconfig, ...] # paths this template made last run; omitted when empty
atomi/ci:
active: true
history:
- version: 2
time: 2026-03-09T16:20:00Z
answers:
ci_provider: { type: String, value: github }
deterministic_states: {}
files: [.editorconfig, .github/workflows/ci.yml, package.json]
managed_files: [.dockerignore, .editorconfig, ...] # sorted union of every files list; omitted when empty
file_conflicts: # clashes of the last layering pass; omitted when empty
- path: .editorconfig
resolution: lww_all_no_resolver
winner_template: 42c8d1e0-9a8b-4c7d-8e6f-5a4b3c2d1e0f
variations:
- template_id: e5d07b3a-2f1e-4d3c-9b8a-7f6e5d4c3b2a
- template_id: 42c8d1e0-9a8b-4c7d-8e6f-5a4b3c2d1e0f

Fields

The table lists every field, who writes it, and when. Paths are relative to the folder, with / separators.

FieldMeaningWritten
<user>/<template>one template record per stacked templatewhen create adds a template
activerun this template on create and updatetrue on add; nothing sets false
history[]history entries, oldest firstone appended per add, upgrade or rerun
history[].versionthe version number runwith the entry
history[].timewhen the entry was saved (Utc::now())with the entry
history[].answersquestion id to answer, as { type, value }with the entry
history[].deterministic_stateskey to value made by d.getwith the entry, always {}
filespaths this template's own output had last runrecomputed every run
managed_filessorted, de-duplicated union of every filesrecomputed every run
file_conflicts[]file clash records of the last layering passrecomputed every run

Answer type is one of String, StringArray or Bool. A select, text, password or date answer is a String; a checkbox is a StringArray; a confirm is a Bool.

file_conflicts[].resolution is one of these:

ValueMeaning
resolverevery writer voted the same conflict resolver and config; it merged them (resolver_used names it)
lww_all_no_resolverno writer voted a conflict resolver; the last layer won (winner_template)
lww_no_consensussome voted a conflict resolver, some none; the last layer won (with_resolver, without_resolver)
lww_ambiguous_resolverwriters voted different conflict resolvers or configs; the last layer won

Rules a reader can rely on

  • The last history entry is the truth. The next run replays history[-1]: its version, its answers, and its time as the stack order. Earlier entries are never read.
  • answers holds the whole tree's answers. A stacked template's entry holds every answer its dependency tree used, presets included (module_type above came from a preset, node_version from docker:7).
  • files comes from template output, not from the folder. It is taken from each template's own output before stacking, so a path appears under every template that made it, even one that lost a clash.
  • Lists are sorted. files and managed_files are sorted and de-duplicated; .cyan_state.yaml and .cyan_output are never listed.
  • The file is skipped by the merge. The local set never includes it, so it can never get conflict markers.
  • A missing file means "new folder". No file: the first create treats the folder as having no templates; an existing folder's files are then merged against an empty base.

Who reads and writes it

Here is the real code that loads, appends to and rewrites the file.

sulfone.iridiumcyancoordinator/src/state/models.rs
  1. lines 8-40The three types: history entry, template record, and the file with records flattened to the top level.
    cyancoordinator/src/state/models.rs:8-40rust
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct TemplateHistoryEntry {
    pub version: i64,
    pub time: DateTime<Utc>,
    pub answers: HashMap<String, Answer>,
    pub deterministic_states: HashMap<String, String>,
    }
    #[derive(Debug, Serialize, Deserialize)]
    pub struct TemplateState {
    pub active: bool,
    pub history: Vec<TemplateHistoryEntry>,
    /// Normalized, path-only snapshot of the files this template produced on the
    /// most recent run. Empty for templates that produced nothing.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub files: Vec<String>,
    }
    #[derive(Debug, Serialize, Deserialize, Default)]
    pub struct CyanState {
    #[serde(flatten)]
    pub templates: HashMap<String, TemplateState>,
    /// Sorted, de-duplicated union of every active template's output paths — the
    /// path-only manifest of cyanprint-managed files.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub managed_files: Vec<String>,
    /// File conflicts resolved during layering
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub file_conflicts: Vec<FileConflictEntry>,
    }
  2. lines 52-61managed files: each record's files set from this run, the union sorted and de-duplicated.
    cyancoordinator/src/state/models.rs:52-61rust
    pub fn set_managed_files(&mut self, managed_by_template: &HashMap<String, Vec<String>>) {
    for (key, ts) in self.templates.iter_mut() {
    ts.files = managed_by_template.get(key).cloned().unwrap_or_default();
    }
    let mut all: Vec<String> = managed_by_template.values().flatten().cloned().collect();
    all.sort();
    all.dedup();
    self.managed_files = all;
    }
  3. sulfone.iridium/cyancoordinator/src/state/services.rs:24-36Load: no file gives an empty state.
    cyancoordinator/src/state/services.rs:24-36rust
    impl StateReader for DefaultStateManager {
    fn load_state_file(&self, path: &Path) -> Result<CyanState, Box<dyn Error + Send>> {
    if path.exists() {
    let file = fs::File::open(path).map_err(|e| Box::new(e) as Box<dyn Error + Send>)?;
    let reader = BufReader::new(file);
    let state: CyanState = serde_yaml::from_reader(reader)
    .map_err(|e| Box::new(e) as Box<dyn Error + Send>)?;
    Ok(state)
    } else {
    Ok(CyanState::default())
    }
    }
    }
  4. sulfone.iridium/cyancoordinator/src/state/services.rs:50-88Append a history entry: reload, push, save. The deterministic map is always new and empty.
    cyancoordinator/src/state/services.rs:50-88rust
    fn save_template_metadata(
    &self,
    target_dir: &Path,
    template: &TemplateVersionRes,
    answers: &HashMap<String, Answer>,
    _template_state: &TemplateState,
    username: &str,
    ) -> Result<(), Box<dyn Error + Send>> {
    let state_file_path = target_dir.join(".cyan_state.yaml");
    let mut state = self.load_state_file(&state_file_path)?;
    let template_key = format!("{}/{}", username, template.template.name);
    let deterministic_states = HashMap::new();
    let history_entry = TemplateHistoryEntry {
    version: template.principal.version,
    time: Utc::now(),
    answers: answers.clone(),
    deterministic_states,
    };
    let template_state_entry =
    state
    .templates
    .entry(template_key)
    .or_insert(YamlTemplateState {
    active: true,
    history: Vec::new(),
    files: Vec::new(),
    });
    template_state_entry.history.push(history_entry);
    self.save_state_file(&state, &state_file_path)?;
    Ok(())
    }
  5. sulfone.iridium/cyanprint/src/run.rs:856-869create: reload after the batch run, set file_conflicts and managed files, save.
    cyanprint/src/run.rs:856-869rust
    // Persist file conflicts to state file (always update to clear stale entries)
    let state_manager = DefaultStateManager::new();
    let mut cyan_state = state_manager
    .load_state_file(&state_file_path)
    .unwrap_or_default();
    let conflicts_count = file_conflicts.len();
    cyan_state.file_conflicts = file_conflicts;
    // Recompute the managed-files manifest wholesale from this run's active
    // templates: sets each template's `files` and the top-level `managed_files`
    // union, clearing stale entries (e.g. for now-deactivated templates).
    cyan_state.set_managed_files(&managed_by_template);
    let managed_count = cyan_state.managed_files.len();
    // A save failure here drops the still-armed `session_guard`, releasing the sessions.
    state_manager.save_state_file(&cyan_state, &state_file_path)?;
  6. sulfone.iridium/cyanprint/src/update/orchestrator.rs:161-168update: load once, before the run.
    cyanprint/src/update/orchestrator.rs:161-168rust
    let state_file_path = target_dir.join(".cyan_state.yaml");
    let state_manager = DefaultStateManager::new();
    let mut cyan_state = state_manager
    .load_state_file(&state_file_path)
    .map_err(|e| {
    Box::new(std::io::Error::other(format!("Failed to load state: {e}")))
    as Box<dyn Error + Send>
    })?;
  7. sulfone.iridium/cyanprint/src/update/orchestrator.rs:272-279update: save that early copy, which drops the history entries the batch run appended.
    cyanprint/src/update/orchestrator.rs:272-279rust
    // Persist file conflicts to state file (always update to clear stale entries)
    let conflicts_count = file_conflicts.len();
    cyan_state.file_conflicts = file_conflicts;
    // Recompute the managed-files manifest wholesale from this run's active templates.
    cyan_state.set_managed_files(&managed_by_template);
    let managed_count = cyan_state.managed_files.len();
    // A save failure here drops the still-armed `session_guard`, releasing the sessions.
    state_manager.save_state_file(&cyan_state, &state_file_path)?;

Why it is shaped this way

Questions for the designer

  1. Why are template records top-level keys instead of under templates:?
  2. Was saving deterministic_states as {} a known gap, or a choice?
  3. active is read but never set to false. Was removing a stacked template planned?
  4. Should history[].answers drop answers to questions the template no longer asks?