Cut the phase clause and the fixed genesis, then land the Draft seed lane

The deletion line first. `world.advance_time` was emitted by the panel and
handled by `execute_world` but absent from `operation_schema`, so every
invocation died at validation; it is named now. `qualifies` loses its
`phase == Active` clause: `require_answer` already owns the Draft-answer
refusal, so the clause protected nothing and only pinned a Draft world's
deficit at the authored intent forever. `WorldScaleIntentRef::default()` and
the comment claiming world ingress authors no scale target are gone, along
with `world_create.v1` and `controller_work.v9`; `build_prompt`'s inlined
evidence/mismatch/tools tail collapses into one `prompt_body` owner.

Then the lane. `world_create.v2` carries a scale target and its jurisdiction
roots, which genesis declares beside the commons so `resolve_patch` can
resolve them. `SeedPort` reads a snapshot and commits one unanswered Draft
patch as `CallerId::Principal(owner)` — it has no approve, no activate, no
clock, no operator log, because those are not methods on the type. `SeedRunner`
is `ElaborationRunner`'s eleven stages with four substitutions: the phase gate,
the row selection, the identity namespace, and the submit port. It shares the
round loop, the tool application, the evidence filter, the cap check, and the
repair prompt verbatim. `world/vault.rs` is a read-only markdown reader over a
configured root: no network, no git, no vault name in core, and a spoiler tier
is a directory and therefore a query scope.

Termination is derived: the Draft deficit falls as seed patches land, so the
runner keeps no counter and a commit that does not lower its row is a fixed
point rather than a retry. `ApproveDraft` and `ActivateWorld` remain the only
path to Active.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-05 17:00:41 +02:00
commit 681f7063b1
7 changed files with 1778 additions and 60 deletions

View file

@ -2,7 +2,7 @@
use crate::{
mesh::{COMMAND_BOUNDARY, COMMAND_RESULT_SCHEMA, PROVIDER_ID, SURFACE_ID},
world::{ControllerMode, OperatorEvent, WorldPhase, WorldSnapshot},
world::{ControllerMode, JurisdictionKey, OperatorEvent, WorldPhase, WorldSnapshot},
};
use anyhow::{Context, bail};
use chrono::{DateTime, Utc};
@ -46,6 +46,19 @@ pub(crate) struct EveRouteHint {
pub(crate) transport: Option<String>,
}
/// The `world_create.v2` payload, in one place, so the button that captures it
/// and the descriptor that advertises it cannot drift.
const CREATE_BINDINGS: [&str; 6] = [
"title",
"subject_label",
"narrative_persona_label",
"operational_agent_label",
"targets",
"jurisdictions",
];
const SEED_BINDINGS: [&str; 2] = ["vault_scope", "brief"];
pub(crate) fn surface_version(snapshot: Option<&WorldSnapshot>) -> u64 {
snapshot
.map(|world| world.revision.saturating_add(1))
@ -154,6 +167,74 @@ fn cover_card(panel: &CoverPanel) -> Value {
})
}
/// What the seed lane has done and what it will answer next. Everything here is
/// derived from `scale_deficit` and `revision`: in Draft every commit is a patch
/// admission, so `revision - 1` is exactly the seed patches committed since
/// genesis, and "next shortfall" calls the runner's own `select_row` so the card
/// and the runner cannot disagree about what happens next.
///
/// It shows no in-flight session and no last outcome. Both would need a second
/// reader of the controller-work store from here and a status cache in
/// `AppState`; the last outcome is already in the invocation's own
/// `command_result` receipt, which is where a command's result belongs.
fn seed_card(world: &WorldSnapshot) -> Value {
let next = crate::world::select_row(world).map_or_else(
|| "Nothing short.".to_owned(),
|row| {
format!(
"{} · {:?} · short {}",
jurisdiction_label(world, row.jurisdiction),
row.kind,
row.deficit
)
},
);
let rows = world
.scale_deficit
.iter()
.enumerate()
.map(|(index, row)| {
json!({
"id":format!("world.seed.row.{index}"),
"kind":"text",
"props":{"value":format!(
"{} · {:?} · target {} · alive {} · short {}",
jurisdiction_label(world, row.jurisdiction),
row.kind,
row.target,
row.qualified,
row.deficit
)},
"children":[]
})
})
.collect::<Vec<_>>();
json!({
"id":"world.seed.card",
"kind":"card",
"props":{
"title":"Seed",
"detail":format!("Draft patches committed: {}", world.revision.saturating_sub(1)),
"nextShortfall":next
},
"children":rows
})
}
fn jurisdiction_label(world: &WorldSnapshot, jurisdiction: JurisdictionKey) -> String {
match jurisdiction {
JurisdictionKey::PlaceSubtree(root) => world
.places
.iter()
.find(|entry| entry.id == root)
.map_or_else(
|| "an unnamed place subtree".to_owned(),
|entry| entry.label.clone(),
),
JurisdictionKey::Uncovered => "everything no declared root covers".to_owned(),
}
}
pub(crate) fn authenticated_surface(
account: &str,
snapshot: Option<&WorldSnapshot>,
@ -205,28 +286,32 @@ pub(crate) fn authenticated_surface(
"stateBindings":[local_draft("operational_agent_label", "string")],
"children":[]
}),
json!({
"id":"world.create.targets",
"kind":"control.input.textarea",
"props":{"label":"Scale target","rows":2,"placeholder":"{\"person\": 12, \"institution\": 3}"},
"stateBindings":[local_draft("targets", "json")],
"children":[]
}),
json!({
"id":"world.create.jurisdictions",
"kind":"control.input.textarea",
"props":{"label":"Jurisdiction roots","rows":3,"placeholder":"[{\"handle\":\"low_sere\",\"label\":\"The Low Sere\",\"permille\":700}]"},
"stateBindings":[local_draft("jurisdictions", "json")],
"children":[]
}),
command_button(
"world.create",
"Create world",
"world.create",
json!({}),
&[
"title",
"subject_label",
"narrative_persona_label",
"operational_agent_label",
],
&CREATE_BINDINGS,
),
]);
commands.push(command_descriptor(
"world.create",
"ghostlight.world_create.v1",
&[
"title",
"subject_label",
"narrative_persona_label",
"operational_agent_label",
],
"ghostlight.world_create.v2",
&CREATE_BINDINGS,
"WorldMailbox",
));
}
@ -265,6 +350,38 @@ pub(crate) fn authenticated_surface(
"WorldMailbox",
));
}
if world.owner == crate::world::PrincipalId::new(account) {
children.extend([
json!({
"id":"world.seed.vault_scope",
"kind":"control.input.text",
"props":{"label":"Vault scope (optional)","placeholder":"A subdirectory of the configured vault"},
"stateBindings":[local_draft("vault_scope", "string")],
"children":[]
}),
json!({
"id":"world.seed.brief",
"kind":"control.input.textarea",
"props":{"label":"Brief (optional)","rows":2,"placeholder":"One sentence of what this world is for"},
"stateBindings":[local_draft("brief", "string")],
"children":[]
}),
command_button(
"world.seed",
"Seed the world",
"world.seed",
json!({}),
&SEED_BINDINGS,
),
seed_card(world),
]);
commands.push(command_descriptor(
"world.seed",
"ghostlight.world_seed.v1",
&SEED_BINDINGS,
"SeedPort",
));
}
if world.owner == crate::world::PrincipalId::new(account)
&& world.draft_approvals == world.required_approvers
{
@ -495,9 +612,11 @@ pub(crate) fn operation_schema(operation: &str) -> Option<&'static str> {
"heimdall.auth.begin" => "heimdall.auth_begin_command.v1",
"heimdall.auth.complete" => "heimdall.auth_complete_command.v1",
"app.auth.logout" => "ghostlight.app_logout.v2",
"world.create" => "ghostlight.world_create.v1",
"world.create" => "ghostlight.world_create.v2",
"world.approve" => "ghostlight.world_approve.v0",
"world.activate" => "ghostlight.world_activate.v0",
"world.advance_time" => "ghostlight.world_advance_time.v0",
"world.seed" => "ghostlight.world_seed.v1",
"world.speak" => "ghostlight.world_speak.v0",
"world.controller.act" => "ghostlight.world_controller_act.v0",
_ => return None,

View file

@ -12,10 +12,11 @@ use crate::{
world::{
AffordanceId, CONSUMER_BODY_LIMIT, CellRun, CommandBody, CommandId, ConsumerPort,
ConsumerRegistry, ControllerError, ControllerModels, ControllerPendingReason,
ControllerRunner, ControllerWorkCustody, Cover, CoverBudget, CreateWorldIntent,
DecisionInvocation, DecisionOpportunity, KernelError, MailboxError, NarrativeRun,
OperationalRun, PrincipalCommandIntent, PrincipalId, Statement, SubmissionDisposition,
SubmitReceipt, TickMinutes, WorldMailbox, WorldSnapshot, derive_cover,
ControllerRunner, ControllerWorkCustody, Cover, CoverBudget, CreateJurisdictionIntent,
CreateWorldIntent, DecisionInvocation, DecisionOpportunity, KernelError, MailboxError,
NarrativeRun, OperationalRun, PrincipalCommandIntent, PrincipalId, SeedOutcome, SeedPort,
Statement, SubjectKind, SubmissionDisposition, SubmitReceipt, TickMinutes,
VaultEvidenceSource, WorldMailbox, WorldPhase, WorldSnapshot, derive_cover,
},
};
use anyhow::{Context, bail, ensure};
@ -38,6 +39,7 @@ use cultnet_rs::{
use serde::Deserialize;
use serde_json::{Value, json};
use std::{
collections::BTreeMap,
convert::Infallible,
fs,
net::SocketAddr,
@ -145,6 +147,51 @@ struct CreatePayload {
narrative_persona_label: Option<String>,
#[serde(default)]
operational_agent_label: Option<String>,
/// World-wide target of goal-bearing subjects per kind. Required, and may
/// be empty: a world with no target is a deliberate choice, not a default
/// that arrives because nobody said anything. A payload that omits it is
/// refused, which is what `world_create.v2` means.
targets: BTreeMap<SubjectKind, u32>,
/// The jurisdiction roots, declared by genesis beside the commons because
/// `resolve_patch` only resolves roots the same patch declares. A duplicate
/// handle and a permille sum over 1000 are refused by the resolver, not
/// pre-checked here: a pre-check would be a second reducer.
jurisdictions: Vec<CreateJurisdiction>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct CreateJurisdiction {
/// The draft handle genesis declares the root under, and the intent's key.
handle: String,
label: String,
permille: u32,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct SeedPayload {
/// A subdirectory of the configured vault root, or empty for the whole
/// vault. Relative and `..`-free, refused at `VaultEvidenceSource::open`.
/// The root itself is configuration: a payload carrying an absolute path
/// would turn an authenticated Eve button into a read primitive over the
/// server's filesystem.
#[serde(default)]
vault_scope: String,
/// One sentence of the owner's own intent, carried into the brief verbatim
/// and into the Vault query as a referent.
#[serde(default)]
brief: Option<String>,
}
/// The shape a jurisdiction handle may take. Checked at ingress because the
/// handle becomes a draft-index key the model reads back in mismatches, and a
/// handle carrying whitespace or case would make that text unusable.
fn is_handle_shape(value: &str) -> bool {
let mut chars = value.chars();
value.len() <= 48
&& chars.next().is_some_and(|first| first.is_ascii_lowercase())
&& chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
}
#[derive(Debug, Deserialize)]
@ -1324,6 +1371,16 @@ async fn execute_world(
if invocation.operation.operation_id == "world.create" {
let payload: CreatePayload = serde_json::from_value(invocation.payload.clone())
.map_err(|error| RuntimeCommandError::Payload(error.to_string()))?;
if let Some(root) = payload
.jurisdictions
.iter()
.find(|root| !is_handle_shape(&root.handle))
{
return Err(RuntimeCommandError::Payload(format!(
"jurisdiction handle {} is not a draft handle",
root.handle
)));
}
let receipt = state
.world
.create(
@ -1333,6 +1390,16 @@ async fn execute_world(
human_subject_label: payload.subject_label,
narrative_persona_label: payload.narrative_persona_label,
operational_agent_label: payload.operational_agent_label,
targets: payload.targets,
jurisdictions: payload
.jurisdictions
.into_iter()
.map(|root| CreateJurisdictionIntent {
handle: root.handle,
label: root.label,
permille: root.permille,
})
.collect(),
},
verified_principal,
)
@ -1397,6 +1464,25 @@ async fn execute_world(
})?,
}
}
// The one arm that builds no `CommandBody`: the seed runner submits
// through its own port, as the owner, and the receipt reports what one
// session did rather than what one command committed.
"world.seed" => {
let payload: SeedPayload = serde_json::from_value(invocation.payload.clone())
.map_err(|error| RuntimeCommandError::Payload(error.to_string()))?;
let outcome = seed_once(state, verified_principal, &snapshot, payload).await?;
let after = current_world(state)
.await
.map_err(|error| RuntimeCommandError::Payload(error.to_string()))?;
return Ok(json!({
"kind":"seeded",
"outcome":outcome.name(),
"revision":after.as_ref().map(|world| world.revision),
"deficit":after
.as_ref()
.map(|world| world.scale_deficit.iter().map(|row| u64::from(row.deficit)).sum::<u64>()),
}));
}
operation => {
return Err(RuntimeCommandError::Payload(format!(
"unknown world operation {operation}"
@ -1597,6 +1683,62 @@ where
}
}
/// Where the seed lane's read-only markdown vault lives. Configuration, read at
/// open exactly as every other runtime path is: the payload names a relative
/// scope inside it and never the root.
const SEED_VAULT_ROOT_ENVIRONMENT: &str = "GHOSTLIGHT_SEED_VAULT_ROOT";
/// One seeding session, inside the request that asked for it. There is no
/// background task and no stop channel: a spawned sweep would need the owner's
/// verified evidence to outlive the request that carried it, and then two new
/// authorities in `AppState` to be stoppable. The checkpoint discipline already
/// makes a long request safe — a transport timeout loses the response, not the
/// work — so the owner's repetition is the sweep and not pressing the button
/// again is the stop.
///
/// Every refusal here happens before anything is spent. The reducer refuses a
/// non-owner too, at `require_patch_author`, and the runner refuses an Active
/// world again at its own phase gate; this is the gate that keeps a paid
/// session from running first.
async fn seed_once(
state: &AppState,
verified_principal: &VerifiedPrincipalEvidence,
snapshot: &WorldSnapshot,
payload: SeedPayload,
) -> Result<SeedOutcome, RuntimeCommandError> {
if snapshot.owner != PrincipalId::new(verified_principal.account_subject_hash()) {
return Err(RuntimeCommandError::Payload(
"seeding a world is its owner's lane".into(),
));
}
if snapshot.phase != WorldPhase::Draft {
return Ok(SeedOutcome::NotDraft);
}
let Some(controllers) = state
.controllers
.as_deref()
.filter(|_| !state.controller_quarantined.load(Ordering::SeqCst))
else {
return Err(RuntimeCommandError::Payload(
"the cognition organ is closed or quarantined".into(),
));
};
let root = std::env::var(SEED_VAULT_ROOT_ENVIRONMENT).map_err(|_| {
RuntimeCommandError::Payload(format!("{SEED_VAULT_ROOT_ENVIRONMENT} is not configured"))
})?;
let vault = VaultEvidenceSource::open(std::path::Path::new(&root), &payload.vault_scope)
.map_err(|error| RuntimeCommandError::Payload(error.to_string()))?;
let runner = controllers.seeder(
SeedPort::new(state.world.clone(), verified_principal.clone()),
Arc::new(vault),
payload.brief,
);
runner
.sweep(1)
.await
.map_err(|error| RuntimeCommandError::Payload(error.to_string()))
}
/// How often the authoring lane takes one sweep. Slow, and skipping: a sweep
/// that admits nothing is a fixed point, not a reason to spin against a paid
/// inference endpoint.
@ -2606,9 +2748,14 @@ mod tests {
&fixture.cookie,
invocation(
"world.create",
"ghostlight.world_create.v1",
"ghostlight.world_create.v2",
0,
json!({"title":"Cutover World","subject_label":"Operator"}),
json!({
"title":"Cutover World",
"subject_label":"Operator",
"targets":{},
"jurisdictions":[]
}),
&uuid::Uuid::new_v4().to_string(),
),
)
@ -2681,9 +2828,14 @@ mod tests {
let id = uuid::Uuid::new_v4().to_string();
let command = invocation(
"world.create",
"ghostlight.world_create.v1",
"ghostlight.world_create.v2",
0,
json!({"title":"Retry World","subject_label":"Operator"}),
json!({
"title":"Retry World",
"subject_label":"Operator",
"targets":{},
"jurisdictions":[]
}),
&id,
);
let first = post(&fixture.state, &fixture.cookie, command.clone()).await;
@ -2804,6 +2956,19 @@ mod tests {
/// surface into the kernel's private command types the rest of this
/// module deliberately does not name.
async fn active_two_cell_world(state: &AppState, cookie: &str) {
two_cell_world(state, cookie, BTreeMap::new(), Vec::new(), true).await;
}
/// The same genesis, with an authored scale intent and without the
/// approve/activate pair, so a test can look at the Draft world the seed
/// lane actually runs against.
async fn two_cell_world(
state: &AppState,
cookie: &str,
targets: BTreeMap<SubjectKind, u32>,
jurisdictions: Vec<CreateJurisdictionIntent>,
activate: bool,
) {
let principal = state
.sessions
.lock()
@ -2820,12 +2985,17 @@ mod tests {
human_subject_label: "Operator".into(),
narrative_persona_label: Some("Persona".into()),
operational_agent_label: Some("Operational Agent".into()),
targets,
jurisdictions,
},
&principal,
)
.await
.unwrap();
let mut snapshot = state.world.snapshot().await.unwrap();
if !activate {
return;
}
for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] {
state
.world
@ -2881,6 +3051,7 @@ mod tests {
narrative_commands: 0,
operational_commands: 0,
elaboration_commands: 0,
seed_commands: 0,
})
}
}

View file

@ -7,7 +7,8 @@
//! affordance fields.
use super::elaboration::{
ElaborationCheckpoint, ElaborationRunner, NullEvidenceSource, valid_elaboration_progression,
ElaborationCheckpoint, ElaborationRunner, EvidenceSource, NullEvidenceSource, SeedCheckpoint,
SeedRunner, valid_elaboration_progression, valid_seed_progression,
};
use super::tool_schema;
use crate::world::{
@ -16,8 +17,8 @@ use crate::world::{
DecisionInvocation, DecisionOpportunity, DependencyTarget, EdgeId, ElaborationPort, EntityId,
EntityKind, FactStandingView, KernelError, KnowledgeSnapshot, KnowledgeSource, Magnitude,
MailboxError, OfficeSnapshot, ProposedEffect, Quantity, RefKind, Resolution, RoleBinding,
Statement, SubjectId, SubjectSnapshot, SubmitReceipt, Target, TickIndex, WorldMailbox,
WorldSnapshot,
SeedPort, Statement, SubjectId, SubjectSnapshot, SubmitReceipt, Target, TickIndex,
WorldMailbox, WorldSnapshot,
};
use async_trait::async_trait;
use chrono::Utc;
@ -60,8 +61,8 @@ const CELL_TOOL_STEP_BUDGET: usize = 2;
/// carried by tool identity, never by a model-written argument.
const HANDLE_SEPARATOR: &str = "__";
const PERSONA_WORD_BUDGET: usize = 180;
const CONTROLLER_WORK_ROW: &str = "controller_work.v9";
const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v9";
const CONTROLLER_WORK_ROW: &str = "controller_work.v10";
const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v10";
/// The Interpreter's byte-span capture tool. It is not the generated `speak`
/// affordance tool: one captures an utterance out of preserved prose, the other
@ -480,6 +481,12 @@ pub(crate) enum ControllerWork {
/// The authoring lane. One store, one custody probe, one progression check:
/// forking them would buy nothing and split one authority in three.
Elaboration(ElaborationCheckpoint),
/// Draft's authoring lane. A separate variant rather than a reused
/// `Elaboration` row, because an elaboration session carries a `PatchAnswer`
/// and a seed answers nothing: sharing the row would mean either widening a
/// kernel enum read by `require_answer` and `ground_covers`, or a session
/// whose answer field is never submitted.
Seed(SeedCheckpoint),
}
/// Which lane a stored checkpoint belongs to. Distinct from `ControllerMode`,
@ -491,6 +498,7 @@ pub(crate) enum WorkLane {
Operational,
Grouped,
Elaboration,
Seed,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -575,6 +583,7 @@ impl ControllerWork {
Self::Operational(checkpoint) => checkpoint.command_id(),
Self::Grouped(checkpoint) => checkpoint.command_id(),
Self::Elaboration(checkpoint) => checkpoint.command_id(),
Self::Seed(checkpoint) => checkpoint.command_id(),
}
}
@ -584,6 +593,7 @@ impl ControllerWork {
Self::Operational(_) => WorkLane::Operational,
Self::Grouped(_) => WorkLane::Grouped,
Self::Elaboration(_) => WorkLane::Elaboration,
Self::Seed(_) => WorkLane::Seed,
}
}
@ -593,7 +603,9 @@ impl ControllerWork {
#[cfg_attr(not(test), expect(dead_code, reason = "read by the resolution test"))]
fn resolution(&self) -> Resolution {
match self {
Self::Narrative(_) | Self::Operational(_) | Self::Elaboration(_) => Resolution::Detail,
Self::Narrative(_) | Self::Operational(_) | Self::Elaboration(_) | Self::Seed(_) => {
Resolution::Detail
}
Self::Grouped(checkpoint) => Resolution::Coarse {
constituents: checkpoint.constituents().len(),
},
@ -612,6 +624,7 @@ impl ControllerWork {
last_mismatches,
..
}) => completed.is_empty() && last_mismatches.is_empty(),
Self::Seed(checkpoint) => checkpoint.is_initial(),
_ => false,
}
}
@ -622,6 +635,7 @@ impl ControllerWork {
Self::Operational(checkpoint) => checkpoint.integrity_is_valid(),
Self::Grouped(checkpoint) => checkpoint.integrity_is_valid(),
Self::Elaboration(checkpoint) => checkpoint.integrity_is_valid(),
Self::Seed(checkpoint) => checkpoint.integrity_is_valid(),
}
}
}
@ -1236,6 +1250,10 @@ pub(crate) enum ControllerWorkCustody {
narrative_commands: usize,
operational_commands: usize,
elaboration_commands: usize,
seed_commands: usize,
// `Grouped` still has no count here. That asymmetry is the grouped
// lane's debt, named rather than fixed: widening it in this pass would
// be work with no consumer.
},
/// A compare-and-swap or post-write ownership check did not confirm. The
/// process must reopen the journal before doing any other controller work.
@ -1444,6 +1462,7 @@ impl ControllerWorkStore for CultCacheControllerWorkStore {
narrative_commands: count(WorkLane::Narrative),
operational_commands: count(WorkLane::Operational),
elaboration_commands: count(WorkLane::Elaboration),
seed_commands: count(WorkLane::Seed),
})
}
}
@ -1482,6 +1501,9 @@ fn valid_controller_work_progression(existing: &ControllerWork, next: &Controlle
(ControllerWork::Elaboration(existing), ControllerWork::Elaboration(next)) => {
valid_elaboration_progression(existing, next)
}
(ControllerWork::Seed(existing), ControllerWork::Seed(next)) => {
valid_seed_progression(existing, next)
}
_ => false,
}
}
@ -2146,6 +2168,28 @@ impl ControllerRunner {
)
}
/// Draft's authoring lane, built from the same inference transport and the
/// same work store. The port is not one this runner holds: it carries the
/// owner's verified evidence and therefore belongs to the request that
/// asked for the work, and the evidence source is supplied by that request
/// too. `NullEvidenceSource` stays the elaborator's; there is no mode flag
/// choosing between them.
pub(crate) fn seeder(
&self,
port: SeedPort,
evidence: Arc<dyn EvidenceSource>,
brief: Option<String>,
) -> SeedRunner {
SeedRunner::new(
port,
Arc::clone(&self.inference),
evidence,
Arc::clone(&self.work),
self.models.elaborator.clone(),
brief,
)
}
#[cfg(test)]
pub(crate) fn with_test_ports(
mailbox: WorldMailbox,
@ -2200,12 +2244,14 @@ impl ControllerRunner {
ControllerWorkLookup::Confirmed(
ControllerWork::Operational(_)
| ControllerWork::Grouped(_)
| ControllerWork::Elaboration(_),
| ControllerWork::Elaboration(_)
| ControllerWork::Seed(_),
)
| ControllerWorkLookup::CustodyUncertain(
ControllerWork::Operational(_)
| ControllerWork::Grouped(_)
| ControllerWork::Elaboration(_),
| ControllerWork::Elaboration(_)
| ControllerWork::Seed(_),
) => {
return Err(ControllerError::CommandMismatch);
}
@ -2285,12 +2331,14 @@ impl ControllerRunner {
ControllerWorkLookup::Confirmed(
ControllerWork::Narrative(_)
| ControllerWork::Grouped(_)
| ControllerWork::Elaboration(_),
| ControllerWork::Elaboration(_)
| ControllerWork::Seed(_),
)
| ControllerWorkLookup::CustodyUncertain(
ControllerWork::Narrative(_)
| ControllerWork::Grouped(_)
| ControllerWork::Elaboration(_),
| ControllerWork::Elaboration(_)
| ControllerWork::Seed(_),
) => {
return Err(ControllerError::CommandMismatch);
}
@ -2530,12 +2578,14 @@ impl ControllerRunner {
ControllerWorkLookup::Confirmed(
ControllerWork::Narrative(_)
| ControllerWork::Operational(_)
| ControllerWork::Elaboration(_),
| ControllerWork::Elaboration(_)
| ControllerWork::Seed(_),
)
| ControllerWorkLookup::CustodyUncertain(
ControllerWork::Narrative(_)
| ControllerWork::Operational(_)
| ControllerWork::Elaboration(_),
| ControllerWork::Elaboration(_)
| ControllerWork::Seed(_),
) => {
return Err(ControllerError::CommandMismatch);
}
@ -5142,6 +5192,7 @@ mod tests {
controls: BTreeSet::new(),
commitments: Vec::new(),
pressures: Vec::new(),
qualified: false,
};
let speaker = SubjectSnapshot {
id: speaker_id,
@ -5170,6 +5221,7 @@ mod tests {
controls: BTreeSet::new(),
commitments: Vec::new(),
pressures: Vec::new(),
qualified: false,
};
let snapshot = WorldSnapshot {
world_id: opportunity.world_id,
@ -5382,6 +5434,7 @@ mod tests {
controls: BTreeSet::new(),
commitments: Vec::new(),
pressures: Vec::new(),
qualified: false,
};
let other = SubjectSnapshot {
id: other_id,
@ -5403,6 +5456,7 @@ mod tests {
controls: BTreeSet::new(),
commitments: Vec::new(),
pressures: Vec::new(),
qualified: false,
};
let named_place = |id, label: &str| PlaceSnapshot {
id,
@ -5955,6 +6009,7 @@ mod tests {
narrative_commands: count(WorkLane::Narrative),
operational_commands: count(WorkLane::Operational),
elaboration_commands: count(WorkLane::Elaboration),
seed_commands: count(WorkLane::Seed),
})
}
}
@ -8224,11 +8279,13 @@ mod tests {
narrative_commands: 0,
operational_commands: 0,
elaboration_commands: 1,
seed_commands: 0,
},
ControllerWorkCustody::Owned {
narrative_commands: 0,
operational_commands: 1,
elaboration_commands: 0,
seed_commands: 0,
}
);
}

View file

@ -24,8 +24,8 @@ use super::patch::{
};
use super::{
BoundaryDigest, CausalBoundary, CommandId, Declaration, ElaborationPort, EntityId, EvidenceRef,
JurisdictionKey, KernelError, MailboxError, Mismatch, PatchAnswer, SubjectId, WorldId,
WorldPatch, WorldPhase, WorldSnapshot,
JurisdictionKey, KernelError, MailboxError, Mismatch, PatchAnswer, ScaleDeficitRow, SeedPort,
SubjectId, SubjectKind, WorldId, WorldPatch, WorldPhase, WorldSnapshot,
};
use async_trait::async_trait;
use codex_connector::CodexInputItem;
@ -201,20 +201,20 @@ pub(super) fn valid_elaboration_progression(
#[derive(Clone, Debug, Error, PartialEq, Eq)]
#[error("{detail}")]
pub(super) struct EvidenceError {
pub(crate) struct EvidenceError {
detail: String,
}
/// The referents the answer names, as world labels.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct EvidenceQuery {
pub(super) referents: Vec<String>,
pub(crate) struct EvidenceQuery {
pub(crate) referents: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct EvidenceReceipt {
pub(crate) struct EvidenceReceipt {
/// The exact reference an admitted patch may carry.
pub(super) reference: EvidenceRef,
pub(crate) reference: EvidenceRef,
/// What the elaborator is allowed to read. Prompt material, never state.
pub(super) excerpt: String,
pub(super) source: String,
@ -226,7 +226,7 @@ pub(super) struct EvidenceReceipt {
/// string is canonical and that an `Admit`'s reference is listed in the same
/// patch.
#[async_trait]
pub(super) trait EvidenceSource: Send + Sync {
pub(crate) trait EvidenceSource: Send + Sync {
async fn retrieve(&self, query: &EvidenceQuery) -> Result<Vec<EvidenceReceipt>, EvidenceError>;
}
@ -235,7 +235,7 @@ pub(super) trait EvidenceSource: Send + Sync {
/// structure and operate on it, but cannot mint quantity, because `admit`
/// requires a listed reference and there are none. Creation of quantity without
/// provenance should be impossible, not merely discouraged.
pub(super) struct NullEvidenceSource;
pub(crate) struct NullEvidenceSource;
#[async_trait]
impl EvidenceSource for NullEvidenceSource {
@ -720,6 +720,15 @@ fn build_prompt(
"Answer: {}\n\n",
render_answer(snapshot, &session.answer)
));
prompt_body(&mut prompt, receipts, last_mismatches);
prompt
}
/// The half of an authoring prompt that is neither jurisdiction- nor
/// phase-specific: what may be cited, what must be repaired, and which tools
/// exist. One owner, so the two lanes cannot drift on what a citation rule says
/// or on which tools are offered.
fn prompt_body(prompt: &mut String, receipts: &[EvidenceReceipt], last_mismatches: &[Mismatch]) {
if receipts.is_empty() {
prompt.push_str(
"No evidence receipts were retrieved. You may declare structure and operate on it; you cannot admit quantity without a receipt.\n\n",
@ -744,7 +753,6 @@ fn build_prompt(
prompt.push('\n');
}
prompt.push_str(&format!("Tools: {}\n", patch_tool_signatures()));
prompt
}
fn render_jurisdiction(snapshot: &WorldSnapshot, jurisdiction: JurisdictionKey) -> String {
@ -1047,6 +1055,704 @@ fn digest_of<T: Serialize>(value: &T) -> Result<String, ControllerError> {
Ok(format!("sha256:{:x}", Sha256::digest(bytes)))
}
// ---- The seed lane -------------------------------------------------------
//
// Draft's authoring session, beside Active's. It shares this file's round loop,
// tool application, evidence filter, cap check, repair prompt, and checkpoint
// discipline; it differs in three places and no fourth — the phase it runs in,
// the row it selects, and the port it submits through.
const SEED_NAMESPACE: &str = "ghostlight.command.seed.v1";
const SEED_INSTRUCTIONS: &str = "Use only the supplied tools to author living structure inside your jurisdiction. A subject counts only when it has a controller, at least one affordance grant, and holds a goal commitment. Author the shortfall you were given, then submit. Recording a gap changes nothing.";
/// The row a session answers, plus the ancestry it was built against. There is
/// no `PatchAnswer` here: a seed answers nothing, and giving this session an
/// answer field it must never submit would be a field that lies.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct SeedSession {
pub(super) world_id: WorldId,
pub(super) jurisdiction: JurisdictionKey,
pub(super) kind: SubjectKind,
pub(super) target: u32,
pub(super) qualified: u32,
/// The commit digest the draft is built against, so each landed patch opens
/// a fresh session and the sweep advances instead of resubmitting one id.
pub(super) ancestry: String,
}
/// Derived from the world, the row, and the ancestry, so a crashed loop resumes
/// the same store row without a registry. `patch::derive_id` keeps exactly two
/// call sites: this is a command key, not a referent id.
fn seed_command_id(session: &SeedSession) -> Result<CommandId, ControllerError> {
let scope = digest_of(&(session.world_id, session.jurisdiction, session.kind))?;
Ok(CommandId::derived(
SEED_NAMESPACE,
&[&scope, &session.ancestry],
))
}
/// `ElaborationCheckpoint`'s stages with `SeedSession` substituted and nothing
/// added. The draft is not a field, for the same reason it is not one there: it
/// is re-derived from `completed`, so a resumed session cannot submit a draft
/// the conversation does not produce.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "stage", rename_all = "snake_case")]
pub(super) enum SeedCheckpoint {
SeedInFlight {
command_id: CommandId,
session: SeedSession,
agent_prompt: String,
last_mismatches: Vec<Mismatch>,
completed: Vec<InferenceOutput>,
invocation: PreparedInference,
},
ReadyToSubmit {
command_id: CommandId,
session: SeedSession,
agent_prompt: String,
last_mismatches: Vec<Mismatch>,
completed: Vec<InferenceOutput>,
},
/// The round budget ran out, or the model finished without a submit. The
/// shortfall stays derived; nothing is repaired by waiting.
NoPatch {
command_id: CommandId,
session: SeedSession,
agent_prompt: String,
completed: Vec<InferenceOutput>,
gaps: Vec<ControllerNeed>,
},
}
impl SeedCheckpoint {
pub(super) fn command_id(&self) -> CommandId {
match self {
Self::SeedInFlight { command_id, .. }
| Self::ReadyToSubmit { command_id, .. }
| Self::NoPatch { command_id, .. } => *command_id,
}
}
fn session(&self) -> &SeedSession {
match self {
Self::SeedInFlight { session, .. }
| Self::ReadyToSubmit { session, .. }
| Self::NoPatch { session, .. } => session,
}
}
pub(super) fn is_initial(&self) -> bool {
matches!(
self,
Self::SeedInFlight {
completed,
last_mismatches,
..
} if completed.is_empty() && last_mismatches.is_empty()
)
}
pub(super) fn integrity_is_valid(&self) -> bool {
match self {
Self::SeedInFlight {
command_id,
agent_prompt,
last_mismatches,
completed,
invocation,
..
} => {
!agent_prompt.is_empty()
&& canonical_model(&invocation.invocation.request.model)
&& match evaluate_elaboration_loop(agent_prompt, last_mismatches, completed) {
Ok(ElaborationLoopEvaluation::Continue { conversation }) => seed_request(
*command_id,
completed.len(),
&invocation.invocation.request.model,
conversation,
)
.is_ok_and(|expected| {
prepared_matches_request(
invocation,
&expected,
*command_id,
completed.len(),
)
}),
Ok(ElaborationLoopEvaluation::Complete { .. }) | Err(_) => false,
}
}
Self::ReadyToSubmit {
agent_prompt,
last_mismatches,
completed,
..
} => derive_elaboration_capture(agent_prompt, last_mismatches, completed)
.is_ok_and(|capture| capture.submitted),
Self::NoPatch {
agent_prompt,
completed,
..
} => derive_elaboration_capture(agent_prompt, &[], completed)
.is_ok_and(|capture| !capture.submitted),
}
}
}
/// A session may gather more evidence and may end, but it may never rewrite the
/// row it bound to.
pub(super) fn valid_seed_progression(existing: &SeedCheckpoint, next: &SeedCheckpoint) -> bool {
if existing.command_id() != next.command_id() || existing.session() != next.session() {
return false;
}
match (existing, next) {
(
SeedCheckpoint::SeedInFlight {
completed: existing,
..
},
SeedCheckpoint::SeedInFlight {
completed: next, ..
}
| SeedCheckpoint::ReadyToSubmit {
completed: next, ..
}
| SeedCheckpoint::NoPatch {
completed: next, ..
},
) => next.len() >= existing.len() && next.starts_with(existing),
// A rejection reopens the same command id for repair. A rejected
// command mutates nothing, so the round evidence starts over.
(
SeedCheckpoint::ReadyToSubmit { .. },
SeedCheckpoint::SeedInFlight {
last_mismatches, ..
},
) => !last_mismatches.is_empty(),
_ => false,
}
}
/// What one seed `step` did, for the transport that asked for it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SeedOutcome {
/// Every row's deficit is zero: the terminating condition.
Clean,
/// The world is not Draft. Seeding is Draft's lane exactly as elaboration
/// is Active's.
NotDraft,
Committed,
/// The patch committed and the row's deficit did not strictly fall. A fixed
/// point, not a retry.
NoProgress,
/// The kernel returned a complete mismatch set; the next round repairs it.
Rejected,
/// The world moved under the session. Re-select; this is not a retry loop.
Superseded,
/// The round budget was spent without a submit.
NoPatch,
}
impl SeedOutcome {
pub(crate) fn name(self) -> &'static str {
match self {
Self::Clean => "clean",
Self::NotDraft => "not_draft",
Self::Committed => "committed",
Self::NoProgress => "no_progress",
Self::Rejected => "rejected",
Self::Superseded => "superseded",
Self::NoPatch => "no_patch",
}
}
}
/// The Draft authoring loop. Holds no state between steps; every field is a
/// port, an identity, or the owner's own one-sentence brief.
pub(crate) struct SeedRunner {
mailbox: SeedPort,
inference: Arc<dyn InferencePort>,
evidence: Arc<dyn EvidenceSource>,
work: Arc<dyn ControllerWorkStore>,
model: String,
brief: Option<String>,
}
impl SeedRunner {
pub(super) fn new(
mailbox: SeedPort,
inference: Arc<dyn InferencePort>,
evidence: Arc<dyn EvidenceSource>,
work: Arc<dyn ControllerWorkStore>,
model: String,
brief: Option<String>,
) -> Self {
Self {
mailbox,
inference,
evidence,
work,
model,
brief,
}
}
/// One shortfall row, start to finish.
pub(crate) async fn step(&self) -> Result<SeedOutcome, ControllerError> {
let snapshot = self.mailbox.snapshot().await.map_err(snapshot_error)?;
if snapshot.phase != WorldPhase::Draft {
return Ok(SeedOutcome::NotDraft);
}
let Some(row) = select_row(&snapshot) else {
return Ok(SeedOutcome::Clean);
};
let session = SeedSession {
world_id: snapshot.world_id,
jurisdiction: row.jurisdiction,
kind: row.kind,
target: row.target,
qualified: row.qualified,
ancestry: snapshot.last_commit_digest.clone().unwrap_or_default(),
};
let command_id = seed_command_id(&session)?;
let receipts = self
.evidence
.retrieve(&EvidenceQuery {
referents: seed_referents(&snapshot, &session, self.brief.as_deref()),
})
.await
.map_err(|error| ControllerError::WorkPersistence(error.to_string()))?;
let allowed: BTreeSet<EvidenceRef> = receipts
.iter()
.map(|receipt| receipt.reference.clone())
.collect();
let existing = match self.work.lookup(command_id).await? {
ControllerWorkLookup::Missing => None,
ControllerWorkLookup::Confirmed(ControllerWork::Seed(checkpoint))
| ControllerWorkLookup::CustodyUncertain(ControllerWork::Seed(checkpoint)) => {
if checkpoint.session() != &session {
return Ok(SeedOutcome::Superseded);
}
Some(checkpoint)
}
ControllerWorkLookup::Confirmed(_) | ControllerWorkLookup::CustodyUncertain(_) => {
return Err(ControllerError::CommandMismatch);
}
};
let (agent_prompt, mut last_mismatches, mut completed) = match existing {
Some(SeedCheckpoint::NoPatch { .. }) => return Ok(SeedOutcome::NoPatch),
Some(
SeedCheckpoint::SeedInFlight {
agent_prompt,
last_mismatches,
completed,
..
}
| SeedCheckpoint::ReadyToSubmit {
agent_prompt,
last_mismatches,
completed,
..
},
) => (agent_prompt, last_mismatches, completed),
None => (
build_seed_prompt(&snapshot, &session, self.brief.as_deref(), &receipts, &[]),
Vec::new(),
Vec::new(),
),
};
loop {
match evaluate_elaboration_loop(&agent_prompt, &last_mismatches, &completed)? {
ElaborationLoopEvaluation::Continue { conversation } => {
let request =
seed_request(command_id, completed.len(), &self.model, conversation)?;
let invocation = self.inference.prepare(request).map_err(|source| {
ControllerError::Inference {
purpose: InferencePurpose::Elaboration,
source,
}
})?;
self.persist(SeedCheckpoint::SeedInFlight {
command_id,
session: session.clone(),
agent_prompt: agent_prompt.clone(),
last_mismatches: last_mismatches.clone(),
completed: completed.clone(),
invocation: invocation.clone(),
})
.await?;
let output = self.inference.infer(invocation).await.map_err(|source| {
ControllerError::Inference {
purpose: InferencePurpose::Elaboration,
source,
}
})?;
completed.push(output);
}
ElaborationLoopEvaluation::Complete { capture } => {
if !capture.submitted {
self.persist(SeedCheckpoint::NoPatch {
command_id,
session,
agent_prompt,
completed,
gaps: capture.gaps,
})
.await?;
return Ok(SeedOutcome::NoPatch);
}
self.persist(SeedCheckpoint::ReadyToSubmit {
command_id,
session: session.clone(),
agent_prompt: agent_prompt.clone(),
last_mismatches: last_mismatches.clone(),
completed: completed.clone(),
})
.await?;
let draft = filter_evidence(capture.draft, &allowed);
if let Err(error) = patch::check_patch_caps(&draft) {
return Err(ControllerError::Serialization(format!(
"seed draft exceeded a patch item cap: {error:?}"
)));
}
let submitted = self
.mailbox
.submit_seed(command_id, snapshot.world_id, snapshot.revision, draft)
.await;
return match submitted {
// Termination is the deficit, not a counter the runner
// keeps: a commit that did not strictly lower this
// row's shortfall is a fixed point.
Ok(_) => {
let after = self.mailbox.snapshot().await.map_err(snapshot_error)?;
let remaining = row_deficit(&after, &session);
Ok(if remaining < row.deficit {
SeedOutcome::Committed
} else {
SeedOutcome::NoProgress
})
}
Err(MailboxError::Kernel(KernelError::PatchRejected(mismatches))) => {
last_mismatches = mismatches;
let repaired = build_seed_prompt(
&snapshot,
&session,
self.brief.as_deref(),
&receipts,
&last_mismatches,
);
self.persist_repair(command_id, &session, &repaired, &last_mismatches)
.await?;
Ok(SeedOutcome::Rejected)
}
Err(MailboxError::Kernel(KernelError::RevisionMismatch { .. })) => {
Ok(SeedOutcome::Superseded)
}
Err(error) => Err(snapshot_error(error)),
};
}
}
}
}
/// One bounded sweep. The budget is the caller's, because who may spend a
/// paid endpoint is a transport question and how far a deficit has fallen
/// is not.
pub(crate) async fn sweep(&self, sessions: usize) -> Result<SeedOutcome, ControllerError> {
let mut last = SeedOutcome::Clean;
for _ in 0..sessions {
last = self.step().await?;
if !matches!(last, SeedOutcome::Committed) {
break;
}
}
Ok(last)
}
async fn persist(&self, checkpoint: SeedCheckpoint) -> Result<(), ControllerError> {
match self.work.persist(&ControllerWork::Seed(checkpoint)).await? {
ControllerWorkWrite::Applied | ControllerWorkWrite::AlreadyPresent => Ok(()),
ControllerWorkWrite::CustodyUncertain => Err(ControllerError::WorkPersistence(
"controller work custody is uncertain".into(),
)),
}
}
async fn persist_repair(
&self,
command_id: CommandId,
session: &SeedSession,
agent_prompt: &str,
last_mismatches: &[Mismatch],
) -> Result<(), ControllerError> {
let conversation = match evaluate_elaboration_loop(agent_prompt, last_mismatches, &[])? {
ElaborationLoopEvaluation::Continue { conversation } => conversation,
ElaborationLoopEvaluation::Complete { .. } => {
return Err(ControllerError::Serialization(
"a repair round completed before any evidence".into(),
));
}
};
let request = seed_request(command_id, 0, &self.model, conversation)?;
let invocation =
self.inference
.prepare(request)
.map_err(|source| ControllerError::Inference {
purpose: InferencePurpose::Elaboration,
source,
})?;
self.persist(SeedCheckpoint::SeedInFlight {
command_id,
session: session.clone(),
agent_prompt: agent_prompt.to_owned(),
last_mismatches: last_mismatches.to_vec(),
completed: Vec::new(),
invocation,
})
.await
}
}
/// The first shortfall the world reports, in the order the snapshot reports
/// them. The panel calls this too, so the card and the runner cannot disagree
/// about what happens next.
pub(crate) fn select_row(snapshot: &WorldSnapshot) -> Option<ScaleDeficitRow> {
snapshot
.scale_deficit
.iter()
.find(|row| row.deficit > 0)
.copied()
}
fn row_deficit(snapshot: &WorldSnapshot, session: &SeedSession) -> u32 {
snapshot
.scale_deficit
.iter()
.find(|row| row.jurisdiction == session.jurisdiction && row.kind == session.kind)
.map_or(0, |row| row.deficit)
}
fn seed_request(
command_id: CommandId,
round: usize,
model: &str,
input: Vec<CodexInputItem>,
) -> Result<InferenceRequest, ControllerError> {
tool_request(
command_id,
round,
InferencePurpose::Elaboration,
model,
SEED_INSTRUCTIONS,
input,
patch_tools(),
RequestShape {
max_output_tokens: 4_000,
parallel_tool_calls: false,
},
)
}
/// What the Vault is asked about. Deliberately not `answer_referents`, which
/// returns nothing for the uncovered residual — the only jurisdiction a genesis
/// world has. A one-room world retrieves against its own title and the labels
/// of the places that already exist rather than against nothing.
fn seed_referents(
snapshot: &WorldSnapshot,
session: &SeedSession,
brief: Option<&str>,
) -> Vec<String> {
let mut referents = Vec::new();
match session.jurisdiction {
JurisdictionKey::PlaceSubtree(root) => referents.extend(
snapshot
.places
.iter()
.find(|entry| entry.id == root)
.map(|entry| entry.label.clone()),
),
JurisdictionKey::Uncovered => referents.push(snapshot.title.clone()),
}
if let Some(brief) = brief.map(str::trim).filter(|value| !value.is_empty()) {
referents.push(brief.to_owned());
}
referents.extend(
snapshot
.places
.iter()
.take(8)
.map(|entry| entry.label.clone()),
);
referents.dedup();
referents
}
fn build_seed_prompt(
snapshot: &WorldSnapshot,
session: &SeedSession,
brief: Option<&str>,
receipts: &[EvidenceReceipt],
last_mismatches: &[Mismatch],
) -> String {
let mut prompt = String::new();
prompt.push_str("You are seeding a world before it opens. Nothing here is running yet.\n\n");
prompt.push_str(&format!("World: {}\n", snapshot.title));
prompt.push_str(&format!(
"Jurisdiction: {}\n",
render_jurisdiction(snapshot, session.jurisdiction)
));
prompt.push_str(&format!(
"Shortfall: this jurisdiction is meant to hold {} {} who are alive in it; {} qualify today. Author the rest.\n",
session.target,
render_kind(session.kind),
session.qualified
));
if let Some(brief) = brief.map(str::trim).filter(|value| !value.is_empty()) {
prompt.push_str(&format!("{brief}\n"));
}
prompt.push_str(
"\nA subject qualifies only when it has a controller, at least one affordance grant, and holds a goal commitment. Declare people, institutions, and populations who want something; give each a controller, grants, a position, and a goal. Give them the rest of a life: routines and obligations that recur, counterparties, channels they speak on and who controls them, authority and the offices that lend it, holdings and the dependencies those holdings serve, routes between the places they move through. A subject with no counterparty who can command or litigate its goal leaves a boundary for the elaborator; that is allowed and expected, not an error.\nYou may not declare a human-controlled subject: only the world's first person is human, and that was genesis.\n\n",
);
prompt.push_str(&render_world_structure(snapshot));
prompt.push('\n');
prompt_body(&mut prompt, receipts, last_mismatches);
prompt
}
fn render_kind(kind: SubjectKind) -> &'static str {
match kind {
SubjectKind::Person => "persons",
SubjectKind::Institution => "institutions",
SubjectKind::Population => "populations",
}
}
/// The world the session is authoring into, rendered from snapshot fields that
/// already exist. A renderer beside `render_jurisdiction` and `render_answer`,
/// and seed-only: widening the Active elaborator's prompt is a behaviour change
/// to a working lane and belongs to whoever measures it.
fn render_world_structure(snapshot: &WorldSnapshot) -> String {
let place_label = |id: EntityId| {
snapshot
.places
.iter()
.find(|entry| entry.id == id)
.map_or_else(
|| "an unnamed place".to_owned(),
|entry| entry.label.clone(),
)
};
let mut out = String::from("Standing structure:\n");
out.push_str(" Places:");
if snapshot.places.is_empty() {
out.push_str(" none");
}
for place in &snapshot.places {
match place.container {
Some(container) => {
out.push_str(&format!(
" {} (in {});",
place.label,
place_label(container)
));
}
None => out.push_str(&format!(" {};", place.label)),
}
}
out.push_str("\n Routes:");
if snapshot.routes.is_empty() {
out.push_str(" none");
}
for route in &snapshot.routes {
out.push_str(&format!(
" {}: {} -> {}, {:?}, {};",
route.label,
place_label(route.from),
place_label(route.to),
route.access,
if route.open { "open" } else { "closed" }
));
}
out.push_str("\n Subjects:");
if snapshot.subjects.is_empty() {
out.push_str(" none");
}
for subject in &snapshot.subjects {
out.push_str(&format!(
" {} ({:?}, {}, in {}, grants: {}, {});",
subject.label,
subject.kind,
subject
.controller_mode
.map_or_else(|| "external".to_owned(), |mode| format!("{mode:?}")),
subject
.position
.map_or_else(|| "nowhere".to_owned(), place_label),
subject.affordances.len(),
if subject.qualified {
"counts"
} else {
"does not count"
}
));
}
out.push_str("\n Affordances:");
if snapshot.affordances.is_empty() {
out.push_str(" none");
}
for affordance in &snapshot.affordances {
out.push_str(&format!(
" {}, roles: {}, {};",
affordance.entry.kind.0,
if affordance.entry.roles.is_empty() {
"none".to_owned()
} else {
affordance
.entry
.roles
.iter()
.map(|role| role.role.0.clone())
.collect::<Vec<_>>()
.join("/")
},
if affordance.entry.carries_speech {
"speech"
} else {
"silent"
}
));
}
out.push_str("\n Resources:");
if snapshot.resources.is_empty() {
out.push_str(" none");
}
for resource in &snapshot.resources {
out.push_str(&format!(" {};", resource.label));
}
out.push_str("\n Shortfall rows:");
if snapshot.scale_deficit.is_empty() {
out.push_str(" none");
}
for row in &snapshot.scale_deficit {
out.push_str(&format!(
" {} {}: target {}, qualified {}, short {};",
render_jurisdiction(snapshot, row.jurisdiction),
render_kind(row.kind),
row.target,
row.qualified,
row.deficit
));
}
out.push('\n');
out
}
#[cfg(test)]
mod tests {
use super::*;

View file

@ -122,6 +122,11 @@ impl WorldMailbox {
position: Some(Ref::Draft(DraftHandle::new(GENESIS_PLACE))),
})
};
// Roots stand beside the commons, not inside it: a root contained by
// the commons would make every commons subject count toward that root
// through `covers_place`, and the world's first person belongs to no
// jurisdiction's population target. The owner subject lands in
// `Uncovered`, visible and reducing nothing.
let mut declarations = vec![
Declaration::Entity(EntityDeclaration {
handle: DraftHandle::new(GENESIS_PLACE),
@ -154,6 +159,22 @@ impl WorldMailbox {
NewController::OperationalAgent,
));
}
for root in &input.jurisdictions {
declarations.push(Declaration::Entity(EntityDeclaration {
handle: DraftHandle::new(root.handle.clone()),
label: root.label.trim().to_owned(),
kind: EntityKind::Place,
container: None,
}));
}
let scale_intent = WorldScaleIntentRef {
targets: input.targets,
jurisdictions: input
.jurisdictions
.iter()
.map(|root| (DraftHandle::new(root.handle.clone()), root.permille))
.collect(),
};
self.create_authenticated(
CreateWorld {
id: input.id,
@ -164,9 +185,7 @@ impl WorldMailbox {
operations: Vec::new(),
evidence: Vec::new(),
},
// World ingress authors no scale target: the intent names
// jurisdiction roots, and genesis declares only the commons.
scale_intent: WorldScaleIntentRef::default(),
scale_intent,
},
AuthenticatedCaller::verified_principal(principal_id),
)
@ -539,6 +558,64 @@ impl ElaborationPort {
}
}
/// The seeding organ's narrowing of the mailbox. It reads a snapshot and
/// commits one unanswered Draft patch as the owner. It has no `operator_log`,
/// no `agency_graph`, no `submit_clock`, and no `ApproveDraft`/`ActivateWorld`:
/// those are not methods on this type, so reaching for one fails to compile.
///
/// It carries the owner's `VerifiedPrincipalEvidence` for the session's
/// lifetime because a multi-round session cannot re-derive it: the only minter
/// is `AppSessionOwner` holding a live cookie, and a checkpoint that stored an
/// account hash so the runner could re-mint one would be a second minter and an
/// offline forge path. The evidence is captured from the request that asked for
/// the work and dies with the port.
#[derive(Clone)]
pub(crate) struct SeedPort {
mailbox: WorldMailbox,
principal: VerifiedPrincipalEvidence,
}
impl SeedPort {
pub(crate) fn new(mailbox: WorldMailbox, principal: VerifiedPrincipalEvidence) -> Self {
Self { mailbox, principal }
}
pub(super) async fn snapshot(&self) -> Result<WorldSnapshot, MailboxError> {
self.mailbox.snapshot().await
}
/// One body, hardcoded. The seed lane cannot express an answered patch, so
/// it meets exactly one answer gate — `require_answer`'s Draft branch — and
/// the owner arm of `require_patch_author`, which is unconfined.
///
/// It takes `expected_revision` rather than stamping one: a world that
/// moved under a long session fails `StaleRevision` and the runner reports
/// `Superseded`, where a stamped submission would silently commit against a
/// world the model never saw.
pub(super) async fn submit_seed(
&self,
command_id: CommandId,
world_id: WorldId,
expected_revision: u64,
patch: WorldPatch,
) -> Result<SubmitReceipt, MailboxError> {
self.mailbox
.submit_principal(
PrincipalCommandIntent {
id: command_id,
world_id,
expected_revision,
body: CommandBody::AdmitPatch {
answers: None,
patch,
},
},
&self.principal,
)
.await
}
}
/// The consumer ingress's narrowing of the mailbox: one method. The ingress
/// has no reason to read the world — it selects no answer, pre-validates
/// nothing, and returns a receipt rather than state — so a snapshot method here

View file

@ -15,6 +15,7 @@ mod journal;
mod mailbox;
mod patch;
mod tool_schema;
mod vault;
pub(crate) use action::ActionMismatch;
pub(crate) use clock::{FictionalMinutes, Motion, TickMinutes};
@ -31,8 +32,9 @@ pub(crate) use controllers::{
pub(crate) use cover::{
AgencyGraph, Cell, CellId, Constituent, Cover, CoverBudget, Resolution, TickIndex, derive_cover,
};
pub(crate) use elaboration::{SeedOutcome, select_row};
pub(crate) use mailbox::{
ConsumerPort, ControllerPort, ElaborationPort, MailboxError, WorldMailbox,
ConsumerPort, ControllerPort, ElaborationPort, MailboxError, SeedPort, WorldMailbox,
};
pub(crate) use patch::{
AccessKind, Affordance, AffordanceKindName, Audience, AuthoredSource, AuthorityGrant,
@ -51,6 +53,7 @@ use patch::{
};
#[cfg(test)]
pub(crate) use patch::{AuthorityGrantRef, AuthorityTargetRef};
pub(crate) use vault::VaultEvidenceSource;
// Test-only narrowing of the controller organ's inference and work-store
// seams, so `runtime`'s own spec tests can drive `ControllerRunner` over a
// counting/scripted `InferencePort` and an in-memory `ControllerWorkStore`
@ -314,6 +317,23 @@ pub(crate) struct CreateWorldIntent {
pub(crate) human_subject_label: String,
pub(crate) narrative_persona_label: Option<String>,
pub(crate) operational_agent_label: Option<String>,
/// World-wide target of goal-bearing subjects per kind. Required, and may
/// be empty: a world with no target is a deliberate choice, not a default
/// that arrives because nobody said anything.
pub(crate) targets: BTreeMap<SubjectKind, u32>,
/// The jurisdiction roots genesis declares beside the commons, because
/// `resolve_patch` only resolves roots the same patch declares.
pub(crate) jurisdictions: Vec<CreateJurisdictionIntent>,
}
/// One jurisdiction root as ingress states it. The handle is a string here and
/// a `DraftHandle` inside the world subtree, which is the one lowering: the
/// handle constructor is not reachable from runtime ingress.
#[derive(Clone, Debug)]
pub(crate) struct CreateJurisdictionIntent {
pub(crate) handle: String,
pub(crate) label: String,
pub(crate) permille: u32,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
@ -871,6 +891,11 @@ pub(crate) struct SubjectSnapshot {
/// subject's state, and the actor already sees the commitment that produced
/// it.
pub(crate) pressures: Vec<PressureSnapshot>,
/// A projection of `qualifies`, not a stored flag and not a second count:
/// whether this subject already reduces its jurisdiction's scale deficit.
/// The seed brief needs to say which subjects count; recomputing the
/// conjunction outside the kernel would be a second definition of alive.
pub(crate) qualified: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@ -3411,6 +3436,7 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
magnitude: *magnitude,
})
.collect(),
qualified: qualifies(state, *subject_id),
})
})
.collect::<Result<Vec<_>, KernelError>>()?;
@ -3660,19 +3686,25 @@ pub(crate) struct ScaleDeficitRow {
pub(crate) deficit: u32,
}
/// Whether a subject counts toward the world's scale target. Three of the four
/// clauses cannot currently fail — the world-level phase gate, the one-
/// controller rule, and the non-empty grant set are already enforced elsewhere
/// — so `Goal` carries the whole discrimination at this pass. The conjunction
/// is written once anyway, because retirement and grant revocation make two of
/// the clauses live later and a scattered count would then be wrong in three
/// places. "Executable" is structural, never "preconditions currently hold":
/// evaluating them per subject per snapshot would make the deficit flicker as
/// routes open and close.
/// Whether a subject counts toward the world's scale target. Aliveness is
/// structural and phase-free: a controller, a non-empty grant set, and a held
/// `Goal`. A Draft world's deficit is what the seed lane has left to author; an
/// Active world's is what the elaborator has left to answer.
///
/// There is no phase clause here because `require_answer` already owns the
/// Draft-answer refusal: it refuses every Draft answer outright, so a phase
/// clause in this predicate would protect nothing and would only pin a Draft
/// world's deficit at the authored intent forever, leaving the seed lane no
/// derived termination.
///
/// The conjunction is written once, because retirement and grant revocation
/// make the first two clauses live later and a scattered count would then be
/// wrong in three places. "Executable" is structural, never "preconditions
/// currently hold": evaluating them per subject per snapshot would make the
/// deficit flicker as routes open and close.
fn qualifies(state: &WorldState, subject_id: SubjectId) -> bool {
let scope = DecisionScope { subject_id };
state.phase == WorldPhase::Active
&& state.controller_assignments.contains_key(&scope)
state.controller_assignments.contains_key(&scope)
&& state
.affordance_grants
.get(&scope)

View file

@ -0,0 +1,556 @@
//! A read-only markdown vault, behind the world's `EvidenceSource` seam.
//!
//! It resolves referent strings to notes and hands back bounded excerpts. It
//! never writes, never leaves its configured root, never touches git or the
//! network, and holds no world truth: its output is `EvidenceReceipt`s whose
//! `excerpt` and `source` are prompt material and whose `reference` is the only
//! thing that can ever reach the journal.
//!
//! It is the one authority in the seed lane that can be tested with no kernel
//! at all, which is why it is a module.
use super::EvidenceRef;
use super::elaboration::{EvidenceError, EvidenceQuery, EvidenceReceipt, EvidenceSource};
use async_trait::async_trait;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};
use thiserror::Error;
/// Below `MAX_PATCH_EVIDENCE` (64), so a session that cites everything it was
/// handed still fits inside one patch.
const MAX_VAULT_RECEIPTS: usize = 24;
const MAX_HITS_PER_REFERENT: usize = 3;
/// One hop, never recursive: a note's neighbours are context, and a transitive
/// walk would hand a session the whole vault under one referent.
const MAX_LINK_FANOUT: usize = 4;
const MAX_EXCERPT_CHARS: usize = 800;
const MAX_VAULT_NOTES: usize = 4_096;
const MAX_NOTE_BYTES: u64 = 512 * 1024;
#[derive(Debug, Error)]
pub(crate) enum VaultError {
#[error("vault root is not a readable directory: {0}")]
Root(String),
#[error("vault scope escapes its root: {0}")]
Scope(String),
#[error("vault holds more than {MAX_VAULT_NOTES} notes")]
TooManyNotes,
}
/// One note as the reader holds it. The body is kept in memory because the
/// corpora this reads are a few megabytes of markdown and a per-query file read
/// would buy nothing but a second failure mode.
#[derive(Clone, Debug)]
struct VaultNote {
/// The evidence reference: the note's vault-relative path with forward
/// slashes, e.g. `Spoilers/Places/Low Sere.md`. It is a path and not a
/// wikilink target, because stems collide across directories; not a scheme,
/// because the kernel has no scheme registry; and not a digest, because a
/// human must be able to resolve it years later.
reference: String,
title: String,
/// Everything after the frontmatter block.
body: String,
/// Wikilink targets, left side only.
links: Vec<String>,
}
pub(crate) struct VaultEvidenceSource {
notes: Vec<VaultNote>,
/// Many-to-one: filename stem, frontmatter title, and each alias all key
/// the same note. Ambiguity is resolved by the shortest reference path, and
/// refused for that referent when two candidates tie.
by_key: BTreeMap<String, Vec<usize>>,
}
impl VaultEvidenceSource {
/// `root` is the configured vault root; `scope` is a relative subdirectory
/// or empty. Both are canonicalized and the scope must live under the root,
/// so `..`, an absolute scope, and a symlink out are all refused here. A
/// spoiler tier is a directory in every vault that has one, so it is
/// expressed as a scope and there is no tier field anywhere in this file.
pub(crate) fn open(root: &Path, scope: &str) -> Result<Self, VaultError> {
let root = root
.canonicalize()
.map_err(|error| VaultError::Root(error.to_string()))?;
if !root.is_dir() {
return Err(VaultError::Root(root.display().to_string()));
}
let scope_path = if scope.trim().is_empty() {
root.clone()
} else {
let relative = Path::new(scope.trim());
if relative.is_absolute()
|| relative
.components()
.any(|part| !matches!(part, Component::Normal(_)))
{
return Err(VaultError::Scope(scope.to_owned()));
}
let joined = root.join(relative);
let canonical = joined
.canonicalize()
.map_err(|error| VaultError::Scope(error.to_string()))?;
if !canonical.starts_with(&root) {
return Err(VaultError::Scope(canonical.display().to_string()));
}
canonical
};
let mut paths: Vec<PathBuf> = Vec::new();
collect_notes(&scope_path, &mut paths)?;
paths.sort();
let mut notes = Vec::new();
for path in paths {
let Ok(metadata) = std::fs::metadata(&path) else {
continue;
};
if metadata.len() > MAX_NOTE_BYTES {
continue;
}
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(relative) = path.strip_prefix(&root) else {
continue;
};
let reference = relative
.components()
.map(|part| part.as_os_str().to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join("/");
if reference.trim() != reference || reference.is_empty() {
continue;
}
let stem = path
.file_stem()
.map(|value| value.to_string_lossy().into_owned())
.unwrap_or_default();
let (front, body) = split_frontmatter(&text);
let (front_title, aliases) = read_front_keys(front);
let title = front_title.unwrap_or_else(|| stem.clone());
let links = wikilink_targets(body);
let mut keys: Vec<String> = vec![stem, title.clone()];
keys.extend(aliases);
notes.push((
VaultNote {
reference,
title,
body: body.to_owned(),
links,
},
keys,
));
}
let mut by_key: BTreeMap<String, Vec<usize>> = BTreeMap::new();
for (index, (_, keys)) in notes.iter().enumerate() {
for key in keys {
let key = key.trim().to_lowercase();
if key.is_empty() {
continue;
}
by_key.entry(key).or_default().push(index);
}
}
Ok(Self {
notes: notes.into_iter().map(|(note, _)| note).collect(),
by_key,
})
}
/// Exact key first, then a bounded keyword search. A referent whose exact
/// match is ambiguous between two equally short paths resolves to nothing
/// rather than to a guess.
fn resolve(&self, referent: &str) -> Vec<usize> {
let key = referent.trim().to_lowercase();
if let Some(candidates) = self.by_key.get(&key) {
let mut ranked: Vec<usize> = candidates.clone();
ranked.sort_by_key(|index| {
(
self.notes[*index].reference.len(),
self.notes[*index].reference.clone(),
)
});
ranked.dedup();
if ranked.len() == 1 {
return ranked;
}
let shortest = self.notes[ranked[0]].reference.len();
let tied = ranked
.iter()
.filter(|index| self.notes[**index].reference.len() == shortest)
.count();
return if tied == 1 {
vec![ranked[0]]
} else {
Vec::new()
};
}
let tokens: Vec<String> = key
.split_whitespace()
.filter(|token| token.len() > 2)
.map(str::to_owned)
.collect();
if tokens.is_empty() {
return Vec::new();
}
let mut scored: Vec<(usize, usize)> = self
.notes
.iter()
.enumerate()
.filter_map(|(index, note)| {
let title = note.title.to_lowercase();
let body = note.body.to_lowercase();
let score: usize = tokens
.iter()
.map(|token| {
usize::from(title.contains(token.as_str())) * 4
+ body.matches(token.as_str()).count().min(8)
})
.sum();
(score > 0).then_some((score, index))
})
.collect();
scored.sort_by_key(|(score, index)| {
(
std::cmp::Reverse(*score),
self.notes[*index].reference.clone(),
)
});
scored
.into_iter()
.take(MAX_HITS_PER_REFERENT)
.map(|(_, index)| index)
.collect()
}
fn receipt(&self, index: usize, heading: Option<&str>) -> EvidenceReceipt {
let note = &self.notes[index];
EvidenceReceipt {
reference: EvidenceRef::new(note.reference.clone()),
excerpt: excerpt(&note.body, heading),
source: note.title.clone(),
}
}
}
#[async_trait]
impl EvidenceSource for VaultEvidenceSource {
async fn retrieve(&self, query: &EvidenceQuery) -> Result<Vec<EvidenceReceipt>, EvidenceError> {
let mut seen: BTreeSet<String> = BTreeSet::new();
let mut receipts = Vec::new();
for referent in &query.referents {
let (target, heading) = match referent.split_once('#') {
Some((target, heading)) => (target, Some(heading)),
None => (referent.as_str(), None),
};
for index in self.resolve(target) {
if receipts.len() >= MAX_VAULT_RECEIPTS {
return Ok(receipts);
}
if seen.insert(self.notes[index].reference.clone()) {
receipts.push(self.receipt(index, heading));
}
for link in self.notes[index].links.iter().take(MAX_LINK_FANOUT) {
if receipts.len() >= MAX_VAULT_RECEIPTS {
return Ok(receipts);
}
let (link_target, link_heading) = match link.split_once('#') {
Some((target, heading)) => (target, Some(heading)),
None => (link.as_str(), None),
};
for linked in self.resolve(link_target) {
if seen.insert(self.notes[linked].reference.clone()) {
receipts.push(self.receipt(linked, link_heading));
}
}
}
}
}
Ok(receipts)
}
}
fn collect_notes(directory: &Path, into: &mut Vec<PathBuf>) -> Result<(), VaultError> {
let entries =
std::fs::read_dir(directory).map_err(|error| VaultError::Root(error.to_string()))?;
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_notes(&path, into)?;
} else if path.extension().is_some_and(|value| value == "md") {
if into.len() >= MAX_VAULT_NOTES {
return Err(VaultError::TooManyNotes);
}
into.push(path);
}
}
Ok(())
}
/// A leading `---` line opens a frontmatter block that runs to the next `---`.
/// Absence is normal — whole vaults carry none — so the fallback is the whole
/// file as body. The block is split, never parsed as YAML: only `title:` and
/// `aliases:` are read, line-wise, and everything else is ignored.
fn split_frontmatter(text: &str) -> (&str, &str) {
let trimmed = text.strip_prefix('\u{feff}').unwrap_or(text);
let Some(rest) = trimmed
.strip_prefix("---\r\n")
.or_else(|| trimmed.strip_prefix("---\n"))
else {
return ("", trimmed);
};
for (offset, line) in rest.match_indices('\n') {
let candidate = rest[..offset].rsplit('\n').next().unwrap_or_default();
if candidate.trim_end() == "---" {
let start = offset - candidate.len();
return (&rest[..start], &rest[offset + line.len()..]);
}
}
("", trimmed)
}
fn read_front_keys(front: &str) -> (Option<String>, Vec<String>) {
let mut title = None;
let mut aliases = Vec::new();
let mut in_alias_list = false;
for line in front.lines() {
let unindented = line.trim_start();
if let Some(item) = unindented.strip_prefix("- ")
&& in_alias_list
{
aliases.push(clean_scalar(item));
continue;
}
in_alias_list = false;
if let Some(value) = unindented.strip_prefix("title:") {
let value = clean_scalar(value);
if !value.is_empty() {
title = Some(value);
}
} else if let Some(value) = unindented.strip_prefix("aliases:") {
let value = value.trim();
if let Some(inner) = value.strip_prefix('[').and_then(|v| v.strip_suffix(']')) {
aliases.extend(inner.split(',').map(clean_scalar).filter(|v| !v.is_empty()));
} else if value.is_empty() {
in_alias_list = true;
} else {
aliases.push(clean_scalar(value));
}
}
}
(
title,
aliases.into_iter().filter(|v| !v.is_empty()).collect(),
)
}
fn clean_scalar(value: &str) -> String {
value
.trim()
.trim_matches(|c| c == '"' || c == '\'')
.trim()
.to_owned()
}
/// Three forms: `[[Target]]`, `[[Target|display]]`, and `[[Target#Heading]]`.
/// The display half is discarded; the heading half is kept, because it seeks
/// the excerpt.
fn wikilink_targets(body: &str) -> Vec<String> {
let mut targets = Vec::new();
let mut rest = body;
while let Some(open) = rest.find("[[") {
rest = &rest[open + 2..];
let Some(close) = rest.find("]]") else {
break;
};
let inner = &rest[..close];
rest = &rest[close + 2..];
let target = inner.split('|').next().unwrap_or_default().trim();
if !target.is_empty() && !targets.iter().any(|seen| seen == target) {
targets.push(target.to_owned());
}
}
targets
}
/// The named heading's section when one was asked for, else the head of the
/// body. Cut at a char boundary, because a reference is bytes and an excerpt is
/// text.
fn excerpt(body: &str, heading: Option<&str>) -> String {
let region = heading
.and_then(|heading| heading_section(body, heading))
.unwrap_or(body);
let region = region.trim();
match region.char_indices().nth(MAX_EXCERPT_CHARS) {
None => region.to_owned(),
Some((cut, _)) => region[..cut].to_owned(),
}
}
fn heading_section<'a>(body: &'a str, heading: &str) -> Option<&'a str> {
let wanted = heading.trim().to_lowercase();
let mut start = None;
let mut level = 0usize;
let mut offset = 0usize;
for line in body.split_inclusive('\n') {
let hashes = line.chars().take_while(|c| *c == '#').count();
if hashes > 0 {
let text = line[hashes..].trim().to_lowercase();
match start {
None if text == wanted => {
start = Some(offset + line.len());
level = hashes;
}
Some(begin) if hashes <= level => return Some(&body[begin..offset]),
_ => {}
}
}
offset += line.len();
}
start.map(|begin| &body[begin..])
}
#[cfg(test)]
mod tests {
use super::*;
fn write(root: &Path, relative: &str, text: &str) {
let path = root.join(relative);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
fn fixture() -> tempfile::TempDir {
let directory = tempfile::tempdir().unwrap();
let root = directory.path();
write(
root,
"Public/Places/Low Sere.md",
"The sere runs dry nine months a year.\nSee [[Rain Gate]] and [[Rain Gate|the gate]].\n",
);
write(
root,
"Public/Places/Rain Gate.md",
"---\ntitle: The Rain Gate\naliases:\n - Gate of Rain\n - Hinge\nstatus: canonical\n---\n# Body\nWater enters here.\n\n## Tolls\nA toll of one is charged.\n",
);
write(root, "Public/index.md", "Public index.\n");
write(root, "Public/World/index.md", "World index, deeper.\n");
write(
root,
"Spoilers/Dungeons/Provenance.md",
"The hinge was built by the drowned. Link: [[Low Sere#Nothing]]\n",
);
directory
}
fn query(referents: &[&str]) -> EvidenceQuery {
EvidenceQuery {
referents: referents.iter().map(|value| (*value).to_owned()).collect(),
}
}
/// Spec test 14. References are vault-relative paths, every wikilink form
/// resolves to the same note as the bare one, an ambiguous stem resolves to
/// the shortest path, the excerpt is bounded, and a source opened on
/// `Public` cannot see `Spoilers`.
#[tokio::test]
async fn the_vault_resolves_titles_aliases_and_wikilinks_inside_its_scope() {
let directory = fixture();
let whole = VaultEvidenceSource::open(directory.path(), "").unwrap();
let receipts = whole.retrieve(&query(&["Low Sere"])).await.unwrap();
assert_eq!(
receipts[0].reference,
EvidenceRef::new("Public/Places/Low Sere.md"),
"a reference is the vault-relative path, forward-slashed"
);
// The bare and the piped link are one target, and the linked note came
// back through the one-hop fanout.
assert!(
receipts
.iter()
.any(|receipt| receipt.reference == EvidenceRef::new("Public/Places/Rain Gate.md"))
);
// Frontmatter title and alias key the same note as the stem does.
for name in ["Rain Gate", "The Rain Gate", "Gate of Rain", "hinge"] {
let hit = whole.retrieve(&query(&[name])).await.unwrap();
assert_eq!(
hit[0].reference,
EvidenceRef::new("Public/Places/Rain Gate.md"),
"{name} did not resolve to the note"
);
}
// A heading link seeks its section rather than the head of the body.
let heading = whole.retrieve(&query(&["Rain Gate#Tolls"])).await.unwrap();
assert!(heading[0].excerpt.contains("toll of one"));
assert!(!heading[0].excerpt.contains("Water enters here"));
// Two `index.md` notes; the shallower path wins.
let ambiguous = whole.retrieve(&query(&["index"])).await.unwrap();
assert_eq!(
ambiguous[0].reference,
EvidenceRef::new("Public/index.md"),
"an ambiguous stem resolved to the deeper path"
);
for receipt in whole
.retrieve(&query(&["Low Sere", "index"]))
.await
.unwrap()
{
assert!(receipt.excerpt.chars().count() <= MAX_EXCERPT_CHARS);
assert!(receipt.reference.text().trim() == receipt.reference.text());
assert!(!receipt.reference.text().is_empty());
}
assert!(
whole
.retrieve(&query(&["Low Sere", "Provenance", "index"]))
.await
.unwrap()
.len()
<= MAX_VAULT_RECEIPTS
);
// The spoiler tier is a directory, so it is a scope.
let public = VaultEvidenceSource::open(directory.path(), "Public").unwrap();
assert!(
public
.retrieve(&query(&["Provenance"]))
.await
.unwrap()
.is_empty()
);
assert!(
whole
.retrieve(&query(&["Provenance"]))
.await
.unwrap()
.iter()
.any(|receipt| receipt.reference
== EvidenceRef::new("Spoilers/Dungeons/Provenance.md")),
"the unscoped source should still read the spoiler subtree"
);
}
/// Spec test 15. The scope is a corner of a configured vault, never a read
/// primitive over the filesystem.
#[test]
fn a_vault_scope_cannot_escape_its_root() {
let directory = fixture();
let root = directory.path();
for scope in ["..", "../..", "Public/../..", "Public/../../etc"] {
assert!(
VaultEvidenceSource::open(root, scope).is_err(),
"{scope} was admitted"
);
}
let absolute = root.join("Public");
assert!(VaultEvidenceSource::open(root, &absolute.display().to_string()).is_err());
assert!(VaultEvidenceSource::open(root, "Public").is_ok());
}
}