Localize model authority slices
This commit is contained in:
parent
8e48f7bb7b
commit
13c386f6d1
6 changed files with 308 additions and 16 deletions
|
|
@ -141,7 +141,7 @@ async fn main() -> anyhow::Result<()> {
|
|||
calls: calls.clone(),
|
||||
});
|
||||
let started = Instant::now();
|
||||
let resolved = resolve_activity_outcomes(model.as_ref(), &campaign, &[proposal.clone()]).await;
|
||||
let resolved = resolve_activity_outcomes(model.clone(), &campaign, &[proposal.clone()]).await;
|
||||
let private_calls = calls.lock().expect("outcome trace lock").clone();
|
||||
std::fs::write(
|
||||
result_root.join("private-model-calls.json"),
|
||||
|
|
|
|||
|
|
@ -1065,7 +1065,8 @@ impl WorldCompiler {
|
|||
"PRIVATE RELATIONSHIP ACTOR COMPILATION\nThis is a private branch-local stage. Synthesize exactly one ordinary actor candidate for every approved_private_subject in the supplied order. Copy each name exactly. Choose one exact location id from the supplied topology. The approved relationship descriptions are private, player-approved context: use them only to preserve facts explicitly owned by the counterpart, such as that person's role, affiliation, capabilities, knowledge, goals, obligations, or stated feelings. Do not infer that the counterpart knows the player's secrets or private history, and do not convert player-only interpretation into counterpart knowledge. When ownership is ambiguous, omit the fact and let the private approval preview expose the gap. Candidate relationships may name only exact actor, institution, or population IDs supplied in the public world context and should preserve an explicit affiliation or obligation; never invent a player ID or relationship-anchor ID. Return actor candidates only: no canonical IDs, narration, facts, evidence gaps, branch assumptions, agency profiles, or changes to the public world.\nCONTEXT:\n{}",
|
||||
serde_json::to_string(&private_context)?
|
||||
);
|
||||
let schema = serde_json::to_value(schema_for!(PrivateRelationshipActorSet))?;
|
||||
let mut schema = serde_json::to_value(schema_for!(PrivateRelationshipActorSet))?;
|
||||
constrain_private_relationship_actor_schema(&mut schema, anchors, seed)?;
|
||||
let sources = receipt_ids(evidence_receipts);
|
||||
let mut receipts = Vec::new();
|
||||
let mut correction = String::new();
|
||||
|
|
@ -2435,6 +2436,59 @@ fn materialize_private_relationship_actors(
|
|||
Ok(actors)
|
||||
}
|
||||
|
||||
fn constrain_private_relationship_actor_schema(
|
||||
schema: &mut serde_json::Value,
|
||||
anchors: &[RequiredRelationshipActor],
|
||||
seed: &CompiledSeed,
|
||||
) -> Result<()> {
|
||||
let actors = schema
|
||||
.pointer_mut("/properties/actors")
|
||||
.ok_or_else(|| anyhow!("private relationship actor schema has no actors property"))?;
|
||||
actors["minItems"] = serde_json::json!(anchors.len());
|
||||
actors["maxItems"] = serde_json::json!(anchors.len());
|
||||
|
||||
let candidate = schema
|
||||
.pointer_mut("/$defs/PrivateRelationshipActorCandidate")
|
||||
.ok_or_else(|| anyhow!("private relationship actor schema has no candidate definition"))?;
|
||||
candidate["properties"]["name"] = serde_json::json!({
|
||||
"type":"string",
|
||||
"enum":anchors.iter().map(|anchor| anchor.name.clone()).collect::<Vec<_>>()
|
||||
});
|
||||
candidate["properties"]["location_id"] = serde_json::json!({
|
||||
"type":"string",
|
||||
"enum":seed.locations.iter().map(|location| location.id.clone()).collect::<Vec<_>>()
|
||||
});
|
||||
|
||||
let allowed_relationship_subject_ids = seed
|
||||
.actors
|
||||
.iter()
|
||||
.map(|actor| actor.id.clone())
|
||||
.chain(
|
||||
seed.institutions
|
||||
.iter()
|
||||
.map(|institution| institution.id.clone()),
|
||||
)
|
||||
.chain(seed.gestalts.iter().map(|gestalt| gestalt.id.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
if allowed_relationship_subject_ids.is_empty() {
|
||||
candidate["properties"]["relationships"] = serde_json::json!({
|
||||
"type":"array",
|
||||
"maxItems":0
|
||||
});
|
||||
} else {
|
||||
let relationship = schema
|
||||
.pointer_mut("/$defs/CompiledRelationship")
|
||||
.ok_or_else(|| {
|
||||
anyhow!("private relationship actor schema has no relationship definition")
|
||||
})?;
|
||||
relationship["properties"]["subject_id"] = serde_json::json!({
|
||||
"type":"string",
|
||||
"enum":allowed_relationship_subject_ids
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_required_relationship_actors(
|
||||
campaign: &Campaign,
|
||||
anchors: &[RequiredRelationshipActor],
|
||||
|
|
@ -5194,6 +5248,59 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_actor_schema_projects_exact_current_binding_authority() {
|
||||
let seed = private_actor_test_seed();
|
||||
let anchors = vec![RequiredRelationshipActor {
|
||||
id: "relationship-anchor:quartermaster".into(),
|
||||
name: "convoy quartermaster".into(),
|
||||
approved_relationship_descriptions: vec!["trusted convoy contact".into()],
|
||||
}];
|
||||
let mut schema = serde_json::to_value(schema_for!(PrivateRelationshipActorSet)).unwrap();
|
||||
constrain_private_relationship_actor_schema(&mut schema, &anchors, &seed).unwrap();
|
||||
let validator = jsonschema::validator_for(&schema).unwrap();
|
||||
let candidate = |name: &str, location_id: &str, relationships: serde_json::Value| {
|
||||
serde_json::json!({
|
||||
"actors":[{
|
||||
"name":name,
|
||||
"location_id":location_id,
|
||||
"capabilities":[],
|
||||
"knowledge":[],
|
||||
"equipment":[],
|
||||
"conditions":[],
|
||||
"obligations":[],
|
||||
"relationships":relationships,
|
||||
"goals":[],
|
||||
"memories":[]
|
||||
}]
|
||||
})
|
||||
};
|
||||
|
||||
assert!(validator.is_valid(&candidate(
|
||||
"convoy quartermaster",
|
||||
"convoy-staging",
|
||||
serde_json::json!([])
|
||||
)));
|
||||
assert!(!validator.is_valid(&candidate(
|
||||
"renamed quartermaster",
|
||||
"convoy-staging",
|
||||
serde_json::json!([])
|
||||
)));
|
||||
assert!(!validator.is_valid(&candidate(
|
||||
"convoy quartermaster",
|
||||
"invented-location",
|
||||
serde_json::json!([])
|
||||
)));
|
||||
assert!(!validator.is_valid(&candidate(
|
||||
"convoy quartermaster",
|
||||
"convoy-staging",
|
||||
serde_json::json!([{
|
||||
"subject_id":"invented-office",
|
||||
"description":"invented affiliation"
|
||||
}])
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_actor_materialization_attaches_server_identity() {
|
||||
let anchor = RequiredRelationshipActor {
|
||||
|
|
|
|||
|
|
@ -5902,7 +5902,7 @@ async fn advance_one_strategic_tick(
|
|||
"persona_stage_receipt.v1",
|
||||
stage.receipt.storage_key(),
|
||||
)? {
|
||||
Some((_, existing)) if existing == stage.receipt => {}
|
||||
Some((_, existing)) if existing.same_receipted_content(&stage.receipt) => {}
|
||||
Some(_) => anyhow::bail!("strategic model receipt hash collision"),
|
||||
None => {
|
||||
runtime.store.insert(
|
||||
|
|
|
|||
|
|
@ -87,6 +87,22 @@ impl ModelStageReceipt {
|
|||
&self.receipt_hash
|
||||
}
|
||||
}
|
||||
|
||||
pub fn same_receipted_content(&self, other: &Self) -> bool {
|
||||
self.storage_key() == other.storage_key()
|
||||
&& self.schema == other.schema
|
||||
&& self.provider == other.provider
|
||||
&& self.model == other.model
|
||||
&& self.stage == other.stage
|
||||
&& self.snapshot_binding == other.snapshot_binding
|
||||
&& self.request_hash == other.request_hash
|
||||
&& self.output_hash == other.output_hash
|
||||
&& self.source_receipt_ids == other.source_receipt_ids
|
||||
&& self.validation_result == other.validation_result
|
||||
&& self.local_validation_error == other.local_validation_error
|
||||
&& self.input_chars == other.input_chars
|
||||
&& self.output_chars == other.output_chars
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
|
|
@ -382,6 +398,50 @@ mod tests {
|
|||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn receipt_fixture() -> ModelStageReceipt {
|
||||
ModelStageReceipt {
|
||||
schema: "ghostlight.persona_stage_receipt.v1".into(),
|
||||
receipt_hash: "sha256:receipt".into(),
|
||||
provider: "fixture".into(),
|
||||
model: "fixture-model".into(),
|
||||
stage: "fixture-stage".into(),
|
||||
snapshot_binding: "campaign:one:revision:4".into(),
|
||||
request_hash: "sha256:request".into(),
|
||||
output_hash: "sha256:output".into(),
|
||||
source_receipt_ids: vec!["receipt:source".into()],
|
||||
latency_ms: 17,
|
||||
validation_result: "valid".into(),
|
||||
local_validation_error: None,
|
||||
input_chars: 120,
|
||||
output_chars: 42,
|
||||
provider_attempts: vec![ModelProviderAttemptReceipt {
|
||||
latency_ms: 17,
|
||||
..Default::default()
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_addressed_receipts_ignore_only_observational_attempt_telemetry() {
|
||||
let original = receipt_fixture();
|
||||
let mut repeated = original.clone();
|
||||
repeated.latency_ms = 91;
|
||||
repeated.provider_attempts = vec![ModelProviderAttemptReceipt {
|
||||
provider_request_id: Some("retry-request".into()),
|
||||
latency_ms: 91,
|
||||
..Default::default()
|
||||
}];
|
||||
assert!(original.same_receipted_content(&repeated));
|
||||
|
||||
let mut changed_output = repeated.clone();
|
||||
changed_output.output_hash = "sha256:different".into();
|
||||
assert!(!original.same_receipted_content(&changed_output));
|
||||
|
||||
let mut changed_semantics = repeated;
|
||||
changed_semantics.validation_result = "semantic_invalid".into();
|
||||
assert!(!original.same_receipted_content(&changed_semantics));
|
||||
}
|
||||
|
||||
struct InvalidThenValid {
|
||||
calls: AtomicUsize,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,11 @@ use anyhow::{Result, anyhow};
|
|||
use schemars::{JsonSchema, schema_for};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
sync::Arc,
|
||||
};
|
||||
use tokio::{sync::Semaphore, task::JoinSet};
|
||||
|
||||
const OUTCOME_PROPOSAL_OUTPUT_CONTRACT: &str = r#"The top-level object has exactly one field named outcomes—never action_resolutions, results, or resolutions. outcomes is an array with one item per supplied action_digest. Every item requires action_digest, band (success, mixed, or failure), effect_kind, and supporting_state_references. Fields are conditionally required, not optional suggestions: no_material_change requires reason; resource_created and resource_consumed require owner_subject_id and resource; resource_transferred requires owner_subject_id, other_subject_id, and resource; gestalt_pressure requires owner_subject_id plus both pressure arrays; agency_relation_shift requires relation_id and strength_delta; member_memory requires member_id and memory; member_obligation requires member_id and obligation; member_relationship requires member_id, other_subject_id, and relationship_description; knowledge_learned requires owner_subject_id and fact_id. Every scalar field not named for the chosen effect_kind is omitted or null; irrelevant pressure arrays are omitted or empty. A non-neutral irrelevant field is invalid. pressure_additions and pressure_resolutions are arrays of plain strings, never objects. no_material_change uses an empty supporting_state_references array; every material effect cites the smallest causally decisive set of one to eight values copied literally and only from that action's allowed_state_references. A source_subject_id, target_subject_id, target_state subject_id, member_state_owner_id, owner_subject_id, other_subject_id, member_id, relation_id, or fact_id is not a supporting state reference unless that exact string also appears in allowed_state_references. For member_relationship, other_subject_id already identifies the target; do not repeat it as provenance. Do not emit summary; Ghostlight derives it from the validated typed effect. When resource_created is admissible and concrete capability-backed making or repair establishes a durable source-owned result, the resource field names that resulting object, stock, repair, or usable arrangement. It never restates an action or an unnamed recipient's response. Example no-op shape: {"outcomes":[{"action_digest":"sha256:<copy an exact supplied digest>","band":"mixed","effect_kind":"no_material_change","supporting_state_references":[],"reason":"No durable state changed."}]}"#;
|
||||
const OUTCOME_VERIFIER_OUTPUT_CONTRACT: &str = r#"The top-level object has exactly one field named verdicts—never verifications, outcomes, results, or resolutions. verdicts is an array with one item per supplied action_digest. Every item has exactly action_digest, result, and repair_guidance. Example: {"verdicts":[{"action_digest":"sha256:<copy exact supplied digest>","result":"match","repair_guidance":null}]}"#;
|
||||
|
|
@ -130,13 +134,62 @@ struct OutcomeVerifierVerdict {
|
|||
}
|
||||
|
||||
pub async fn resolve_activity_outcomes(
|
||||
model: &dyn ModelPort,
|
||||
model: Arc<dyn ModelPort>,
|
||||
campaign: &Campaign,
|
||||
proposals: &[CellActionProposal],
|
||||
) -> Result<(Vec<StrategicActivityOutcome>, Vec<ModelStageOutput>)> {
|
||||
if proposals.is_empty() {
|
||||
return Ok((Vec::new(), Vec::new()));
|
||||
}
|
||||
let parallelism = usize::from(campaign.resolution_policy.provider_parallelism.max(1));
|
||||
let permits = Arc::new(Semaphore::new(parallelism));
|
||||
let campaign = Arc::new(campaign.clone());
|
||||
let mut tasks = JoinSet::new();
|
||||
for (index, proposal) in proposals.iter().cloned().enumerate() {
|
||||
let model = model.clone();
|
||||
let campaign = campaign.clone();
|
||||
let permits = permits.clone();
|
||||
tasks.spawn(async move {
|
||||
let _permit = permits
|
||||
.acquire_owned()
|
||||
.await
|
||||
.map_err(|_| anyhow!("strategic outcome concurrency gate closed"))?;
|
||||
let resolved = resolve_activity_outcome(model.as_ref(), &campaign, &proposal).await?;
|
||||
Ok::<_, anyhow::Error>((index, resolved))
|
||||
});
|
||||
}
|
||||
let mut ordered = BTreeMap::new();
|
||||
while let Some(task) = tasks.join_next().await {
|
||||
let (index, resolved) =
|
||||
task.map_err(|error| anyhow!("strategic outcome worker failed: {error}"))??;
|
||||
if ordered.insert(index, resolved).is_some() {
|
||||
return Err(anyhow!(
|
||||
"strategic outcome worker returned a duplicate slot"
|
||||
));
|
||||
}
|
||||
}
|
||||
if ordered.len() != proposals.len() {
|
||||
return Err(anyhow!(
|
||||
"strategic outcome workers returned {} slots for {} selected actions",
|
||||
ordered.len(),
|
||||
proposals.len()
|
||||
));
|
||||
}
|
||||
let mut outcomes = Vec::with_capacity(proposals.len());
|
||||
let mut stages = Vec::new();
|
||||
for (_, (mut action_outcomes, mut action_stages)) in ordered {
|
||||
outcomes.append(&mut action_outcomes);
|
||||
stages.append(&mut action_stages);
|
||||
}
|
||||
Ok((outcomes, stages))
|
||||
}
|
||||
|
||||
async fn resolve_activity_outcome(
|
||||
model: &dyn ModelPort,
|
||||
campaign: &Campaign,
|
||||
proposal: &CellActionProposal,
|
||||
) -> Result<(Vec<StrategicActivityOutcome>, Vec<ModelStageOutput>)> {
|
||||
let proposals = std::slice::from_ref(proposal);
|
||||
let context = build_context(campaign, proposals)?;
|
||||
let digests = proposals
|
||||
.iter()
|
||||
|
|
@ -2074,6 +2127,48 @@ mod tests {
|
|||
requests: Mutex<Vec<ModelStageRequest>>,
|
||||
}
|
||||
|
||||
struct IsolatingOutcomeModel {
|
||||
requests: Mutex<Vec<ModelStageRequest>>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ModelPort for IsolatingOutcomeModel {
|
||||
async fn run(&self, request: &ModelStageRequest) -> Result<String> {
|
||||
assert_eq!(request.stage, "strategic_outcome_resolver");
|
||||
self.requests.lock().unwrap().push(request.clone());
|
||||
let (_, payload) = request
|
||||
.lived_stream
|
||||
.rsplit_once("OUTCOME_CONTEXT:\n")
|
||||
.ok_or_else(|| anyhow!("fixture request omitted outcome context"))?;
|
||||
let context: serde_json::Value = serde_json::from_str(payload)?;
|
||||
let actions = context["actions"]
|
||||
.as_array()
|
||||
.ok_or_else(|| anyhow!("fixture context omitted actions"))?;
|
||||
if actions.len() != 1 {
|
||||
return Err(anyhow!(
|
||||
"unrelated strategic actions shared one resolver context"
|
||||
));
|
||||
}
|
||||
let digest = actions[0]["action_digest"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow!("fixture action omitted digest"))?;
|
||||
Ok(serde_json::json!({
|
||||
"outcomes":[{
|
||||
"action_digest":digest,
|
||||
"band":"mixed",
|
||||
"effect_kind":"no_material_change",
|
||||
"supporting_state_references":[],
|
||||
"reason":"This exact attempt establishes no durable change."
|
||||
}]
|
||||
})
|
||||
.to_string())
|
||||
}
|
||||
|
||||
fn provider(&self) -> &'static str {
|
||||
"isolating-outcome-model"
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ModelPort for RepeatingPressureModel {
|
||||
async fn run(&self, request: &ModelStageRequest) -> Result<String> {
|
||||
|
|
@ -2651,12 +2746,12 @@ mod tests {
|
|||
location_ids: vec!["dock".into()],
|
||||
}];
|
||||
let digest = cell_action_digest(&action).unwrap();
|
||||
let model = RepeatingPressureModel {
|
||||
let model = Arc::new(RepeatingPressureModel {
|
||||
action_digest: digest,
|
||||
requests: Mutex::new(Vec::new()),
|
||||
};
|
||||
});
|
||||
|
||||
let (outcomes, stages) = resolve_activity_outcomes(&model, &value, &[action])
|
||||
let (outcomes, stages) = resolve_activity_outcomes(model.clone(), &value, &[action])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
|
|
@ -2787,16 +2882,16 @@ mod tests {
|
|||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resolver_batches_selected_attempts_under_one_digest_bound_stage() {
|
||||
async fn resolver_keeps_each_selected_attempt_in_one_digest_bound_stage() {
|
||||
let value = campaign();
|
||||
let action = proposal();
|
||||
let digest = cell_action_digest(&action).unwrap();
|
||||
let model = OutcomeFixtureModel {
|
||||
let model = Arc::new(OutcomeFixtureModel {
|
||||
action_digest: digest.clone(),
|
||||
requests: Mutex::new(Vec::new()),
|
||||
};
|
||||
});
|
||||
|
||||
let (outcomes, stages) = resolve_activity_outcomes(&model, &value, &[action])
|
||||
let (outcomes, stages) = resolve_activity_outcomes(model.clone(), &value, &[action])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
|
|
@ -2852,6 +2947,36 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resolver_never_shares_authority_context_between_selected_attempts() {
|
||||
let value = campaign();
|
||||
let first = proposal();
|
||||
let mut second = proposal();
|
||||
second.intent = "inspect the eastern causeway supports".into();
|
||||
second.intended_effect = "establish whether the eastern supports remain sound".into();
|
||||
let expected = vec![
|
||||
cell_action_digest(&first).unwrap(),
|
||||
cell_action_digest(&second).unwrap(),
|
||||
];
|
||||
let model = Arc::new(IsolatingOutcomeModel {
|
||||
requests: Mutex::new(Vec::new()),
|
||||
});
|
||||
|
||||
let (outcomes, stages) = resolve_activity_outcomes(model.clone(), &value, &[first, second])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
outcomes
|
||||
.iter()
|
||||
.map(|outcome| outcome.action_digest.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
expected
|
||||
);
|
||||
assert_eq!(stages.len(), 2);
|
||||
assert_eq!(model.requests.lock().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_context_projects_only_locally_admissible_durable_handles() {
|
||||
let value = campaign();
|
||||
|
|
@ -3028,12 +3153,12 @@ mod tests {
|
|||
let value = campaign();
|
||||
let action = proposal();
|
||||
let digest = cell_action_digest(&action).unwrap();
|
||||
let model = CorrectingOutcomeModel {
|
||||
let model = Arc::new(CorrectingOutcomeModel {
|
||||
action_digest: digest,
|
||||
resolver_calls: Mutex::new(0),
|
||||
};
|
||||
});
|
||||
|
||||
let (outcomes, stages) = resolve_activity_outcomes(&model, &value, &[action])
|
||||
let (outcomes, stages) = resolve_activity_outcomes(model.clone(), &value, &[action])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
|
|
|
|||
|
|
@ -199,7 +199,7 @@ pub async fn propose_resolution_wave_with_policy(
|
|||
.await?;
|
||||
}
|
||||
let (activity_outcomes, outcome_stages) = resolve_activity_outcomes(
|
||||
outcome_model.as_ref(),
|
||||
outcome_model.clone(),
|
||||
campaign,
|
||||
&selection.activity_proposals,
|
||||
)
|
||||
|
|
|
|||
Loading…
Reference in a new issue