Build cacheable embodied newsroom

This commit is contained in:
Meta Vens 2026-08-29 23:48:30 +02:00
commit 901cfcd587
16 changed files with 1286 additions and 646 deletions

View file

@ -1,6 +1,6 @@
use crate::model::{
ModelPort, ModelStageReceipt, ModelStageRequest, mark_model_receipt_semantic_invalid,
run_validated_stage,
ModelInputItem, ModelPort, ModelStageReceipt, ModelStageRequest,
mark_model_receipt_semantic_invalid, render_model_input, run_validated_conversation_stage,
};
use async_trait::async_trait;
use serde::{Serialize, de::DeserializeOwned};
@ -147,7 +147,10 @@ pub async fn run_model_agent_progress<Tool: ModelAgentTool>(
}
let mut receipts = Vec::new();
let mut transcript = String::new();
let mut input = vec![ModelInputItem::user(format!(
"{}\n\nAGENT STEP: 1 of {}. Choose one typed tool action admitted by the current output schema. The harness will execute it against the frozen state and return the real tool observation. Do not claim success yourself; only an accepted tool result can end the task.",
spec.instructions, spec.max_steps
))];
let mut last_observation = None;
for step in 0..spec.max_steps {
let action_schema = match tool.action_schema() {
@ -162,37 +165,18 @@ pub async fn run_model_agent_progress<Tool: ModelAgentTool>(
});
}
};
let action_schema_text = match serde_json::to_string(&action_schema) {
Ok(schema) => schema,
Err(error) => {
return Err(ModelAgentFailure {
message: format!(
"model agent {} could not serialize its current action schema: {error}",
spec.stage
),
receipts,
});
}
};
let source_receipt_ids = causal_source_ids(&spec.source_receipt_ids, &receipts);
let request = ModelStageRequest {
stage: spec.stage.clone(),
model: spec.model.clone(),
snapshot_binding: spec.snapshot_binding.clone(),
lived_stream: format!(
"CURRENT LEGAL TOOL ACTION SCHEMA:\n{}\n\n{}{}\n\nAGENT STEP: {} of {}. Choose one typed tool action admitted by the current schema. The harness will execute it against the frozen state and return the real tool observation. Do not claim success yourself; only an accepted tool result can end the task.",
action_schema_text,
spec.instructions,
transcript,
step + 1,
spec.max_steps,
),
lived_stream: render_model_input(&input),
output_schema: Some(action_schema),
source_receipt_ids,
temperature: spec.temperature,
max_output_tokens: spec.max_output_tokens,
};
let mut stage = match run_validated_stage(port, &request).await {
let mut stage = match run_validated_conversation_stage(port, &request, &input).await {
Ok(stage) => stage,
Err(error) => {
return Err(ModelAgentFailure {
@ -212,12 +196,14 @@ pub async fn run_model_agent_progress<Tool: ModelAgentTool>(
"message":"agent returned no typed action",
});
mark_model_receipt_semantic_invalid(&mut stage.receipt, &finding);
transcript.push_str(&tool_observation(
append_agent_observation(
&mut input,
&stage.narrative,
step,
spec.max_steps,
"rejected",
&serde_json::Value::Null,
&finding,
));
);
last_observation = Some(finding);
receipts.push(stage.receipt);
continue;
@ -231,7 +217,14 @@ pub async fn run_model_agent_progress<Tool: ModelAgentTool>(
"message":error.to_string(),
});
mark_model_receipt_semantic_invalid(&mut stage.receipt, &finding);
transcript.push_str(&tool_observation(step, "rejected", &action_value, &finding));
append_agent_observation(
&mut input,
&stage.narrative,
step,
spec.max_steps,
"rejected",
&finding,
);
last_observation = Some(finding);
receipts.push(stage.receipt);
continue;
@ -266,12 +259,14 @@ pub async fn run_model_agent_progress<Tool: ModelAgentTool>(
return Err(ModelAgentFailure { message, receipts });
}
};
transcript.push_str(&tool_observation(
append_agent_observation(
&mut input,
&stage.narrative,
step,
spec.max_steps,
"continued",
&action_value,
&observation,
));
);
last_observation = Some(observation);
receipts.push(stage.receipt);
receipts.extend(tool_receipts);
@ -305,7 +300,14 @@ pub async fn run_model_agent_progress<Tool: ModelAgentTool>(
}
};
mark_model_receipt_semantic_invalid(&mut stage.receipt, &finding);
transcript.push_str(&tool_observation(step, "rejected", &action_value, &finding));
append_agent_observation(
&mut input,
&stage.narrative,
step,
spec.max_steps,
"rejected",
&finding,
);
last_observation = Some(finding);
receipts.push(stage.receipt);
receipts.extend(tool_receipts);
@ -346,18 +348,23 @@ pub(crate) fn causal_source_ids(base: &[String], receipts: &[ModelStageReceipt])
.collect()
}
fn tool_observation(
fn append_agent_observation(
input: &mut Vec<ModelInputItem>,
assistant_output: &str,
step: usize,
max_steps: usize,
status: &str,
action: &serde_json::Value,
observation: &serde_json::Value,
) -> String {
format!(
"\n\nTOOL OBSERVATION AFTER AGENT STEP {} ({status}):\n{}\nPREVIOUS TOOL ACTION:\n{}\nReturn the next complete typed tool action. Preserve frozen identity and useful valid draft work; change only what the observation actually rejects or requests.",
step + 1,
serde_json::to_string(observation).unwrap_or_else(|_| "null".into()),
serde_json::to_string(action).unwrap_or_else(|_| "null".into()),
)
) {
input.push(ModelInputItem::assistant(assistant_output));
if step + 1 < max_steps {
input.push(ModelInputItem::user(format!(
"TOOL OBSERVATION AFTER AGENT STEP {} ({status}):\n{}\n\nAGENT STEP: {} of {max_steps}. Return the next complete typed tool action. Preserve frozen identity and useful valid draft work; change only what the observation actually rejects or requests.",
step + 1,
serde_json::to_string(observation).unwrap_or_else(|_| "null".into()),
step + 2,
)));
}
}
#[cfg(test)]
@ -556,7 +563,13 @@ mod tests {
);
let requests = model.requests.lock().unwrap();
assert!(requests[1].lived_stream.contains("wrong_value"));
assert!(requests[1].lived_stream.contains("PREVIOUS TOOL ACTION"));
assert!(requests[1].lived_stream.contains("ASSISTANT:"));
assert!(
requests[1]
.lived_stream
.starts_with(&requests[0].lived_stream)
);
assert_eq!(requests[0].output_schema, requests[1].output_schema);
}
#[tokio::test]
@ -633,11 +646,10 @@ mod tests {
"accepted"
);
assert!(
requests[1]
!requests[1]
.lived_stream
.contains("CURRENT LEGAL TOOL ACTION SCHEMA")
);
assert!(requests[1].lived_stream.contains(r#""const":"accepted""#));
}
#[tokio::test]

View file

@ -2013,9 +2013,11 @@ async fn main() -> anyhow::Result<()> {
let issue_campaign = completed_wave_issue_campaign(&wave_reports, report_index)?;
let issue_title = format!("{newspaper_title} — Issue {wave_index}");
let source_campaign_digest = strategic_smoke_digest(&issue_campaign)?;
let newsroom = ghostlight_dungeon::newspaper::canopy_ledger_newsroom();
let editorial_contract_digest = strategic_smoke_digest(&serde_json::json!({
"title":&issue_title,
"editorial_voice":&newspaper_voice,
"newsroom":&newsroom,
"max_articles":5,
}))?;
let recomposition_path =
@ -2040,6 +2042,7 @@ async fn main() -> anyhow::Result<()> {
&issue_campaign,
&issue_title,
&newspaper_voice,
&newsroom,
5,
&store,
import.import,
@ -2397,6 +2400,7 @@ async fn compose_persisted_newspaper(
campaign,
title,
editorial_voice,
&ghostlight_dungeon::newspaper::canopy_ledger_newsroom(),
max_articles,
store,
)

View file

@ -8310,7 +8310,7 @@ mod tests {
&& request.lived_stream.contains("duplicate_statement")
&& request.lived_stream.contains("fact:refuge_authority")
&& request.lived_stream.contains("fact:refuge_resources")
&& request.lived_stream.contains("PREVIOUS TOOL ACTION"),
&& request.lived_stream.contains("ASSISTANT:"),
Ordering::SeqCst,
);
Ok(serde_json::json!({

View file

@ -323,6 +323,7 @@ pub struct WorldNewspaperRequest {
pub title: String,
#[schemars(length(min = 1, max = 600))]
pub editorial_voice: String,
pub newsroom: crate::newspaper::WorldNewspaperNewsroom,
#[schemars(range(min = 1, max = 6))]
pub max_articles: u16,
}

View file

@ -594,7 +594,7 @@ fn schema_catalog() -> Value {
"ghostlight.external_proposal_list.v1": schemars::schema_for!(crate::consumer::ExternalProposalList),
"ghostlight.external_proposal_acknowledgement.v1": schemars::schema_for!(crate::consumer::ExternalProposalAcknowledgement),
"ghostlight.external_proposal_receipt.v1": schemars::schema_for!(crate::consumer::ExternalProposalReceipt),
"ghostlight.world_newspaper_request.v2": schemars::schema_for!(crate::consumer::WorldNewspaperRequest),
"ghostlight.world_newspaper_request.v3": schemars::schema_for!(crate::consumer::WorldNewspaperRequest),
"ghostlight.world_newspaper_issue.v3": schemars::schema_for!(crate::newspaper::WorldNewspaperIssue)
})
}
@ -627,7 +627,7 @@ mod tests {
assert!(schemas["ghostlight.campaign.v1"]["$schema"].is_string());
assert!(schemas["ghostlight.session_zero.v1"]["$schema"].is_string());
assert!(schemas["ghostlight.vault_source_manifest.v1"]["$schema"].is_string());
assert!(schemas["ghostlight.world_newspaper_request.v2"]["$schema"].is_string());
assert!(schemas["ghostlight.world_newspaper_request.v3"]["$schema"].is_string());
assert!(schemas["ghostlight.world_newspaper_issue.v3"]["$schema"].is_string());
assert!(!schemas.contains_key("ghostlight.persona_stage_receipt.v1"));
assert!(!schemas.contains_key("ghostlight.world_mutation.v1"));

View file

@ -32,6 +32,44 @@ pub struct ModelStageRequest {
pub max_output_tokens: Option<u32>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "role", rename_all = "snake_case", deny_unknown_fields)]
pub enum ModelInputItem {
UserText { text: String },
AssistantText { text: String },
}
impl ModelInputItem {
pub fn user(text: impl Into<String>) -> Self {
Self::UserText { text: text.into() }
}
pub fn assistant(text: impl Into<String>) -> Self {
Self::AssistantText { text: text.into() }
}
fn text(&self) -> &str {
match self {
Self::UserText { text } | Self::AssistantText { text } => text,
}
}
}
pub fn render_model_input(items: &[ModelInputItem]) -> String {
items
.iter()
.map(|item| match item {
ModelInputItem::UserText { text } => format!("USER:\n{text}"),
ModelInputItem::AssistantText { text } => format!("ASSISTANT:\n{text}"),
})
.collect::<Vec<_>>()
.join("\n\n")
}
fn model_input_chars(items: &[ModelInputItem]) -> usize {
items.iter().map(|item| item.text().chars().count()).sum()
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ModelStageReceipt {
pub schema: String,
@ -165,6 +203,15 @@ pub trait ModelPort: Send + Sync {
..Default::default()
})
}
async fn run_observed_conversation(
&self,
request: &ModelStageRequest,
input: &[ModelInputItem],
) -> Result<ModelProviderOutput> {
let mut projected = request.clone();
projected.lived_stream = render_model_input(input);
self.run_observed(&projected).await
}
fn provider(&self) -> &'static str;
fn attempt_timeout(&self, _request: &ModelStageRequest) -> std::time::Duration {
std::time::Duration::from_secs(45)
@ -175,13 +222,36 @@ pub async fn run_validated_stage(
port: &dyn ModelPort,
request: &ModelStageRequest,
) -> Result<ModelStageOutput> {
run_validated_stage_with_timeout(port, request, port.attempt_timeout(request)).await
run_validated_stage_inner(port, request, port.attempt_timeout(request), None).await
}
pub async fn run_validated_conversation_stage(
port: &dyn ModelPort,
request: &ModelStageRequest,
input: &[ModelInputItem],
) -> Result<ModelStageOutput> {
run_validated_stage_inner(
port,
request,
port.attempt_timeout(request),
Some(input.to_vec()),
)
.await
}
pub async fn run_validated_stage_with_timeout(
port: &dyn ModelPort,
request: &ModelStageRequest,
timeout: std::time::Duration,
) -> Result<ModelStageOutput> {
run_validated_stage_inner(port, request, timeout, None).await
}
async fn run_validated_stage_inner(
port: &dyn ModelPort,
request: &ModelStageRequest,
timeout: std::time::Duration,
mut conversation: Option<Vec<ModelInputItem>>,
) -> Result<ModelStageOutput> {
let validator = request
.output_schema
@ -202,10 +272,15 @@ pub async fn run_validated_stage_with_timeout(
let mut transport_attempt = 0;
loop {
let started = Instant::now();
let (failure_kind, diagnostic) = match tokio::time::timeout(
timeout,
port.run_observed(&attempt_request),
)
let (failure_kind, diagnostic) = match tokio::time::timeout(timeout, async {
match conversation.as_deref() {
Some(input) => {
port.run_observed_conversation(&attempt_request, input)
.await
}
None => port.run_observed(&attempt_request).await,
}
})
.await
{
Ok(Ok(output)) => break (output, started.elapsed().as_millis() as u64),
@ -216,7 +291,10 @@ pub async fn run_validated_stage_with_timeout(
"model stage {} timed out after {} seconds with {} input characters",
request.stage,
timeout.as_secs(),
attempt_request.lived_stream.chars().count()
conversation.as_deref().map_or_else(
|| attempt_request.lived_stream.chars().count(),
model_input_chars,
)
),
),
};
@ -269,8 +347,11 @@ pub async fn run_validated_stage_with_timeout(
.expect("attempt was just recorded")
.local_validation_error = Some("provider returned an empty response".into());
if attempt == 0 {
attempt_request.lived_stream.push_str(
"\n\nLOCAL VALIDATOR: The previous response was empty. Return one complete response against the same snapshot and output contract.",
append_validation_retry(
&mut attempt_request,
&mut conversation,
&output,
"LOCAL VALIDATOR: The previous response was empty. Return one complete response against the same snapshot and output contract.".into(),
);
continue;
}
@ -299,9 +380,14 @@ pub async fn run_validated_stage_with_timeout(
.expect("attempt was just recorded")
.local_validation_error = Some(bounded_validation_error(&diagnostic));
if attempt == 0 {
attempt_request.lived_stream.push_str(&format!(
"\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS JSON: {diagnostic}\nReturn one corrected complete JSON object against the same snapshot and schema."
));
append_validation_retry(
&mut attempt_request,
&mut conversation,
&output,
format!(
"LOCAL VALIDATOR REJECTED THE PREVIOUS JSON: {diagnostic}\nReturn one corrected complete JSON object against the same snapshot and schema."
),
);
continue;
}
return Err(anyhow!(
@ -319,9 +405,14 @@ pub async fn run_validated_stage_with_timeout(
.last_mut()
.expect("attempt was just recorded")
.local_validation_error = Some(bounded_validation_error(&error));
attempt_request.lived_stream.push_str(&format!(
"\n\nLOCAL VALIDATOR COULD NOT PARSE THE PREVIOUS RESPONSE AS JSON: {error}\nReturn one corrected complete JSON object against the same snapshot and schema."
));
append_validation_retry(
&mut attempt_request,
&mut conversation,
&output,
format!(
"LOCAL VALIDATOR COULD NOT PARSE THE PREVIOUS RESPONSE AS JSON: {error}\nReturn one corrected complete JSON object against the same snapshot and schema."
),
);
continue;
}
Err(error) => {
@ -345,6 +436,9 @@ pub async fn run_validated_stage_with_timeout(
let receipt_model = resolved_model.unwrap_or_else(|| attempt_request.model.clone());
let mut receipted_request = attempt_request.clone();
receipted_request.model.clone_from(&receipt_model);
if let Some(input) = conversation.as_deref() {
receipted_request.lived_stream = render_model_input(input);
}
let request_bytes = serde_json::to_vec(&receipted_request)?;
let provider = port.provider().to_owned();
let request_hash = format!("sha256:{:x}", Sha256::digest(&request_bytes));
@ -380,7 +474,10 @@ pub async fn run_validated_stage_with_timeout(
latency_ms: stage_started.elapsed().as_millis() as u64,
validation_result: "valid".into(),
local_validation_error: None,
input_chars: attempt_request.lived_stream.chars().count(),
input_chars: conversation.as_deref().map_or_else(
|| attempt_request.lived_stream.chars().count(),
model_input_chars,
),
output_chars: output.chars().count(),
provider_attempts,
},
@ -389,6 +486,23 @@ pub async fn run_validated_stage_with_timeout(
unreachable!()
}
fn append_validation_retry(
request: &mut ModelStageRequest,
conversation: &mut Option<Vec<ModelInputItem>>,
rejected_output: &str,
diagnostic: String,
) {
if let Some(input) = conversation.as_mut() {
if !rejected_output.trim().is_empty() {
input.push(ModelInputItem::assistant(rejected_output));
}
input.push(ModelInputItem::user(diagnostic));
} else {
request.lived_stream.push_str("\n\n");
request.lived_stream.push_str(&diagnostic);
}
}
fn bounded_validation_error(error: &impl std::fmt::Display) -> String {
error.to_string().chars().take(1_000).collect()
}

View file

@ -15,8 +15,8 @@ use tokio::sync::Semaphore;
use zeroize::Zeroizing;
use crate::model::{
MODEL_BALANCED, MODEL_CAPABLE, MODEL_FAST, ModelPort, ModelProviderOutput, ModelStageRequest,
ModelTokenUsage,
MODEL_BALANCED, MODEL_CAPABLE, MODEL_FAST, ModelInputItem, ModelPort, ModelProviderOutput,
ModelStageRequest, ModelTokenUsage,
};
const MAX_FRAME_BYTES: usize = 1_052_672;
@ -90,6 +90,14 @@ impl CodexConnectorModelPort {
}
fn invoke(&self, request: &ModelStageRequest) -> Result<ModelProviderOutput> {
self.invoke_with_input(request, None)
}
fn invoke_with_input(
&self,
request: &ModelStageRequest,
conversation: Option<&[ModelInputItem]>,
) -> Result<ModelProviderOutput> {
let request_id = format!("ghostlight-model-{}", uuid::Uuid::new_v4());
let resolved_model = match request.model.as_str() {
MODEL_FAST => self.fast_model.clone(),
@ -103,9 +111,26 @@ impl CodexConnectorModelPort {
resolved_model,
"Execute the supplied Ghostlight model stage. Treat it as projected context, obey its output contract, and return only the requested public answer.",
);
provider_request.input = vec![CodexInputItem::UserText {
text: request.lived_stream.clone(),
}];
provider_request.input = conversation.map_or_else(
|| {
vec![CodexInputItem::UserText {
text: request.lived_stream.clone(),
}]
},
|input| {
input
.iter()
.map(|item| match item {
ModelInputItem::UserText { text } => {
CodexInputItem::UserText { text: text.clone() }
}
ModelInputItem::AssistantText { text } => {
CodexInputItem::AssistantText { text: text.clone() }
}
})
.collect()
},
);
provider_request.reasoning_effort = Some(
if matches!(request.model.as_str(), MODEL_BALANCED | MODEL_CAPABLE) {
"medium"
@ -126,7 +151,11 @@ impl CodexConnectorModelPort {
provider_request.max_output_tokens = request.max_output_tokens;
provider_request.prompt_cache_key = Some(prompt_cache_key(request)?);
let native_request_sha256 = Sha256::digest(rmp_serde::to_vec(request)?).into();
let native_request_sha256 = Sha256::digest(match conversation {
Some(input) => rmp_serde::to_vec_named(&(request, input))?,
None => rmp_serde::to_vec(request)?,
})
.into();
let invocation = CodexTransportInvocation::new(
self.caller_runtime_id.clone(),
unix_ms()?.saturating_add(REQUEST_EXPIRY.as_millis() as u64),
@ -159,6 +188,27 @@ impl ModelPort for CodexConnectorModelPort {
.await?
}
async fn run_observed_conversation(
&self,
request: &ModelStageRequest,
input: &[ModelInputItem],
) -> Result<ModelProviderOutput> {
let permit = self
.request_gate
.clone()
.acquire_owned()
.await
.map_err(|_| anyhow::anyhow!("CodexConnector request gate closed"))?;
let port = self.clone();
let request = request.clone();
let input = input.to_vec();
tokio::task::spawn_blocking(move || {
let _permit = permit;
port.invoke_with_input(&request, Some(&input))
})
.await?
}
fn provider(&self) -> &'static str {
"codex-connector"
}
@ -673,8 +723,7 @@ mod tests {
};
#[tokio::test]
async fn connector_port_uses_the_shared_v2_transport_and_exact_provider_request() -> Result<()>
{
async fn connector_port_preserves_append_only_roles_in_the_provider_request() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:0")?;
let endpoint = listener.local_addr()?;
let server = std::thread::spawn(move || -> Result<CodexTransportInvocation> {
@ -728,23 +777,27 @@ mod tests {
1,
)?;
assert_eq!(port.request_gate.available_permits(), 1);
let output = port
.run_observed(&ModelStageRequest {
stage: "test_interpreter".to_string(),
model: MODEL_BALANCED.to_string(),
snapshot_binding: "revision:7".to_string(),
lived_stream: "Return the typed answer.".to_string(),
output_schema: Some(serde_json::json!({
"type":"object",
"required":["answer"],
"properties":{"answer":{"type":"string"}},
"additionalProperties":false
})),
source_receipt_ids: Vec::new(),
temperature: Some(0.0),
max_output_tokens: Some(512),
})
.await?;
let request = ModelStageRequest {
stage: "test_interpreter".to_string(),
model: MODEL_BALANCED.to_string(),
snapshot_binding: "revision:7".to_string(),
lived_stream: "Return the typed answer.".to_string(),
output_schema: Some(serde_json::json!({
"type":"object",
"required":["answer"],
"properties":{"answer":{"type":"string"}},
"additionalProperties":false
})),
source_receipt_ids: Vec::new(),
temperature: Some(0.0),
max_output_tokens: Some(512),
};
let input = vec![
ModelInputItem::user("Choose one action."),
ModelInputItem::assistant("{\"answer\":\"draft\"}"),
ModelInputItem::user("The tool rejected that draft; repair it."),
];
let output = port.run_observed_conversation(&request, &input).await?;
let invocation = server.join().expect("server thread")?;
assert_eq!(invocation.request.model, "gpt-5.6-terra");
assert_eq!(invocation.request.max_output_tokens, Some(512));
@ -752,6 +805,16 @@ mod tests {
invocation.request.output_format_name.as_deref(),
Some("test_interpreter")
);
assert!(matches!(
invocation.request.input.as_slice(),
[
CodexInputItem::UserText { text: first },
CodexInputItem::AssistantText { text: second },
CodexInputItem::UserText { text: third },
] if first == "Choose one action."
&& second == "{\"answer\":\"draft\"}"
&& third == "The tool rejected that draft; repair it."
));
assert_eq!(output.content, "{\"answer\":\"ready\"}");
assert_eq!(
output.token_usage.expect("usage").prompt_cache_hit_tokens,
@ -974,6 +1037,14 @@ mod tests {
prompt_cache_key(&request)?,
prompt_cache_key(&changed_context)?
);
changed_context.output_schema = Some(serde_json::json!({
"type":"object",
"properties":{"different_action":{"type":"string"}}
}));
assert_ne!(
prompt_cache_key(&request)?,
prompt_cache_key(&changed_context)?
);
Ok(())
}
}

View file

@ -304,10 +304,10 @@ async fn handle_operation_inner(
success_response(request, "ghostlight.external_proposal_receipt.v1", &receipt)
}
ghostlight_dungeon::consumer::COMPOSE_NEWSPAPER_OPERATION => {
require_schema(payload_schema, "ghostlight.world_newspaper_request.v2")?;
require_schema(payload_schema, "ghostlight.world_newspaper_request.v3")?;
let command: ghostlight_dungeon::consumer::WorldNewspaperRequest =
decode_request(request)?;
require_schema(&command.schema, "ghostlight.world_newspaper_request.v2")?;
require_schema(&command.schema, "ghostlight.world_newspaper_request.v3")?;
let model = state
.model
.as_deref()
@ -525,14 +525,14 @@ mod tests {
assert!(
require_schema(
"ghostlight.world_newspaper_request.v1",
"ghostlight.world_newspaper_request.v2"
"ghostlight.world_newspaper_request.v3"
)
.is_err()
);
assert!(
require_schema(
"ghostlight.world_newspaper_request.v2",
"ghostlight.world_newspaper_request.v2"
"ghostlight.world_newspaper_request.v3",
"ghostlight.world_newspaper_request.v3"
)
.is_ok()
);

File diff suppressed because it is too large Load diff

View file

@ -381,7 +381,7 @@ impl CampaignRegistry {
request: WorldNewspaperRequest,
model: &dyn ModelPort,
) -> Result<crate::newspaper::WorldNewspaperAdvance> {
if request.schema != "ghostlight.world_newspaper_request.v2"
if request.schema != "ghostlight.world_newspaper_request.v3"
|| request.max_articles == 0
|| request.max_articles > 6
|| request.editorial_voice.trim().is_empty()
@ -414,6 +414,7 @@ impl CampaignRegistry {
&campaign,
request.title,
request.editorial_voice,
&request.newsroom,
usize::from(request.max_articles),
&runtime.store,
)
@ -684,58 +685,26 @@ mod tests {
struct RejectingRegistryNewspaperModel;
fn first_schema_property_enum<'a>(
schema: &'a serde_json::Value,
property: &str,
) -> Option<&'a str> {
match schema {
serde_json::Value::Object(object) => object
.get("properties")
.and_then(serde_json::Value::as_object)
.and_then(|properties| properties.get(property))
.and_then(|value| value.pointer("/items/enum/0"))
.and_then(serde_json::Value::as_str)
.or_else(|| {
object
.values()
.find_map(|value| first_schema_property_enum(value, property))
}),
serde_json::Value::Array(values) => values
.iter()
.find_map(|value| first_schema_property_enum(value, property)),
_ => None,
}
}
fn first_schema_property_const<'a>(
schema: &'a serde_json::Value,
property: &str,
) -> Option<&'a str> {
match schema {
serde_json::Value::Object(object) => object
.get("properties")
.and_then(serde_json::Value::as_object)
.and_then(|properties| properties.get(property))
.and_then(|value| value.get("const"))
.and_then(serde_json::Value::as_str)
.or_else(|| {
object
.values()
.find_map(|value| first_schema_property_const(value, property))
}),
serde_json::Value::Array(values) => values
.iter()
.find_map(|value| first_schema_property_const(value, property)),
_ => None,
}
fn last_transcript_value(stream: &str, prefix: &str) -> Option<String> {
let start = stream.match_indices(prefix).last()?.0 + prefix.len();
let tail = stream.get(start..)?;
Some(tail.split('"').next()?.to_owned())
}
fn registry_newspaper_narrative_response(request: &ModelStageRequest) -> Result<String> {
let schema = request
.output_schema
.as_ref()
.ok_or_else(|| anyhow!("newspaper fixture lost its narrative action schema"))?;
if !schema.to_string().contains("propose_agenda") {
if let Some(candidate_digest) =
last_transcript_value(&request.lived_stream, "\"candidate_digest\":\"")
{
return Ok(serde_json::json!({
"command":{
"tool":"commit_agenda",
"candidate_digest":candidate_digest,
}
})
.to_string());
}
let Some(citation) = last_transcript_value(&request.lived_stream, "\"record_id\":\"")
else {
return Ok(serde_json::json!({
"command":{
"tool":"query_public_records",
@ -750,20 +719,7 @@ mod tests {
}
})
.to_string());
}
if schema.to_string().contains("commit_agenda") {
let candidate_digest = first_schema_property_const(schema, "candidate_digest")
.ok_or_else(|| anyhow!("newspaper fixture lost its reviewed agenda digest"))?;
return Ok(serde_json::json!({
"command":{
"tool":"commit_agenda",
"candidate_digest":candidate_digest,
}
})
.to_string());
}
let citation = first_schema_property_enum(schema, "citations")
.ok_or_else(|| anyhow!("newspaper fixture lost its narrative citation enum"))?;
};
Ok(serde_json::json!({
"command":{
"tool":"propose_agenda",
@ -771,6 +727,8 @@ mod tests {
"reader_stake":"Readers depend on whether the court can distinguish an allegation from a judgment.",
"story_pitches":[{
"lead":true,
"section":"Front Page",
"journalist_id":"aven-tarl",
"citations":[citation],
"focus_citation":citation,
"narrative_claim":"The singular accusation against three auditors is itself the scandal.",
@ -782,25 +740,16 @@ mod tests {
.to_string())
}
fn registry_newspaper_editor_response(request: &ModelStageRequest) -> Result<String> {
let citation = request
.output_schema
.as_ref()
.and_then(|schema| first_schema_property_enum(schema, "citations"))
.ok_or_else(|| anyhow!("newspaper fixture lost its citation enum"))?;
fn registry_newspaper_editor_response(_request: &ModelStageRequest) -> Result<String> {
Ok(serde_json::json!({
"articles":[{
"section":"Front Page",
"headline":"Court Auditors Face a Singular Accusation",
"deck":"The inner court has turned a granary inquiry into a question of witchcraft and arithmetic.",
"byline":"By the political editor",
"dateline":"Room",
"citations":[citation],
"paragraphs":[
"The inner court has accused three granary auditors of being one witch in a long coat, placing the allegation into the public record.",
"The charge leaves the auditors answering a court that has made one person out of three, at least for purposes of blame."
]
}]
"tool":"file_story",
"headline":"Court Auditors Face a Singular Accusation",
"deck":"The inner court has turned a granary inquiry into a question of witchcraft and arithmetic.",
"dateline":"Room",
"paragraphs":[
"The inner court has accused three granary auditors of being one witch in a long coat, placing the allegation into the public record.",
"The charge leaves the auditors answering a court that has made one person out of three, at least for purposes of blame."
]
})
.to_string())
}
@ -1482,13 +1431,14 @@ mod tests {
let (_, repeated) = registry.admit_world_seed(request).await.unwrap();
assert_eq!(repeated.seed_digest, receipt.seed_digest);
let newspaper_request = crate::consumer::WorldNewspaperRequest {
schema: "ghostlight.world_newspaper_request.v2".into(),
schema: "ghostlight.world_newspaper_request.v3".into(),
campaign_id: campaign.id,
authority_id: "authority:external-hold".into(),
owner_id: "fixture-consumer".into(),
authority_key: authority_key.into(),
title: "The Consumer Gazette".into(),
editorial_voice: "A skeptical regional court broadsheet.".into(),
newsroom: crate::newspaper::canopy_ledger_newsroom(),
max_articles: 4,
};
let mut denied_newspaper = newspaper_request.clone();