Doc system test

Prompt outcome

How one template's question loop ends - QnA, Complete, NeedInput or Err - what each carries, and what the executor, composition and CLI do with it.

Meta block front matter of this doc
namespaces
  • durian.cloud/cyanprint/prompting
  • durian.cloud/cyanprint/composition
  • durian.cloud/cyanprint/coordinator
  • durian.cloud/cyanprint/project-lifecycle
type
format
related
issues
  • https://github.com/AtomiCloud/sulfone.iridium/issues?q=TBD+interactive-error-exits-zero

What it is. A prompt outcome is the value one template's question loop returns. The code calls it TemplateState (in cyanprompt); it has four variants: QnA, Complete, NeedInput and Err.

What problem it solves. The loop can end three ways: every question answered, a headless run missing an answer, or a failure. The caller must tell them apart without parsing text, because each leads somewhere else: build the files, print a question and stop, or report an error.

What newcomers get wrong. TemplateState is also the name of the template record type in the state file code; the two are unrelated, so say "prompt outcome". QnA is not an outcome anyone sees: it only means "keep looping". And Complete carries no deterministic state.

The state machine below is one loop, interactive or headless.

stateDiagram-v2
  [*] --> QnA: start_with / start_headless
  QnA --> QnA: question reply, answer accepted (interactive)<br/>or supplied answer valid (headless)
  QnA --> Complete: final reply
  QnA --> NeedInput: headless only, question id not supplied
  QnA --> Err: transport or decode error, prompt error,<br/>headless validation refused, 1000-call cap
  QnA --> Exit0: interactive, Esc with an empty answer map
  Complete --> [*]: build phase
  NeedInput --> [*]: envelope need_input, exit 2
  Err --> [*]: Template Prompting Error
  Exit0 --> [*]: process ends, exit code 0
The prompt outcome as a state machine

What each variant carries

The table lists every variant, what it holds and who makes it.

VariantHoldsMade by
QnAnothingthe loop, between init calls
Completethe Cyan, the answer mapa final reply (interactive and headless)
NeedInputthe question, the map from its replyheadless walk, unsupplied id
Erra message stringany failure in the loop
  • Interactive Complete holds the whole answer map the loop ended with, including answers the script never read.
  • Headless Complete holds only the revealed answers, not the whole supplied map.
  • A headless Err message names question ids only, never a value (secret redaction).

What happens to each outcome

  1. Executor (DefaultTemplateExecutor::execute_template), per template run:
    • Complete: send the Cyan to the coordinator's build phase; return the archive, the outcome and the session id.
    • NeedInput: skip the build; return an empty archive, the outcome and the session id.
    • Err: release the warmed session; return a ProblemDetails error with title 🚨 Template Prompting Error, status 400, type local and data: { "error": <message> }.
    • QnA: cannot reach here; the code panics if it does.
  2. Composition run, per node:
    • Complete: unpack the archive, store it in the node cache, merge the answers into the composition state.
    • NeedInput: prefix the question id when answer namespacing is on, record it, stop the tree, return an empty file set. Never cached.
  3. CLI, per command:
    • headless: NeedInput → need_input envelope, exit 2; a done run → done, exit 0; an error → error, exit 1 (headless mode).
    • interactive create and update: an error is printed with Error: and the command still returns success (exit 0).

Here is the real code, from the type to the executor's handling.

sulfone.iridiumcyanprompt/src/domain/services/template/states.rs
  1. lines 7-18Four variants; NeedInput carries the question and the map from its reply.
    cyanprompt/src/domain/services/template/states.rs:7-18rust
    pub enum TemplateState {
    QnA(),
    Complete(Cyan, HashMap<String, Answer>),
    /// Headless replay reached a question that has no supplied answer yet.
    ///
    /// Carries the unanswered `Question` and the deterministic state accumulated
    /// from the coordinator up to that point. This is a terminal state for the
    /// headless driver: the caller emits the question and stops, expecting the
    /// next invocation to supply the answer (stateless replay).
    NeedInput(Question, HashMap<String, String>),
    Err(String),
    }
  2. lines 20-28Only QnA continues the loop.
    cyanprompt/src/domain/services/template/states.rs:20-28rust
    impl TemplateState {
    pub fn cont(&self) -> bool {
    match self {
    TemplateState::QnA() => true,
    TemplateState::Complete(_, _) => false,
    TemplateState::NeedInput(_, _) => false,
    TemplateState::Err(_) => false,
    }
    }
  3. sulfone.iridium/cyanprompt/src/domain/services/template/engine.rs:84-93Interactive: a final reply becomes Complete; any error becomes Err with its text.
    cyanprompt/src/domain/services/template/engine.rs:84-93rust
    TemplateOutput::Final(c) => {
    Ok(TemplateState::Complete(c.cyan, answers.clone()))
    }
    });
    state = match result {
    Ok(ok) => ok,
    Err(err) => TemplateState::Err(err.to_string()),
    };
    }
  4. sulfone.iridium/cyancoordinator/src/template/executor.rs:247-253NeedInput: no build, empty archive, session id handed back.
    cyancoordinator/src/template/executor.rs:247-253rust
    // Headless: a NeedInput is a terminal, NON-error outcome. Surface it to the
    // caller without producing an archive — the build phase is skipped because
    // there is no finalized Cyan yet (the caller will emit the question and stop).
    if let TemplateState::NeedInput(_, _) = &prompter_state {
    let actual_session_id = executor_warm.session_id.clone();
    return Ok((Vec::new(), prompter_state, actual_session_id));
    }
  5. sulfone.iridium/cyancoordinator/src/template/executor.rs:255-280Complete goes on to the build; Err releases the session and becomes a Template Prompting Error.
    cyancoordinator/src/template/executor.rs:255-280rust
    let res = match &prompter_state {
    TemplateState::QnA() => panic!("Should terminate in QnA state"),
    TemplateState::NeedInput(_, _) => {
    unreachable!("NeedInput is handled by the early return above")
    }
    TemplateState::Complete(ref c, _) => {
    cprogress!(headless, "✅ Cyan Response obtained");
    Ok(c.clone())
    }
    TemplateState::Err(ref e) => {
    cprogress!(headless, "Error: {e}");
    // Q&A failed after warm/bootstrap — clean the leaked session before
    // surfacing the error.
    clean_warmed_session();
    Err(Box::new(GenericError::ProblemDetails(
    crate::errors::ProblemDetails {
    title: "🚨 Template Prompting Error".to_string(),
    status: 400,
    t: "local".to_string(),
    trace_id: None,
    data: Some(serde_json::json!({
    "error": e.to_string(),
    })),
    },
    )) as Box<dyn Error + Send>)
    }
  6. sulfone.iridium/cyancoordinator/src/operations/composition/state.rs:48-74The composition merges Complete answers and records a NeedInput question.
    cyancoordinator/src/operations/composition/state.rs:48-74rust
    match template_state {
    TemplateState::Complete(_, answers) => {
    // Merge answers into shared state
    for (key, value) in answers.iter() {
    if let Some(existing) = self.shared_answers.get(key) {
    // Type conflict check - surface as a recoverable error rather
    // than panicking on a merge path.
    if discriminant(existing) != discriminant(value) {
    return Err(Box::new(std::io::Error::new(
    std::io::ErrorKind::InvalidData,
    format!(
    "type conflict for key '{key}': existing answer type differs from new answer type"
    ),
    )) as Box<dyn Error + Send>);
    }
    }
    self.shared_answers.insert(key.clone(), value.clone());
    }
    }
    TemplateState::NeedInput(question, _) => {
    // Headless: record the unanswered question (domain type) so the
    // composition can short-circuit and surface it to the CLI, which converts
    // it to the wire representation at the point of emission.
    self.need_input = Some(question.clone());
    }
    TemplateState::QnA() | TemplateState::Err(_) => {}
    }

Worked example: three runs of web:5, three outcomes

Step through the outcome of the web:5 node in three runs of cyanprint create atomi/web:5 ./shop.

web:5's outcome in three runs
  1. Interactive

    The user answers name, port and features; init call 4 returns the final reply.

    outcomeComplete
    holdsCyan + {node_version, module_type, name, port, features}
    nextbuild phase, files written
  2. Headless, name missing

    The answers file has node_version only. docker:7, lint:2 and node-base:3 complete; web:5's walk reaches name with no supplied answer.

    outcomeNeedInput
    holdsquestion e5d07b3a-…/name
    nextenvelope need_input, exit 2, ./shop removed
  3. Headless, port 80

    The answers file has every answer, but port is 80. The discovery walk validates it; web:5's validator refuses.

    outcomeErr
    holdsinvalid answer for question 'port': Use a port from 1024 to 65535
    nextenvelope error, exit 1, ./shop removed

Why it is built this way

Hard cases

  • Interactive errors exit 0. Create and update print the error and return success (main.rs:458-463, 514-521); a script around the interactive CLI cannot see the failure from the exit code. The folder create made stays, because the folder guard acts only in headless runs (run.rs:419-425). Ctrl-C is such an error (question).
  • A validate call with an error body is not an Err. The reply decodes as "accepted", so no outcome changes (question protocol).
  • Esc can end the process inside the loop with exit 0, without any outcome (question).
  • No convergence cap interactively. The interactive loop runs while the outcome is QnA; a template that keeps asking runs forever. Each headless walk stops at 1000 calls.
  • Complete may hold extra answers. Interactive Complete returns every answer it started with, read or not, and they are merged into the composition state and saved.
  • The map in NeedInput is dropped by the CLI: the envelope has no field for it.
  • Two TemplateStates. Searching the code for TemplateState finds the prompt outcome (cyanprompt) and the template record (cyancoordinator state models).

Questions for the designer

  1. Should interactive create and update exit non-zero on an error outcome?
  2. Should Err carry a kind (refused answer, transport, template crash) so callers can react?
  3. Should Complete carry only the answers the script read, in interactive mode too?