Agents

Rust Memory + Consequence

Use Rust 1.85 or newer:

[dependencies]
neutron-ai = "0.2"
reqwest = { version = "0.13", default-features = false, features = ["json", "rustls"] }
serde_json = "1.0"
tokio = { version = "1.53", features = ["macros", "rt-multi-thread"] }

The SDK handles memory and agent context. reqwest calls industry-library and Consequence endpoints that are not yet exposed as typed Rust methods.

Client and authenticated REST helper

use neutron_ai::{ClientOptions, NeutronAIClient};
use reqwest::Client as HttpClient;
use serde_json::{Value, json};
use std::{env, error::Error};

const NUCLEUS_ID: &str = "checkout-platform";

fn required_env(name: &str) -> Result<String, Box<dyn Error>> {
    let value = env::var(name)?;
    if value.trim().is_empty() {
        return Err(format!("{name} is required").into());
    }
    Ok(value)
}

fn scoped(mut body: Value) -> Value {
    body["nucleusId"] = Value::String(NUCLEUS_ID.to_string());
    body
}

async fn post_json(
    http: &HttpClient,
    base_url: &str,
    token: &str,
    path: &str,
    body: Value,
) -> Result<Value, Box<dyn Error>> {
    let response = http
        .post(format!("{}{}", base_url.trim_end_matches('/'), path))
        .bearer_auth(token)
        .json(&body)
        .send()
        .await?
        .error_for_status()?;
    Ok(response.json::<Value>().await?)
}

fn memory_client(base_url: &str) -> Result<NeutronAIClient, Box<dyn Error>> {
    Ok(NeutronAIClient::new(ClientOptions {
        base_url: base_url.to_string(),
        token: Some(required_env("NEUTRON_API_TOKEN")?),
        nucleus_id: Some(NUCLEUS_ID.to_string()),
        tenant_id: None,
    })?)
}

Keep workspace, approver, and internal credentials outside the agent runtime.

Install knowledge and build context

async fn prepare_context(
    http: &HttpClient,
    base_url: &str,
    memory: &NeutronAIClient,
) -> Result<Value, Box<dyn Error>> {
    post_json(
        http,
        base_url,
        &required_env("NEUTRON_WORKSPACE_API_KEY")?,
        "/v1/platform/industry-library/plugins/ai-engineering-delivery/install",
        json!({ "nucleusId": NUCLEUS_ID }),
    )
    .await?;

    memory.remember(json!({
        "scopeId": "history:checkout-releases",
        "agentId": "agent:release-manager",
        "type": "experience",
        "privacyClass": "tenant",
        "text": concat!(
            "Release 3.7 used a 5% cohort for 20 minutes before expansion. ",
            "The rollout paused when database lock time exceeded 250 ms. ",
            "Rollback succeeded. Verify lock duration before expanding similar changes."
        ),
        "metadata": {
            "source": "approved-release-review",
            "release": "3.7",
            "outcome": "rolled-back"
        }
    })).await?;

    Ok(memory.agent_context(json!({
        "scopeIds": [
            "industry:ai-engineering-delivery",
            "service:checkout-api",
            "history:checkout-releases",
            "policy:production-change"
        ],
        "agentId": "agent:release-manager",
        "task": "Prepare a safe release recommendation for checkout API version 3.8.",
        "privacyClasses": ["tenant"],
        "tokenBudget": 1_600,
        "cachePolicy": {
            "mode": "prefer_cache",
            "keyMode": "intent_profile",
            "ttlSeconds": 300,
            "includeDynamicRag": true
        }
    })).await?)
}

Treat the returned promptContext as supporting context. Current evidence and the current task remain primary.

Plan, decide, and approve

async fn plan_and_decide(
    http: &HttpClient,
    base_url: &str,
) -> Result<Value, Box<dyn Error>> {
    let agent_token = required_env("NEUTRON_API_TOKEN")?;
    let run = post_json(
        http,
        base_url,
        &agent_token,
        "/v1/consequence/plan",
        scoped(json!({
            "scopeIds": [
                "industry:ai-engineering-delivery",
                "service:checkout-api",
                "history:checkout-releases",
                "policy:production-change"
            ],
            "agentId": "agent:release-manager",
            "task": "Compare delaying release 3.8, a 1% pilot, a 5% staged rollout, and immediate release while preserving compatibility and the lock budget.",
            "domain": "engineering_ops",
            "objectiveHints": [
                "Reduce customer impact",
                "Preserve rollback capability",
                "Collect evidence before expansion"
            ],
            "constraintHints": [
                "Database lock time must remain below the approved threshold",
                "Expansion requires the accountable release owner",
                "Rollback must remain available"
            ],
            "idempotencyKey": "checkout-3.8-release-review-v1",
            "retentionDays": 90,
            "contextPolicy": {
                "includeMemory": true,
                "includeKnowledge": true,
                "includeContextCapsules": true,
                "includePastDecisions": true,
                "includeReflections": true
            },
            "policy": {
                "mode": "deep",
                "depth": 10,
                "maxScenarios": 8,
                "maxRuntimeMs": 8_000,
                "requireApprovalAboveRisk": "medium",
                "allowExecution": false,
                "storeSafeArtifactsOnly": true,
                "includeCounterfactuals": true,
                "includeReflections": true
            }
        })),
    )
    .await?;

    let scenario_id = run["recommendedScenarioId"]
        .as_str()
        .ok_or("No scenario satisfied the current decision boundary")?;
    let run_id = run["runId"].as_str().ok_or("runId was not returned")?;
    let decided = post_json(
        http,
        base_url,
        &agent_token,
        "/v1/consequence/decide",
        scoped(json!({
            "runId": run_id,
            "scopeIds": ["service:checkout-api", "policy:production-change"],
            "selectedScenarioId": scenario_id,
            "decisionSummary": "Selected the bounded pilot scenario for owner review.",
            "rationaleSummary": "The pilot preserves rollback and gathers current lock evidence; expansion requires threshold compliance and owner review."
        })),
    )
    .await?;
    let decision = decided["decisionRecord"].clone();
    if decision.is_null() {
        return Err("The decision record was not created".into());
    }

    if decision["status"] == "draft" {
        post_json(
            http,
            base_url,
            &required_env("NEUTRON_APPROVER_TOKEN")?,
            "/v1/consequence/approve",
            scoped(json!({
                "decisionId": decision["decisionId"],
                "scopeIds": ["service:checkout-api", "policy:production-change"],
                "note": "Release owner approved the pilot only; expansion needs another review."
            })),
        )
        .await?;
    }
    Ok(decision)
}

Use the approver token only after verifying the authenticated human. Approval records authorization; it does not execute the release.

Observe and reflect

async fn observe_and_reflect(
    http: &HttpClient,
    base_url: &str,
    decision: &Value,
) -> Result<Value, Box<dyn Error>> {
    post_json(
        http,
        base_url,
        &required_env("NEUTRON_API_TOKEN")?,
        "/v1/consequence/observe",
        scoped(json!({
            "decisionId": decision["decisionId"],
            "scopeIds": ["service:checkout-api", "history:checkout-releases"],
            "summary": "The 1% pilot completed without customer errors and was held for review.",
            "observedMetrics": {
                "pilot_percent": 1,
                "pilot_minutes": 30,
                "database_lock_p95_ms": 180,
                "customer_error_rate": 0
            },
            "unexpectedConsequences": [
                "Cache warm-up took ten minutes longer than estimated."
            ],
            "sourceRefs": [
                "release-run:checkout-3.8-pilot",
                "dashboard:database-locks-2026-08-15"
            ]
        })),
    )
    .await?;

    post_json(
        http,
        base_url,
        &required_env("NEUTRON_INTERNAL_TOKEN")?,
        "/v1/consequence/reflect",
        scoped(json!({
            "decisionId": decision["decisionId"],
            "scopeIds": ["service:checkout-api", "history:checkout-releases"]
        })),
    )
    .await
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let base_url = required_env("NEUTRON_API_URL")?;
    let http = HttpClient::new();
    let memory = memory_client(&base_url)?;
    prepare_context(&http, &base_url, &memory).await?;
    let decision = plan_and_decide(&http, &base_url).await?;

    // Call only after a separately authorized action produces trusted evidence.
    let reflected = observe_and_reflect(&http, &base_url, &decision).await?;
    let lesson = reflected["reflectionLessons"].as_array().and_then(|items| items.last());
    if lesson.is_none() {
        return Err("Reflection did not return a lesson".into());
    }
    Ok(())
}

Review the reflection lesson before any durable memory promotion.

Return to the shared lifecycle and production checklist.