Merge commit '492c5e61e1'
This commit is contained in:
commit
a8354b4c23
12 changed files with 3269 additions and 27 deletions
|
|
@ -39,11 +39,13 @@ use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};
|
|||
use cultnet_rs::{PROJECTION_DOCUMENT, Selection};
|
||||
use eureka_state::hold;
|
||||
use huginn_mind::eureka_pipeline::{
|
||||
Line, PipelineDocument, PipelineRef, Short, Slug, pipeline_key,
|
||||
Label, Line, MemoryOrigin, OrgRepo, PipelineDocument, PipelineFollowUp, PipelineKind, PipelineRef, Short, Slug,
|
||||
pipeline_key,
|
||||
};
|
||||
use huginn_mind::{
|
||||
BATCH_MAX, ChatQuery, ChatWindowQuery, Faculty, HuginnMindRequest, HuginnMindResponse, MindRefusal, PipelineAdmissionBatch, PipelineAdmissionOutcome,
|
||||
PipelinePageItems, PipelineProvenance, PipelineSelectionPage, SemanticQuery, SourceQuery,
|
||||
ACTIVITY_REPOS_MAX, BATCH_MAX, ChatQuery, ChatWindowQuery, Faculty, HuginnMindRequest, HuginnMindResponse,
|
||||
MindRefusal, PipelineAdmissionBatch, PipelineAdmissionOutcome, PipelineFacts, PipelinePageItems,
|
||||
PipelineProvenance, PipelineSelectionPage, SemanticQuery, SourceQuery,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
|
|
@ -68,7 +70,7 @@ After Committed or AlreadyAdmitted the batch is read back and compared with what
|
|||
const IMPORT_HELP: &str = "Reads the giver's mind (it sends Query alone) and admits its receipts for the campaign into this one, one batch per source receipt, in order, each naming the giver's receipt in imported_from. It refuses unless the campaign is moved to this mind (exit 1), and when this mind already holds records under the campaign that it did not import from the giver, except follow-ups and ideas it admitted after the import began, which stay in place and are named (exit 1). A rerun after any stop resumes at the first batch this mind does not hold; it prints `imported <campaign> from <instance>: ... verified` only after comparing every document it holds with the giver's (exit 5 if one differs). Until it prints imported, this mind writes nothing else under the campaign; a write that collides stops the import with the refusal (exit 1). Exit 3 Unavailable (rerun), 4 the history cannot be replayed whole (a receipt over 64 documents, too many external referents, a receipt held in part). Only a Self run can run it: a Persona's traffic to a peer's huginn port is fenced.";
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "huginn", about = "Huginn's mind: whoami, view, query, recipes, persona, admit, import, recall, schema", arg_required_else_help = true)]
|
||||
#[command(name = "huginn", about = "Huginn's mind: whoami, view, query, recipes, persona, activity, escalate, admit, import, recall, schema", arg_required_else_help = true)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
|
|
@ -221,6 +223,50 @@ enum Command {
|
|||
#[command(subcommand)]
|
||||
command: Box<PersonaCommand>,
|
||||
},
|
||||
/// Recent forge activity and open PRs in stewarded (or named) repositories.
|
||||
Activity {
|
||||
/// Repository as `Org/Repo`. Repeat for several; defaults to in-force stewardships for this instance.
|
||||
#[arg(long = "repo")]
|
||||
repos: Vec<String>,
|
||||
/// Only events after this forge feed cursor (from a previous `head`).
|
||||
#[arg(long)]
|
||||
after: Option<u64>,
|
||||
},
|
||||
/// Escalate a follow-up brief to Self (usable over the persona door).
|
||||
Escalate {
|
||||
/// The campaign's slug; the brief's source is `<campaign>:campaign:self`.
|
||||
#[arg(long)]
|
||||
campaign: String,
|
||||
/// The repository as `Org/Repo`.
|
||||
#[arg(long)]
|
||||
repo: String,
|
||||
/// What needs attention in the next Self run.
|
||||
#[arg(long)]
|
||||
item: String,
|
||||
/// Why this can wait for a Self run rather than blocking now.
|
||||
#[arg(long)]
|
||||
why_it_can_wait: String,
|
||||
/// The follow-up's label; generated from the timestamp if omitted.
|
||||
#[arg(long)]
|
||||
label: Option<String>,
|
||||
/// The room alias or id where the need arose (conflicts with --dm).
|
||||
#[arg(long, conflicts_with = "dm")]
|
||||
room: Option<String>,
|
||||
/// The direct-message room id where the need arose (conflicts with --room).
|
||||
#[arg(long, conflicts_with = "room")]
|
||||
dm: Option<String>,
|
||||
/// Sender(s) heard from in --room or --dm. Repeat for several.
|
||||
#[arg(long = "heard-from")]
|
||||
heard_from: Vec<String>,
|
||||
#[arg(long, value_parser = faculty, default_value = "Member")]
|
||||
faculty: Faculty,
|
||||
/// The escalating agent's name (the daemon pins `mind-persona` on the receipt).
|
||||
#[arg(long, default_value = "mind-persona")]
|
||||
agent: String,
|
||||
/// The escalating session; else HUGINN_SESSION.
|
||||
#[arg(long)]
|
||||
session: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
|
|
@ -375,6 +421,33 @@ fn run(settings: &Settings, command: Command) -> Result<u8, Trouble> {
|
|||
import::run(settings, import::Flags { campaign, from, from_endpoint, faculty, agent, session })
|
||||
}
|
||||
Command::Persona { command } => persona::run(settings, *command),
|
||||
Command::Activity { repos, after } => activity(settings, repos, after),
|
||||
Command::Escalate {
|
||||
campaign,
|
||||
repo,
|
||||
item,
|
||||
why_it_can_wait,
|
||||
label,
|
||||
room,
|
||||
dm,
|
||||
heard_from,
|
||||
faculty,
|
||||
agent,
|
||||
session,
|
||||
} => escalate(
|
||||
settings,
|
||||
campaign,
|
||||
repo,
|
||||
item,
|
||||
why_it_can_wait,
|
||||
label,
|
||||
room,
|
||||
dm,
|
||||
heard_from,
|
||||
faculty,
|
||||
agent,
|
||||
session,
|
||||
),
|
||||
Command::Recall { command: RecallCommand::Dispatch { top_k, max_anchors, budget, deadline_ms } } => Ok(recall::dispatch(
|
||||
settings,
|
||||
&recall::Flags { top_k: top_k as usize, max_anchors: max_anchors as usize, budget: budget as usize, deadline_ms },
|
||||
|
|
@ -652,17 +725,22 @@ fn admit(
|
|||
let request = |instance: &Slug| {
|
||||
HuginnMindRequest::Admit(PipelineAdmissionBatch { instance: instance.clone(), provenance, documents })
|
||||
};
|
||||
match settings.ask(request)? {
|
||||
let response = settings.ask(request)?;
|
||||
handle_admit_outcome(settings, response, &sent)
|
||||
}
|
||||
|
||||
fn handle_admit_outcome(settings: &Settings, response: HuginnMindResponse, sent: &[PipelineDocument]) -> Result<u8, Trouble> {
|
||||
match response {
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { receipt_id, committed_at, writes }) => {
|
||||
say(format_args!("Committed {receipt_id} at {committed_at}"));
|
||||
for write in &writes {
|
||||
say(format_args!("wrote {}", write.id.0));
|
||||
}
|
||||
read_back(settings, &sent)
|
||||
read_back(settings, sent)
|
||||
}
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::AlreadyAdmitted { receipt_id }) => {
|
||||
say(format_args!("AlreadyAdmitted {receipt_id}"));
|
||||
read_back(settings, &sent)
|
||||
read_back(settings, sent)
|
||||
}
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(refusal)) | HuginnMindResponse::Refused(refusal) => {
|
||||
Ok(refused(&refusal))
|
||||
|
|
@ -678,6 +756,163 @@ fn admit(
|
|||
}
|
||||
}
|
||||
|
||||
fn stewarded_repos(settings: &Settings) -> Result<Vec<OrgRepo>, Trouble> {
|
||||
let owner = settings.client()?.instance().0.clone();
|
||||
let mut selection = door::selection_value(&serde_json::json!({
|
||||
"schemas": [PipelineKind::Stewardship.type_id()],
|
||||
"fields": [{ "index": "in_force", "op": "any_of", "values": ["true"] }],
|
||||
"limit": DEFAULT_LIMIT,
|
||||
}))?;
|
||||
let mut repos: Vec<OrgRepo> = Vec::new();
|
||||
loop {
|
||||
let page = match settings.ask(|instance| HuginnMindRequest::Query {
|
||||
instance: instance.clone(),
|
||||
selection: selection.clone(),
|
||||
semantic: None,
|
||||
})? {
|
||||
HuginnMindResponse::Query(page) => page,
|
||||
HuginnMindResponse::Refused(refusal) => {
|
||||
return Err(Trouble::Internal(format!("stewardship query refused: {refusal:?}")));
|
||||
}
|
||||
other => return Err(unexpected(&other)),
|
||||
};
|
||||
let PipelinePageItems::Headers(headers) = page.items else {
|
||||
return Err(Trouble::Internal("stewardship query answered documents, not headers".into()));
|
||||
};
|
||||
for header in headers {
|
||||
if let PipelineFacts::Stewardship { instance, repo, .. } = header.facts
|
||||
&& instance.0 == owner
|
||||
&& !repos.iter().any(|held| held.0.eq_ignore_ascii_case(&repo.0))
|
||||
{
|
||||
repos.push(repo);
|
||||
if repos.len() >= ACTIVITY_REPOS_MAX {
|
||||
return Ok(repos);
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(next) = page.next else {
|
||||
return Ok(repos);
|
||||
};
|
||||
selection.cursor = Some(next);
|
||||
}
|
||||
}
|
||||
|
||||
fn activity(settings: &Settings, repos: Vec<String>, after: Option<u64>) -> Result<u8, Trouble> {
|
||||
let repos = if repos.is_empty() {
|
||||
stewarded_repos(settings)?
|
||||
} else {
|
||||
if repos.len() > ACTIVITY_REPOS_MAX {
|
||||
return Err(Trouble::invalid(format!(
|
||||
"at most {ACTIVITY_REPOS_MAX} repositories may be queried at once"
|
||||
)));
|
||||
}
|
||||
let mut parsed = Vec::with_capacity(repos.len());
|
||||
for raw in repos {
|
||||
let repo = OrgRepo(raw);
|
||||
repo.validate_org_repo()
|
||||
.map_err(|refusal| Trouble::invalid(format!("--repo is not Org/Repo: {refusal:?}")))?;
|
||||
if !parsed.iter().any(|held: &OrgRepo| held.0.eq_ignore_ascii_case(&repo.0)) {
|
||||
parsed.push(repo);
|
||||
}
|
||||
}
|
||||
parsed
|
||||
};
|
||||
match settings.ask(|instance| HuginnMindRequest::StewardedActivity {
|
||||
instance: instance.clone(),
|
||||
repos,
|
||||
after,
|
||||
})? {
|
||||
HuginnMindResponse::Activity(found) => {
|
||||
say(render::activity(&found));
|
||||
Ok(0)
|
||||
}
|
||||
HuginnMindResponse::Refused(MindRefusal::Unavailable { detail }) => Err(Trouble::Unavailable(detail)),
|
||||
HuginnMindResponse::Refused(refusal) => Ok(refused(&refusal)),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn escalate(
|
||||
settings: &Settings,
|
||||
campaign: String,
|
||||
repo: String,
|
||||
item: String,
|
||||
why_it_can_wait: String,
|
||||
label: Option<String>,
|
||||
room: Option<String>,
|
||||
dm: Option<String>,
|
||||
heard_from: Vec<String>,
|
||||
faculty: Faculty,
|
||||
agent: String,
|
||||
session: Option<String>,
|
||||
) -> Result<u8, Trouble> {
|
||||
let session = settings.session(session)?;
|
||||
if !heard_from.is_empty() && room.is_none() && dm.is_none() {
|
||||
return Err(Trouble::invalid("--heard-from requires --room or --dm"));
|
||||
}
|
||||
if item.trim().is_empty() {
|
||||
return Err(Trouble::invalid("--item must not be blank"));
|
||||
}
|
||||
if why_it_can_wait.trim().is_empty() {
|
||||
return Err(Trouble::invalid("--why-it-can-wait must not be blank"));
|
||||
}
|
||||
let campaign = Slug(campaign);
|
||||
let label = Label(label.unwrap_or_else(|| {
|
||||
format!("esc-{}-{}", chrono::Utc::now().timestamp_millis(), std::process::id())
|
||||
}));
|
||||
let repo = OrgRepo(repo);
|
||||
let item = Line(item);
|
||||
let why_it_can_wait = Line(why_it_can_wait);
|
||||
let origin = match (room, dm) {
|
||||
(Some(rooms), None) => Some(MemoryOrigin::Room {
|
||||
rooms: Short(rooms),
|
||||
heard_from: heard_from.into_iter().map(Short).collect(),
|
||||
}),
|
||||
(None, Some(room)) => Some(MemoryOrigin::Direct {
|
||||
room: Short(room),
|
||||
with: heard_from.into_iter().map(Short).collect(),
|
||||
}),
|
||||
(None, None) => None,
|
||||
(Some(_), Some(_)) => return Err(Trouble::invalid("--room and --dm cannot both be given")),
|
||||
};
|
||||
let expected = PipelineDocument::FollowUp(PipelineFollowUp {
|
||||
campaign: campaign.clone(),
|
||||
label: label.clone(),
|
||||
source: PipelineRef {
|
||||
kind: PipelineKind::Campaign,
|
||||
id: Short(format!("{}:campaign:self", campaign.0)),
|
||||
},
|
||||
repo: repo.clone(),
|
||||
locations: Vec::new(),
|
||||
item: item.clone(),
|
||||
why_it_can_wait: why_it_can_wait.clone(),
|
||||
owner: Short("self-run".into()),
|
||||
origin: origin.clone(),
|
||||
});
|
||||
expected
|
||||
.validate()
|
||||
.map_err(|refusal| Trouble::invalid(format!("invalid escalation field: {refusal:?}")))?;
|
||||
let provenance = PipelineProvenance {
|
||||
faculty,
|
||||
agent: Short(agent),
|
||||
session: Short(session),
|
||||
tool: Short(TOOL.to_string()),
|
||||
imported_from: None,
|
||||
};
|
||||
let response = settings.ask(|instance| HuginnMindRequest::EscalateGoal {
|
||||
instance: instance.clone(),
|
||||
provenance,
|
||||
campaign,
|
||||
label,
|
||||
repo,
|
||||
item,
|
||||
why_it_can_wait,
|
||||
origin,
|
||||
})?;
|
||||
handle_admit_outcome(settings, response, &[expected])
|
||||
}
|
||||
|
||||
/// The end-to-end check that the mind kept what was sent: one `keys` query,
|
||||
/// each stored document compared with the one sent. A difference is exit 5,
|
||||
/// not silence, whatever dropped it (an older leaf, a serde default, skew).
|
||||
|
|
|
|||
|
|
@ -3,7 +3,10 @@
|
|||
use std::fmt::Write;
|
||||
|
||||
use huginn_mind::eureka_pipeline::{PipelineResolution, ResolutionOutcome};
|
||||
use huginn_mind::{ChatHits, ChatWindow, SourceHits, IndexStatus, PersonaStatus, PipelineDocumentSummary, PipelineDocumentView, PipelineStatus, PipelineStatusSummary};
|
||||
use huginn_mind::{
|
||||
ChatHits, ChatWindow, IndexStatus, PersonaStatus, PipelineDocumentSummary, PipelineDocumentView, PipelineStatus,
|
||||
PipelineStatusSummary, RepoActivity, RepoChange, SourceHits,
|
||||
};
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
|
||||
|
|
@ -213,6 +216,47 @@ pub fn chat_window(found: &ChatWindow) -> String {
|
|||
out
|
||||
}
|
||||
|
||||
/// Forge activity as plain text: `head <cursor>`, then events, open PRs, and
|
||||
/// any `capped`, `unseen`, or `moved` repositories.
|
||||
pub fn activity(found: &RepoActivity) -> String {
|
||||
let mut out = format!("head {}\n", found.head);
|
||||
for event in &found.events {
|
||||
let what = match event.change {
|
||||
RepoChange::Pushed { commits } => format!("pushed {commits}"),
|
||||
RepoChange::Pr { number, action } => format!("pr #{number} {}", name_of(&action)),
|
||||
};
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"event {} {} {} {} {what}",
|
||||
event.id,
|
||||
crate::chat::shown(event.at),
|
||||
event.repo.0,
|
||||
event.actor.0
|
||||
);
|
||||
}
|
||||
for pr in &found.open_prs {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"open_pr {} #{} {} {}",
|
||||
pr.repo.0,
|
||||
pr.number,
|
||||
pr.author.0,
|
||||
crate::chat::shown(pr.updated_at)
|
||||
);
|
||||
}
|
||||
for repo in &found.capped {
|
||||
let _ = writeln!(out, "capped {}", repo.0);
|
||||
}
|
||||
for repo in &found.unseen {
|
||||
let _ = writeln!(out, "unseen {}", repo.0);
|
||||
}
|
||||
for moved in &found.moved {
|
||||
let _ = writeln!(out, "moved {} -> {}", moved.from.0, moved.to.0);
|
||||
}
|
||||
out.pop();
|
||||
out
|
||||
}
|
||||
|
||||
/// A fact as one token: a string, a number, a flag, a reference's id, or a
|
||||
/// list of those joined by commas. Anything deeper is not a header fact.
|
||||
fn scalar(value: &Value) -> Option<String> {
|
||||
|
|
|
|||
|
|
@ -4035,3 +4035,326 @@ fn persona_bond_custom_kind_and_expired_intention_semantics() {
|
|||
assert_eq!(seed_after.code, 0, "{} {}", seed_after.out, seed_after.err);
|
||||
assert!(seed_after.out.contains("deru [my_custom]"), "{}", seed_after.out);
|
||||
}
|
||||
|
||||
fn serve_with_persona(
|
||||
root: TempDir,
|
||||
mut daemon: huginn_daemon::Daemon<huginn_mind::OwnedRedbMessagePackBackingStore, Inert>,
|
||||
) -> (Server, SocketAddr) {
|
||||
let mut hub = huginn_daemon::serve::bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap();
|
||||
let mut persona_hub = huginn_daemon::serve::bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap();
|
||||
let addr = hub.local_addr().unwrap();
|
||||
let persona_addr = persona_hub.local_addr().unwrap();
|
||||
let stopping = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let loop_stopping = Arc::clone(&stopping);
|
||||
let registry = huginn_daemon::serve::schema_registry().unwrap();
|
||||
let thread = std::thread::spawn(move || {
|
||||
huginn_daemon::serve::run(
|
||||
&mut daemon,
|
||||
&mut hub,
|
||||
Some(&mut persona_hub),
|
||||
®istry,
|
||||
None,
|
||||
&loop_stopping,
|
||||
&huginn_daemon::ServeOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
(Server { addr, stopping, thread: Some(thread), ended: Arc::default(), _root: Some(root) }, persona_addr)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn huginn_escalate_and_activity_cli_round_trip() {
|
||||
use huginn_mind::eureka_pipeline::{MemoryOrigin, PipelineFollowUp};
|
||||
use huginn_mind::{
|
||||
ACTIVITY_REPOS_MAX, OpenPr, PipelineDocumentSummary, PipelineFacts, PipelineStatusSummary, PrAction, RepoActivity,
|
||||
RepoChange, RepoEvent, RepoMoved,
|
||||
};
|
||||
|
||||
// 1. Live daemon with Door::Persona: escalate commits FollowUp with server-pinned fields,
|
||||
// read_back verifies, while plain `admit` is still refused with NotThisDoor, and
|
||||
// `activity` exits 3 when the daemon has no forge.
|
||||
let (root, daemon) = mind(vec![vec![campaign(), stewardship()]]);
|
||||
let (_server, persona_addr) = serve_with_persona(root, daemon);
|
||||
|
||||
let escalated = at(
|
||||
persona_addr,
|
||||
&[
|
||||
"escalate",
|
||||
"--campaign",
|
||||
CAMPAIGN,
|
||||
"--repo",
|
||||
REPO,
|
||||
"--label",
|
||||
"esc-cli-1",
|
||||
"--item",
|
||||
"Investigate mutex contention.",
|
||||
"--why-it-can-wait",
|
||||
"Next Self run can inspect.",
|
||||
"--room",
|
||||
"#swarm:gamecult.org",
|
||||
"--heard-from",
|
||||
"@meta:gamecult.org",
|
||||
"--agent",
|
||||
"spoofed-agent",
|
||||
"--session",
|
||||
"p-session-1",
|
||||
],
|
||||
None,
|
||||
);
|
||||
assert_eq!(escalated.code, 0, "{} {}", escalated.out, escalated.err);
|
||||
assert!(escalated.out.contains("Committed mind-commit-"), "{}", escalated.out);
|
||||
assert!(escalated.out.contains(&format!("wrote {CAMPAIGN}:follow_up:esc-cli-1")), "{}", escalated.out);
|
||||
assert!(escalated.out.contains("read back 1 equal"), "{}", escalated.out);
|
||||
|
||||
let viewed = at(persona_addr, &["view", &format!("{CAMPAIGN}:follow_up:esc-cli-1")], None);
|
||||
assert_eq!(viewed.code, 0, "{} {}", viewed.out, viewed.err);
|
||||
assert!(viewed.out.contains("Member/mind-persona session p-session-1"), "{}", viewed.out);
|
||||
let raw = at(persona_addr, &["view", "--raw", &format!("{CAMPAIGN}:follow_up:esc-cli-1")], None);
|
||||
assert_eq!(raw.code, 0, "{} {}", raw.out, raw.err);
|
||||
let doc: PipelineDocument = serde_json::from_str(&raw.out).unwrap();
|
||||
let PipelineDocument::FollowUp(PipelineFollowUp { source, owner, locations, origin, .. }) = doc else {
|
||||
panic!("expected FollowUp");
|
||||
};
|
||||
assert_eq!(owner.0, "self-run");
|
||||
assert!(locations.is_empty());
|
||||
assert_eq!(source, PipelineRef { kind: PipelineKind::Campaign, id: Short(format!("{CAMPAIGN}:campaign:self")) });
|
||||
assert_eq!(
|
||||
origin,
|
||||
Some(MemoryOrigin::Room {
|
||||
rooms: Short("#swarm:gamecult.org".into()),
|
||||
heard_from: vec![Short("@meta:gamecult.org".into())],
|
||||
})
|
||||
);
|
||||
|
||||
// Omitting --label auto-generates a valid label and --dm sets Direct origin.
|
||||
let dm_escalated = at(
|
||||
persona_addr,
|
||||
&[
|
||||
"escalate",
|
||||
"--campaign",
|
||||
CAMPAIGN,
|
||||
"--repo",
|
||||
REPO,
|
||||
"--item",
|
||||
"Follow up from DM.",
|
||||
"--why-it-can-wait",
|
||||
"Next Self run.",
|
||||
"--dm",
|
||||
"!dm:gamecult.org",
|
||||
"--heard-from",
|
||||
"@meta:gamecult.org",
|
||||
"--session",
|
||||
"p-session-2",
|
||||
],
|
||||
None,
|
||||
);
|
||||
assert_eq!(dm_escalated.code, 0, "{} {}", dm_escalated.out, dm_escalated.err);
|
||||
assert!(dm_escalated.out.contains("read back 1 equal"), "{}", dm_escalated.out);
|
||||
|
||||
// Admit still refuses over Door::Persona.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let batch_file = write(&dir, "c.json", &json!([campaign_json()]));
|
||||
let admit_refused = at(persona_addr, &admit_args(&batch_file), None);
|
||||
assert_eq!(admit_refused.code, 1, "{} {}", admit_refused.out, admit_refused.err);
|
||||
assert!(admit_refused.out.contains("NotThisDoor"), "{}", admit_refused.out);
|
||||
|
||||
// escalate negative validations: no --json, no --heard-from without --room/--dm, no blank item.
|
||||
for bad in [
|
||||
vec!["escalate", "--json", "--campaign", CAMPAIGN, "--repo", REPO, "--item", "x", "--why-it-can-wait", "y", "--session", "s"],
|
||||
vec!["escalate", "--campaign", CAMPAIGN, "--repo", REPO, "--item", "x", "--why-it-can-wait", "y", "--heard-from", "@a", "--session", "s"],
|
||||
vec!["escalate", "--campaign", CAMPAIGN, "--repo", REPO, "--item", " ", "--why-it-can-wait", "y", "--session", "s"],
|
||||
] {
|
||||
let ran = at(persona_addr, &bad, None);
|
||||
assert_eq!(ran.code, 2, "{bad:?}: {} {}", ran.out, ran.err);
|
||||
}
|
||||
|
||||
// activity against a daemon without a forge exits 3 (Unavailable).
|
||||
let no_forge = at(persona_addr, &["activity"], None);
|
||||
assert_eq!(no_forge.code, 3, "{} {}", no_forge.out, no_forge.err);
|
||||
assert!(no_forge.err.starts_with("Unavailable: "), "{}", no_forge.err);
|
||||
|
||||
// 2. Scripted server verifying Stewardship autodiscovery, --repo/--after, and plain-text rendering.
|
||||
let seen = Arc::new(Mutex::new(Vec::<HuginnMindRequest>::new()));
|
||||
let sink = Arc::clone(&seen);
|
||||
let activity_payload = RepoActivity {
|
||||
head: 42,
|
||||
events: vec![RepoEvent {
|
||||
id: 41,
|
||||
at: 1_765_000_000_000,
|
||||
repo: OrgRepo("GameCult/Huginn".into()),
|
||||
actor: Short("alice".into()),
|
||||
change: RepoChange::Pr { number: 12, action: PrAction::Opened },
|
||||
}],
|
||||
capped: vec![OrgRepo("GameCult/Capped".into())],
|
||||
open_prs: vec![OpenPr {
|
||||
repo: OrgRepo("GameCult/Huginn".into()),
|
||||
number: 12,
|
||||
author: Short("alice".into()),
|
||||
updated_at: 1_765_000_000_000,
|
||||
}],
|
||||
unseen: vec![OrgRepo("GameCult/Secret".into())],
|
||||
moved: vec![RepoMoved {
|
||||
from: OrgRepo("GameCult/Old".into()),
|
||||
to: OrgRepo("GameCult/New".into()),
|
||||
}],
|
||||
};
|
||||
let payload_for_srv = activity_payload.clone();
|
||||
let spy = scripted(move |message| {
|
||||
let (_, request) = decode_request(message).unwrap();
|
||||
sink.lock().unwrap().push(request.clone());
|
||||
match request {
|
||||
HuginnMindRequest::Query { .. } => {
|
||||
let make_hdr = |id: &str, inst: &str, repo_name: &str| PipelineDocumentSummary {
|
||||
id: PipelineRef { kind: PipelineKind::Stewardship, id: Short(id.into()) },
|
||||
status: PipelineStatusSummary::InForce,
|
||||
admission: AdmissionFacts {
|
||||
receipt_id: "r1".into(),
|
||||
admitted_at: "2026-10-10T10:00:00Z".into(),
|
||||
provenance: provenance(),
|
||||
ordinal: 1,
|
||||
},
|
||||
facts: PipelineFacts::Stewardship {
|
||||
instance: slug(inst),
|
||||
repo: OrgRepo(repo_name.into()),
|
||||
sequence: 1,
|
||||
assigned_on: Date("2026-10-10".into()),
|
||||
note: "assigned".into(),
|
||||
names: vec![],
|
||||
},
|
||||
};
|
||||
let page = PipelineSelectionPage {
|
||||
matched: 2,
|
||||
as_of: 1,
|
||||
next: None,
|
||||
items: PipelinePageItems::Headers(vec![
|
||||
make_hdr(&format!("{INSTANCE}:stewardship:GameCult.Huginn.s1"), INSTANCE, "GameCult/Huginn"),
|
||||
make_hdr("other-mind:stewardship:GameCult.Foreign.s1", "other-mind", "GameCult/Foreign"),
|
||||
]),
|
||||
edges: None,
|
||||
scores: None,
|
||||
};
|
||||
answer("query", &HuginnMindResponse::Query(page))
|
||||
}
|
||||
HuginnMindRequest::StewardedActivity { .. } => {
|
||||
answer("stewarded_activity", &HuginnMindResponse::Activity(payload_for_srv.clone()))
|
||||
}
|
||||
other => panic!("unexpected request: {other:?}"),
|
||||
}
|
||||
});
|
||||
|
||||
let auto = at(spy.addr, &["activity"], None);
|
||||
assert_eq!(auto.code, 0, "{} {}", auto.out, auto.err);
|
||||
assert!(auto.out.contains("head 42"), "{}", auto.out);
|
||||
assert!(auto.out.contains("event 41 "), "{}", auto.out);
|
||||
assert!(auto.out.contains("GameCult/Huginn alice pr #12 Opened"), "{}", auto.out);
|
||||
assert!(auto.out.contains("open_pr GameCult/Huginn #12 alice "), "{}", auto.out);
|
||||
assert!(auto.out.contains("capped GameCult/Capped"), "{}", auto.out);
|
||||
assert!(auto.out.contains("unseen GameCult/Secret"), "{}", auto.out);
|
||||
assert!(auto.out.contains("moved GameCult/Old -> GameCult/New"), "{}", auto.out);
|
||||
|
||||
let explicit = at(spy.addr, &["activity", "--repo", "GameCult/Epiphany", "--after", "10"], None);
|
||||
assert_eq!(explicit.code, 0, "{} {}", explicit.out, explicit.err);
|
||||
|
||||
let recorded = seen.lock().unwrap();
|
||||
assert_eq!(recorded.len(), 3, "{recorded:?}");
|
||||
assert!(matches!(&recorded[0], HuginnMindRequest::Query { .. }));
|
||||
assert_eq!(
|
||||
recorded[1],
|
||||
HuginnMindRequest::StewardedActivity {
|
||||
instance: slug(INSTANCE),
|
||||
repos: vec![OrgRepo("GameCult/Huginn".into())],
|
||||
after: None,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
recorded[2],
|
||||
HuginnMindRequest::StewardedActivity {
|
||||
instance: slug(INSTANCE),
|
||||
repos: vec![OrgRepo("GameCult/Epiphany".into())],
|
||||
after: Some(10),
|
||||
}
|
||||
);
|
||||
|
||||
// Negative activity flags: no --json, invalid --repo.
|
||||
for bad in [vec!["activity", "--json"], vec!["activity", "--repo", "not-org-repo"]] {
|
||||
let ran = at(spy.addr, &bad, None);
|
||||
assert_eq!(ran.code, 2, "{bad:?}: {} {}", ran.out, ran.err);
|
||||
}
|
||||
|
||||
// Boundary checks on ACTIVITY_REPOS_MAX (64): autodiscovery collects all up to the cap
|
||||
// instead of stopping at 1, explicit --repo allows exact cap (64), and rejects cap + 1 (65).
|
||||
let seen_cap = Arc::new(Mutex::new(Vec::<HuginnMindRequest>::new()));
|
||||
let sink_cap = Arc::clone(&seen_cap);
|
||||
let empty_activity = RepoActivity {
|
||||
head: 1,
|
||||
events: vec![],
|
||||
capped: vec![],
|
||||
open_prs: vec![],
|
||||
unseen: vec![],
|
||||
moved: vec![],
|
||||
};
|
||||
let cap_srv = scripted(move |message| {
|
||||
let (_, request) = decode_request(message).unwrap();
|
||||
sink_cap.lock().unwrap().push(request.clone());
|
||||
match request {
|
||||
HuginnMindRequest::Query { .. } => {
|
||||
let items: Vec<PipelineDocumentSummary> = (0..=ACTIVITY_REPOS_MAX)
|
||||
.map(|idx| PipelineDocumentSummary {
|
||||
id: PipelineRef { kind: PipelineKind::Stewardship, id: Short(format!("{INSTANCE}:stewardship:r{idx}")) },
|
||||
status: PipelineStatusSummary::InForce,
|
||||
admission: AdmissionFacts {
|
||||
receipt_id: "r1".into(),
|
||||
admitted_at: "2026-10-10T10:00:00Z".into(),
|
||||
provenance: provenance(),
|
||||
ordinal: idx as u64 + 1,
|
||||
},
|
||||
facts: PipelineFacts::Stewardship {
|
||||
instance: slug(INSTANCE),
|
||||
repo: OrgRepo(format!("GameCult/R{idx:02}")),
|
||||
sequence: 1,
|
||||
assigned_on: Date("2026-10-10".into()),
|
||||
note: "assigned".into(),
|
||||
names: vec![],
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
let page = PipelineSelectionPage {
|
||||
matched: items.len() as u32,
|
||||
as_of: 1,
|
||||
next: None,
|
||||
items: PipelinePageItems::Headers(items),
|
||||
edges: None,
|
||||
scores: None,
|
||||
};
|
||||
answer("query", &HuginnMindResponse::Query(page))
|
||||
}
|
||||
HuginnMindRequest::StewardedActivity { .. } => {
|
||||
answer("stewarded_activity", &HuginnMindResponse::Activity(empty_activity.clone()))
|
||||
}
|
||||
other => panic!("unexpected request: {other:?}"),
|
||||
}
|
||||
});
|
||||
let capped_auto = at(cap_srv.addr, &["activity"], None);
|
||||
assert_eq!(capped_auto.code, 0, "{} {}", capped_auto.out, capped_auto.err);
|
||||
|
||||
let exact_args: Vec<String> = std::iter::once("activity".to_string())
|
||||
.chain((0..ACTIVITY_REPOS_MAX).flat_map(|idx| ["--repo".to_string(), format!("GameCult/R{idx:02}")]))
|
||||
.collect();
|
||||
let exact_refs: Vec<&str> = exact_args.iter().map(String::as_str).collect();
|
||||
let exact_cap = at(cap_srv.addr, &exact_refs, None);
|
||||
assert_eq!(exact_cap.code, 0, "{} {}", exact_cap.out, exact_cap.err);
|
||||
|
||||
let over_args: Vec<String> = std::iter::once("activity".to_string())
|
||||
.chain((0..=ACTIVITY_REPOS_MAX).flat_map(|idx| ["--repo".to_string(), format!("GameCult/R{idx:02}")]))
|
||||
.collect();
|
||||
let over_refs: Vec<&str> = over_args.iter().map(String::as_str).collect();
|
||||
let over_cap = at(cap_srv.addr, &over_refs, None);
|
||||
assert_eq!(over_cap.code, 2, "{} {}", over_cap.out, over_cap.err);
|
||||
|
||||
let cap_recorded = seen_cap.lock().unwrap();
|
||||
assert_eq!(cap_recorded.len(), 3, "over-cap must not send");
|
||||
let HuginnMindRequest::StewardedActivity { repos: auto_repos, .. } = &cap_recorded[1] else {
|
||||
panic!("expected StewardedActivity");
|
||||
};
|
||||
assert_eq!(auto_repos.len(), ACTIVITY_REPOS_MAX);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,9 +6,12 @@ use chrono::{DateTime, Utc};
|
|||
use cultnet_rs::Selection;
|
||||
use crate::sources::forge::HttpForge;
|
||||
use huginn_mind::desk_wire::{DeskRequest, DeskResponse};
|
||||
use huginn_mind::eureka_pipeline::{AccountId, PipelineRef, Short, Slug};
|
||||
use huginn_mind::eureka_pipeline::{AccountId, PipelineDocument, PipelineFollowUp, PipelineKind, PipelineRef, Short, Slug};
|
||||
use huginn_mind::wire::{ACTIVITY_REPOS_MAX, HuginnMindRequest, HuginnMindResponse, IndexStatus};
|
||||
use huginn_mind::{ChatHits, ChatQuery, ChatWindow, ChatWindowQuery, Members, Mind, MindRefusal, MindStore, PipelineAdmissionOutcome, SemanticQuery, SourceHits, SourceQuery};
|
||||
use huginn_mind::{
|
||||
ChatHits, ChatQuery, ChatWindow, ChatWindowQuery, Members, Mind, MindRefusal, MindStore, PipelineAdmissionBatch,
|
||||
PipelineAdmissionOutcome, SemanticQuery, SourceHits, SourceQuery,
|
||||
};
|
||||
|
||||
/// Where the index attaches. Called after a batch commits, with the refs the
|
||||
/// batch landed, derived writes included; the sink may read each through
|
||||
|
|
@ -213,15 +216,43 @@ impl<S: MindStore, I: IndexSink<S>> Daemon<S, I> {
|
|||
}
|
||||
let answer = match request {
|
||||
HuginnMindRequest::Whoami => HuginnMindResponse::Whoami(self.mind.status(self.index.status())),
|
||||
HuginnMindRequest::Admit(batch) => {
|
||||
let outcome = self.mind.admit(batch, now);
|
||||
if let PipelineAdmissionOutcome::Committed { writes, .. } = &outcome
|
||||
&& let Err(error) = self.index.committed(&self.mind, writes)
|
||||
{
|
||||
let refs = writes.iter().map(|write| write.id.0.clone()).collect::<Vec<_>>().join(", ");
|
||||
eprintln!("huginn: the index refused the landed writes [{refs}]: {error:#}");
|
||||
HuginnMindRequest::Admit(batch) => self.admit_and_index(batch, now),
|
||||
HuginnMindRequest::EscalateGoal {
|
||||
instance,
|
||||
mut provenance,
|
||||
campaign,
|
||||
label,
|
||||
repo,
|
||||
item,
|
||||
why_it_can_wait,
|
||||
origin,
|
||||
} => {
|
||||
if provenance.imported_from.is_some() {
|
||||
return Handled::Answered(HuginnMindResponse::Refused(MindRefusal::SelectionInvalid {
|
||||
field: "provenance.imported_from".into(),
|
||||
value: None,
|
||||
message: "an escalated goal cannot carry imported_from".into(),
|
||||
}));
|
||||
}
|
||||
HuginnMindResponse::Admit(outcome)
|
||||
provenance.agent = Short("mind-persona".into());
|
||||
let follow_up = PipelineDocument::FollowUp(PipelineFollowUp {
|
||||
source: PipelineRef {
|
||||
kind: PipelineKind::Campaign,
|
||||
id: Short(format!("{}:campaign:self", campaign.0)),
|
||||
},
|
||||
campaign,
|
||||
label,
|
||||
repo,
|
||||
locations: Vec::new(),
|
||||
item,
|
||||
why_it_can_wait,
|
||||
owner: Short("self-run".into()),
|
||||
origin,
|
||||
});
|
||||
self.admit_and_index(
|
||||
PipelineAdmissionBatch { instance, provenance, documents: vec![follow_up] },
|
||||
now,
|
||||
)
|
||||
}
|
||||
HuginnMindRequest::View { id, .. } => match self.mind.view(&id) {
|
||||
Ok(view) => HuginnMindResponse::View(view.map(Box::new)),
|
||||
|
|
@ -308,6 +339,17 @@ impl<S: MindStore, I: IndexSink<S>> Daemon<S, I> {
|
|||
}
|
||||
}
|
||||
|
||||
fn admit_and_index(&mut self, batch: PipelineAdmissionBatch, now: DateTime<Utc>) -> HuginnMindResponse {
|
||||
let outcome = self.mind.admit(batch, now);
|
||||
if let PipelineAdmissionOutcome::Committed { writes, .. } = &outcome
|
||||
&& let Err(error) = self.index.committed(&self.mind, writes)
|
||||
{
|
||||
let refs = writes.iter().map(|write| write.id.0.clone()).collect::<Vec<_>>().join(", ");
|
||||
eprintln!("huginn: the index refused the landed writes [{refs}]: {error:#}");
|
||||
}
|
||||
HuginnMindResponse::Admit(outcome)
|
||||
}
|
||||
|
||||
/// A semantic query starts only if the mind accepts it, and the mind
|
||||
/// decides its members before the index is asked anything. A selection
|
||||
/// with no members is answered at once: nothing is embedded and the index
|
||||
|
|
@ -1102,6 +1144,119 @@ pub(crate) mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daemon_escalate_goal_enforces_persona_door_bounds() {
|
||||
use huginn_mind::eureka_pipeline::{Label, MemoryOrigin, PipelineFollowUp};
|
||||
use huginn_mind::ImportSource;
|
||||
|
||||
let indexed = Arc::new(Mutex::new(Vec::<PipelineRef>::new()));
|
||||
struct RecordingIndex(Arc<Mutex<Vec<PipelineRef>>>);
|
||||
impl<S: MindStore> IndexSink<S> for RecordingIndex {
|
||||
fn committed(&mut self, _mind: &Mind<S>, writes: &[PipelineRef]) -> anyhow::Result<()> {
|
||||
self.0.lock().unwrap().extend(writes.iter().cloned());
|
||||
Ok(())
|
||||
}
|
||||
fn status(&self) -> IndexStatus { IndexStatus::Current }
|
||||
fn search(&mut self, _t: &str, _k: u32, _a: Vec<String>) -> Result<SearchTicket, String> { Err("unused".into()) }
|
||||
fn search_sources(&mut self, _q: &SourceQuery) -> Result<SearchTicket, String> { Err("unused".into()) }
|
||||
fn search_chat(&mut self, _q: &ChatQuery) -> Result<SearchTicket, String> { Err("unused".into()) }
|
||||
fn chat_window(&mut self, _q: &ChatWindowQuery) -> Result<SearchTicket, String> { Err("unused".into()) }
|
||||
fn sources_searched(&mut self) -> Vec<(SearchTicket, Found)> { Vec::new() }
|
||||
fn search_deadline(&self) -> std::time::Duration { std::time::Duration::ZERO }
|
||||
fn searched(&mut self) -> Vec<(SearchTicket, Result<Hits, String>)> { Vec::new() }
|
||||
fn abandon(&mut self, _t: SearchTicket) {}
|
||||
}
|
||||
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let mind = Mind::open(root.path(), &slug(INSTANCE)).unwrap();
|
||||
let mut daemon = Daemon::new(mind, RecordingIndex(Arc::clone(&indexed)));
|
||||
let seed = daemon.handle_at(Door::Full, HuginnMindRequest::Admit(batch(INSTANCE, campaign_seed())), now()).answered();
|
||||
assert!(matches!(seed, HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { .. })), "{seed:?}");
|
||||
indexed.lock().unwrap().clear();
|
||||
|
||||
let admit = HuginnMindRequest::Admit(batch(INSTANCE, vec![identity(INSTANCE)]));
|
||||
assert_eq!(daemon.handle_at(Door::Persona, admit, now()).answered(), HuginnMindResponse::Refused(MindRefusal::NotThisDoor));
|
||||
|
||||
let mut caller_prov = provenance();
|
||||
caller_prov.agent = Short("forged-agent".into());
|
||||
let escalate = HuginnMindRequest::EscalateGoal {
|
||||
instance: slug(INSTANCE),
|
||||
provenance: caller_prov,
|
||||
campaign: slug(CAMPAIGN),
|
||||
label: Label("esc-door-1".into()),
|
||||
repo: OrgRepo(REPO.into()),
|
||||
item: Line("Check lock stall.".into()),
|
||||
why_it_can_wait: Line("Next Self run.".into()),
|
||||
origin: Some(MemoryOrigin::Direct { room: Short("!dm:gamecult.org".into()), with: vec![Short("@meta:gamecult.org".into())] }),
|
||||
};
|
||||
let HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { writes, .. }) =
|
||||
daemon.handle_at(Door::Persona, escalate, now()).answered()
|
||||
else {
|
||||
panic!("EscalateGoal must commit through Door::Persona");
|
||||
};
|
||||
assert_eq!(writes.len(), 1);
|
||||
assert_eq!(indexed.lock().unwrap().as_slice(), writes.as_slice());
|
||||
|
||||
let HuginnMindResponse::View(Some(view)) =
|
||||
daemon.handle_at(Door::Persona, HuginnMindRequest::View { instance: slug(INSTANCE), id: writes[0].clone() }, now()).answered()
|
||||
else {
|
||||
panic!("committed FollowUp must be viewable");
|
||||
};
|
||||
assert_eq!(view.admission.provenance.agent.0, "mind-persona");
|
||||
assert!(view.admission.provenance.imported_from.is_none());
|
||||
let PipelineDocument::FollowUp(PipelineFollowUp { source, owner, locations, origin, .. }) = view.document else {
|
||||
panic!("expected FollowUp");
|
||||
};
|
||||
assert_eq!(owner.0, "self-run");
|
||||
assert!(locations.is_empty());
|
||||
assert_eq!(source, PipelineRef { kind: PipelineKind::Campaign, id: Short(format!("{CAMPAIGN}:campaign:self")) });
|
||||
assert_eq!(origin, Some(MemoryOrigin::Direct { room: Short("!dm:gamecult.org".into()), with: vec![Short("@meta:gamecult.org".into())] }));
|
||||
|
||||
// Foreign instance refused before admission.
|
||||
let foreign = HuginnMindRequest::EscalateGoal {
|
||||
instance: slug(OTHER),
|
||||
provenance: provenance(),
|
||||
campaign: slug(CAMPAIGN),
|
||||
label: Label("esc-foreign".into()),
|
||||
repo: OrgRepo(REPO.into()),
|
||||
item: Line("Foreign.".into()),
|
||||
why_it_can_wait: Line("Wait.".into()),
|
||||
origin: None,
|
||||
};
|
||||
assert_eq!(
|
||||
daemon.handle_at(Door::Persona, foreign, now()).answered(),
|
||||
HuginnMindResponse::Refused(MindRefusal::ForeignInstance { declared: OTHER.into(), mind: INSTANCE.into() })
|
||||
);
|
||||
|
||||
// imported_from refused.
|
||||
let mut with_import = provenance();
|
||||
with_import.imported_from = Some(ImportSource {
|
||||
instance: slug(OTHER),
|
||||
receipt_id: Short("mind-commit-1".into()),
|
||||
ordinal: 1,
|
||||
committed_at: Short("2026-10-10T10:00:00Z".into()),
|
||||
faculty: Faculty::Hands,
|
||||
agent: Short("importer".into()),
|
||||
session: Short("s1".into()),
|
||||
tool: Short("huginn".into()),
|
||||
external: vec![],
|
||||
});
|
||||
let imported = HuginnMindRequest::EscalateGoal {
|
||||
instance: slug(INSTANCE),
|
||||
provenance: with_import,
|
||||
campaign: slug(CAMPAIGN),
|
||||
label: Label("esc-import".into()),
|
||||
repo: OrgRepo(REPO.into()),
|
||||
item: Line("Imported.".into()),
|
||||
why_it_can_wait: Line("Wait.".into()),
|
||||
origin: None,
|
||||
};
|
||||
assert!(matches!(
|
||||
daemon.handle_at(Door::Persona, imported, now()).answered(),
|
||||
HuginnMindResponse::Refused(MindRefusal::SelectionInvalid { ref field, .. }) if field == "provenance.imported_from"
|
||||
));
|
||||
}
|
||||
|
||||
/// Every read the persona door answers reaches the mind there: none of the
|
||||
/// source, chat, activity and roots reads is refused as `NotThisDoor`.
|
||||
/// What the mind then says (a search, or `Unavailable` with no index or
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use cultnet_rs::{CultMeshCdnArtifactManifest, Selection};
|
||||
use eureka_pipeline::{Line, OrgRepo, PIPELINE_SCHEMA_EPOCH, PipelineKind, PipelineRef, Short, Slug};
|
||||
use eureka_pipeline::{Label, Line, MemoryOrigin, OrgRepo, PIPELINE_SCHEMA_EPOCH, PipelineKind, PipelineRef, Short, Slug};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
|
@ -108,6 +108,17 @@ pub enum HuginnMindRequest {
|
|||
/// Every root the mind holds a document under, with its newest admission and a campaign's repos in force: the mind's own
|
||||
/// records, one pass at the head.
|
||||
RootsTouched { instance: Slug },
|
||||
/// Escalates a follow-up brief from a Persona session to Self on the persona door.
|
||||
EscalateGoal {
|
||||
instance: Slug,
|
||||
provenance: PipelineProvenance,
|
||||
campaign: Slug,
|
||||
label: Label,
|
||||
repo: OrgRepo,
|
||||
item: Line,
|
||||
why_it_can_wait: Line,
|
||||
origin: Option<MemoryOrigin>,
|
||||
},
|
||||
}
|
||||
|
||||
/// The most repos one activity read names.
|
||||
|
|
@ -427,6 +438,7 @@ impl HuginnMindRequest {
|
|||
Self::ChatWindow { .. } => "chat_window",
|
||||
Self::StewardedActivity { .. } => "stewarded_activity",
|
||||
Self::RootsTouched { .. } => "roots_touched",
|
||||
Self::EscalateGoal { .. } => "escalate_goal",
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -447,7 +459,8 @@ impl HuginnMindRequest {
|
|||
| Self::SearchChat { .. }
|
||||
| Self::ChatWindow { .. }
|
||||
| Self::StewardedActivity { .. }
|
||||
| Self::RootsTouched { .. } => true,
|
||||
| Self::RootsTouched { .. }
|
||||
| Self::EscalateGoal { .. } => true,
|
||||
Self::Admit(_) => false,
|
||||
}
|
||||
}
|
||||
|
|
@ -465,7 +478,8 @@ impl HuginnMindRequest {
|
|||
| Self::SearchChat { instance, .. }
|
||||
| Self::ChatWindow { instance, .. }
|
||||
| Self::StewardedActivity { instance, .. }
|
||||
| Self::RootsTouched { instance } => Some(instance),
|
||||
| Self::RootsTouched { instance }
|
||||
| Self::EscalateGoal { instance, .. } => Some(instance),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -626,6 +640,19 @@ mod tests {
|
|||
},
|
||||
HuginnMindRequest::ChatWindow { instance: slug(INSTANCE), query: ChatWindowQuery { event_id: Short("$a".into()), before: 5, after: 0 } },
|
||||
HuginnMindRequest::RootsTouched { instance: slug(INSTANCE) },
|
||||
HuginnMindRequest::EscalateGoal {
|
||||
instance: slug(INSTANCE),
|
||||
provenance: provenance(Faculty::Member),
|
||||
campaign: slug(CAMPAIGN),
|
||||
label: Label("esc-1".into()),
|
||||
repo: OrgRepo("GameCult/Huginn".into()),
|
||||
item: Line("Investigate lock stall.".into()),
|
||||
why_it_can_wait: Line("Next Self run.".into()),
|
||||
origin: Some(MemoryOrigin::Room {
|
||||
rooms: Short("#swarm:gamecult.org".into()),
|
||||
heard_from: vec![Short("@alice:gamecult.org".into())],
|
||||
}),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
|
|
@ -713,13 +740,42 @@ mod tests {
|
|||
#[test]
|
||||
fn the_wire_vocabulary_is_the_minds_methods_and_status_is_derived_from_the_response() {
|
||||
let names: Vec<&str> = requests().iter().map(|request| request.operation()).collect();
|
||||
assert_eq!(names, ["whoami", "admit", "view", "query", "persona_get", "persona_put", "search_sources", "search_sources", "search_chat", "chat_window", "roots_touched"]);
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"whoami",
|
||||
"admit",
|
||||
"view",
|
||||
"query",
|
||||
"persona_get",
|
||||
"persona_put",
|
||||
"search_sources",
|
||||
"search_sources",
|
||||
"search_chat",
|
||||
"chat_window",
|
||||
"roots_touched",
|
||||
"escalate_goal",
|
||||
]
|
||||
);
|
||||
for request in requests() {
|
||||
assert_eq!(request.reaches_persona_door(), !matches!(request, HuginnMindRequest::Admit(_)), "{request:?}");
|
||||
let declared = request.instance().is_none();
|
||||
assert_eq!(declared, matches!(request, HuginnMindRequest::Whoami), "{request:?}");
|
||||
let bytes = rmp_serde::to_vec_named(&request).unwrap();
|
||||
assert_eq!(rmp_serde::from_slice::<HuginnMindRequest>(&bytes).unwrap(), request);
|
||||
}
|
||||
let escalate_no_origin = HuginnMindRequest::EscalateGoal {
|
||||
instance: slug(INSTANCE),
|
||||
provenance: provenance(Faculty::Member),
|
||||
campaign: slug(CAMPAIGN),
|
||||
label: Label("esc-2".into()),
|
||||
repo: OrgRepo("GameCult/Huginn".into()),
|
||||
item: Line("Follow up.".into()),
|
||||
why_it_can_wait: Line("Next run.".into()),
|
||||
origin: None,
|
||||
};
|
||||
let bytes = rmp_serde::to_vec_named(&escalate_no_origin).unwrap();
|
||||
assert_eq!(rmp_serde::from_slice::<HuginnMindRequest>(&bytes).unwrap(), escalate_no_origin);
|
||||
assert_eq!(
|
||||
requests()[3].instance(),
|
||||
Some(&slug(OTHER_INSTANCE)),
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ libc = "0.2"
|
|||
# duplicates, as safe calls (the library forbids unsafe code). Already in the
|
||||
# graph through tempfile; this adds its `net` feature, and `fs` for the attachment
|
||||
# saver's descriptor-relative writes (openat, linkat, unlinkat).
|
||||
rustix = { version = "1", default-features = false, features = ["std", "net", "fs"] }
|
||||
rustix = { version = "1", default-features = false, features = ["std", "net", "fs", "process"] }
|
||||
|
||||
# `syn`, `quote` and `proc-macro2` read the library's own source for
|
||||
# tests/public_surface.rs, which pins its public surface. All three are already
|
||||
|
|
@ -94,3 +94,7 @@ path = "src/bin/mind-persona.rs"
|
|||
[[bin]]
|
||||
name = "mind-heartbeat"
|
||||
path = "src/bin/mind-heartbeat.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "mind-chat"
|
||||
path = "src/bin/mind-chat.rs"
|
||||
|
|
|
|||
444
crates/mind-body/src/bin/mind-chat.rs
Normal file
444
crates/mind-body/src/bin/mind-chat.rs
Normal file
|
|
@ -0,0 +1,444 @@
|
|||
//! `mind-chat`: dual-mode Matrix mouth gate and sandbox/host client CLI.
|
||||
//!
|
||||
//! Host gate mode (outside `bwrap`):
|
||||
//! `mind-chat gate --instance <slug> --socket <path> --state-dir <dir> --minds <csv> --operators <csv> --own-sender <mxid> [--daily-cap <n>]`
|
||||
//!
|
||||
//! Client modes (sandboxed via `MIND_CHAT_SOCKET`, or direct host RUDP when unset):
|
||||
//! `mind-chat pending [--ack]`
|
||||
//! `mind-chat tail [--room <room>]`
|
||||
//! `mind-chat say --room <room> (--text <text> | --resend <request_id>)`
|
||||
//! `mind-chat ack --through <seq>`
|
||||
//! `mind-chat mark-read --room <room_id> --event <event_id> --at <unix_ms>`
|
||||
//! `mind-chat open-direct --user <mxid> --text <text>`
|
||||
//! `mind-chat status`
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use chrono::Utc;
|
||||
use eureka_pipeline::Slug;
|
||||
use mind_body::chat_gate::{Answer, Config, Engine, Request, call_socket, serve_gate};
|
||||
use mind_body::chat_rudp::{RudpChat, connection_id};
|
||||
|
||||
const CHAT_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
const USAGE: &str = "\
|
||||
usage:
|
||||
mind-chat gate --instance <slug> --socket <path> --state-dir <dir> --minds <csv> --operators <csv> --own-sender <mxid> [--daily-cap <n>]
|
||||
mind-chat pending [--ack]
|
||||
mind-chat tail [--room <room>]
|
||||
mind-chat say --room <room> (--text <text> | --resend <request_id>)
|
||||
mind-chat ack --through <seq>
|
||||
mind-chat mark-read --room <room_id> --event <event_id> --at <unix_ms>
|
||||
mind-chat open-direct --user <mxid> --text <text>
|
||||
mind-chat status";
|
||||
|
||||
#[cfg(unix)]
|
||||
fn restrict_umask() {
|
||||
// SAFETY: umask only sets this process's file-creation mask.
|
||||
unsafe {
|
||||
libc::umask(0o077);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn restrict_umask() {}
|
||||
|
||||
#[allow(clippy::disallowed_methods, reason = "the binary reads its own environment, and hands it to the library")]
|
||||
fn setting(name: &str) -> Option<String> {
|
||||
std::env::var(name).ok().filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
fn required_env(name: &str) -> Result<String> {
|
||||
setting(name).ok_or_else(|| anyhow!("{name} is not set"))
|
||||
}
|
||||
|
||||
fn split_csv(raw: &str) -> Vec<String> {
|
||||
raw.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
|
||||
}
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
u64::try_from(Utc::now().timestamp_millis()).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn open_rudp(instance: &str) -> Result<RudpChat> {
|
||||
let endpoint_raw = required_env("BIFROST_CHAT_ENDPOINT")?;
|
||||
let endpoint: SocketAddr = endpoint_raw
|
||||
.strip_prefix("rudp://")
|
||||
.and_then(|addr| addr.parse().ok())
|
||||
.ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT is not rudp://<ip>:<port>"))?;
|
||||
let key_path = required_env("BIFROST_CHAT_KEY_FILE")?;
|
||||
let key_text = std::fs::read_to_string(&key_path)
|
||||
.with_context(|| format!("failed to read BIFROST_CHAT_KEY_FILE {key_path}"))?;
|
||||
let conn_id = connection_id(&key_text);
|
||||
Ok(RudpChat::new(endpoint, conn_id, instance, CHAT_TIMEOUT).with_reply_link(true))
|
||||
}
|
||||
|
||||
fn parse_gate_args(args: &[String], get_env: &dyn Fn(&str) -> Option<String>) -> Result<(Config, PathBuf)> {
|
||||
let (mut instance, mut socket, mut state_dir, mut minds, mut operators, mut own_sender, mut daily_cap) =
|
||||
(None, None, None, None, None, None, None);
|
||||
let mut it = args.iter();
|
||||
while let Some(flag) = it.next() {
|
||||
let mut val = || it.next().cloned().ok_or_else(|| anyhow!("{USAGE}"));
|
||||
match flag.as_str() {
|
||||
"--instance" => instance = Some(val()?),
|
||||
"--socket" => socket = Some(PathBuf::from(val()?)),
|
||||
"--state-dir" => state_dir = Some(PathBuf::from(val()?)),
|
||||
"--minds" => minds = Some(split_csv(&val()?)),
|
||||
"--operators" => operators = Some(split_csv(&val()?)),
|
||||
"--own-sender" => own_sender = Some(val()?),
|
||||
"--daily-cap" => {
|
||||
let parsed: u32 = val()?.parse().map_err(|_| anyhow!("--daily-cap must be an integer"))?;
|
||||
daily_cap = Some(parsed);
|
||||
}
|
||||
_ => bail!("{USAGE}"),
|
||||
}
|
||||
}
|
||||
let instance = Slug(instance.ok_or_else(|| anyhow!("--instance is required"))?);
|
||||
let socket = socket.ok_or_else(|| anyhow!("--socket is required"))?;
|
||||
let state_dir = state_dir.ok_or_else(|| anyhow!("--state-dir is required"))?;
|
||||
let minds = minds.unwrap_or_else(|| get_env("MIND_PERSONA_MINDS").map(|s| split_csv(&s)).unwrap_or_default());
|
||||
let operators =
|
||||
operators.unwrap_or_else(|| get_env("MIND_PERSONA_OPERATOR").map(|s| split_csv(&s)).unwrap_or_default());
|
||||
let own_sender = own_sender
|
||||
.or_else(|| get_env("MIND_PERSONA_SELF_SENDER"))
|
||||
.ok_or_else(|| anyhow!("--own-sender is required"))?;
|
||||
let daily_cap = match daily_cap {
|
||||
Some(cap) => Some(cap),
|
||||
None => get_env("MIND_CHAT_DAILY_CAP")
|
||||
.map(|v| v.parse::<u32>().map_err(|_| anyhow!("MIND_CHAT_DAILY_CAP must be an integer")))
|
||||
.transpose()?,
|
||||
};
|
||||
Ok((Config { instance, state_dir, minds, operators, own_sender, daily_cap }, socket))
|
||||
}
|
||||
|
||||
fn run_gate(args: &[String]) -> Result<()> {
|
||||
let (config, socket) = parse_gate_args(args, &setting)?;
|
||||
let chat = open_rudp(&config.instance.0)?;
|
||||
serve_gate(config, chat, &socket, now_ms)
|
||||
}
|
||||
|
||||
fn parse_client_request(cmd: &str, args: &[String]) -> Result<Request> {
|
||||
let mut it = args.iter();
|
||||
match cmd {
|
||||
"pending" => {
|
||||
let mut ack = false;
|
||||
for flag in it {
|
||||
match flag.as_str() {
|
||||
"--ack" if !ack => ack = true,
|
||||
_ => bail!("{USAGE}"),
|
||||
}
|
||||
}
|
||||
Ok(Request::Pending { ack })
|
||||
}
|
||||
"tail" => {
|
||||
let mut room = None;
|
||||
while let Some(flag) = it.next() {
|
||||
match flag.as_str() {
|
||||
"--room" => {
|
||||
let val = it.next().cloned().ok_or_else(|| anyhow!("{USAGE}"))?;
|
||||
if room.replace(val).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
_ => bail!("{USAGE}"),
|
||||
}
|
||||
}
|
||||
Ok(Request::Tail { room })
|
||||
}
|
||||
"say" => {
|
||||
let (mut room, mut text, mut resend) = (None, None, None);
|
||||
while let Some(flag) = it.next() {
|
||||
let val = it.next().cloned().ok_or_else(|| anyhow!("{USAGE}"))?;
|
||||
let slot = match flag.as_str() {
|
||||
"--room" => &mut room,
|
||||
"--text" => &mut text,
|
||||
"--resend" => &mut resend,
|
||||
_ => bail!("{USAGE}"),
|
||||
};
|
||||
if slot.replace(val).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
let room = room.ok_or_else(|| anyhow!("{USAGE}"))?;
|
||||
if text.is_some() == resend.is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
Ok(Request::Say { room, text, resend })
|
||||
}
|
||||
"ack" => {
|
||||
let mut through = None;
|
||||
while let Some(flag) = it.next() {
|
||||
match flag.as_str() {
|
||||
"--through" => {
|
||||
let raw = it.next().ok_or_else(|| anyhow!("{USAGE}"))?;
|
||||
let parsed = raw.parse::<u64>().map_err(|_| anyhow!("--through must be u64"))?;
|
||||
if through.replace(parsed).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
_ => bail!("{USAGE}"),
|
||||
}
|
||||
}
|
||||
Ok(Request::Ack { through: through.ok_or_else(|| anyhow!("{USAGE}"))? })
|
||||
}
|
||||
"mark-read" => {
|
||||
let (mut room, mut event, mut at) = (None, None, None);
|
||||
while let Some(flag) = it.next() {
|
||||
let val = it.next().cloned().ok_or_else(|| anyhow!("{USAGE}"))?;
|
||||
match flag.as_str() {
|
||||
"--room" => {
|
||||
if room.replace(val).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
"--event" => {
|
||||
if event.replace(val).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
"--at" => {
|
||||
let parsed = val.parse::<u64>().map_err(|_| anyhow!("--at must be u64"))?;
|
||||
if at.replace(parsed).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
_ => bail!("{USAGE}"),
|
||||
}
|
||||
}
|
||||
Ok(Request::MarkRead {
|
||||
room: room.ok_or_else(|| anyhow!("{USAGE}"))?,
|
||||
event: event.ok_or_else(|| anyhow!("{USAGE}"))?,
|
||||
at_unix_ms: at.ok_or_else(|| anyhow!("{USAGE}"))?,
|
||||
})
|
||||
}
|
||||
"open-direct" => {
|
||||
let (mut user, mut text) = (None, None);
|
||||
while let Some(flag) = it.next() {
|
||||
let val = it.next().cloned().ok_or_else(|| anyhow!("{USAGE}"))?;
|
||||
let slot = match flag.as_str() {
|
||||
"--user" => &mut user,
|
||||
"--text" => &mut text,
|
||||
_ => bail!("{USAGE}"),
|
||||
};
|
||||
if slot.replace(val).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
Ok(Request::OpenDirect {
|
||||
user: user.ok_or_else(|| anyhow!("{USAGE}"))?,
|
||||
text: text.ok_or_else(|| anyhow!("{USAGE}"))?,
|
||||
})
|
||||
}
|
||||
"status" => {
|
||||
if !args.is_empty() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
Ok(Request::Status {})
|
||||
}
|
||||
_ => bail!("{USAGE}"),
|
||||
}
|
||||
}
|
||||
|
||||
enum DirectFailure {
|
||||
Misconfigured(anyhow::Error),
|
||||
Unavailable(anyhow::Error),
|
||||
}
|
||||
|
||||
fn run_direct(request: Request) -> std::result::Result<Answer, DirectFailure> {
|
||||
let load_config = || -> Result<(Config, RudpChat)> {
|
||||
let instance = Slug(required_env("EUREKA_INSTANCE")?);
|
||||
instance.validate_slug().map_err(|r| anyhow!("invalid EUREKA_INSTANCE: {r:?}"))?;
|
||||
let state_dir = PathBuf::from(required_env("STATE_DIRECTORY")?);
|
||||
let minds = setting("MIND_PERSONA_MINDS").map(|s| split_csv(&s)).unwrap_or_default();
|
||||
let operators = setting("MIND_PERSONA_OPERATOR").map(|s| split_csv(&s)).unwrap_or_default();
|
||||
let own_sender = setting("MIND_PERSONA_SELF_SENDER").unwrap_or_else(|| format!("@{}:gamecult.org", instance.0));
|
||||
let daily_cap = setting("MIND_CHAT_DAILY_CAP")
|
||||
.map(|v| v.parse::<u32>().map_err(|_| anyhow!("MIND_CHAT_DAILY_CAP must be an integer")))
|
||||
.transpose()?;
|
||||
let chat = open_rudp(&instance.0)?;
|
||||
Ok((Config { instance, state_dir, minds, operators, own_sender, daily_cap }, chat))
|
||||
};
|
||||
let (config, chat) = load_config().map_err(DirectFailure::Misconfigured)?;
|
||||
let mut engine = Engine::open(config, chat, now_ms()).map_err(DirectFailure::Unavailable)?;
|
||||
engine.handle(request, now_ms()).map_err(DirectFailure::Unavailable)
|
||||
}
|
||||
|
||||
#[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments")]
|
||||
fn main() {
|
||||
restrict_umask();
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if args.is_empty() || matches!(args[0].as_str(), "-h" | "--help" | "help") {
|
||||
println!("{USAGE}");
|
||||
return;
|
||||
}
|
||||
if args[0] == "gate" {
|
||||
if let Err(error) = run_gate(&args[1..]) {
|
||||
eprintln!("mind-chat: {error:#}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let request = match parse_client_request(&args[0], &args[1..]) {
|
||||
Ok(req) => req,
|
||||
Err(error) => {
|
||||
eprintln!("InvalidInput: {error:#}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
|
||||
let answer = if let Some(socket) = setting("MIND_CHAT_SOCKET") {
|
||||
match call_socket(Path::new(&socket), &request) {
|
||||
Ok(ans) => ans,
|
||||
Err(error) => {
|
||||
eprintln!("Unavailable: {error:#}");
|
||||
std::process::exit(3);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match run_direct(request) {
|
||||
Ok(ans) => ans,
|
||||
Err(DirectFailure::Misconfigured(error)) => {
|
||||
eprintln!("Misconfigured: {error:#}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
Err(DirectFailure::Unavailable(error)) => {
|
||||
eprintln!("Unavailable: {error:#}");
|
||||
std::process::exit(3);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if !answer.stdout.is_empty() {
|
||||
println!("{}", answer.stdout);
|
||||
}
|
||||
if !answer.stderr.is_empty() {
|
||||
eprintln!("{}", answer.stderr);
|
||||
}
|
||||
std::process::exit(i32::from(answer.exit));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn s(items: &[&str]) -> Vec<String> {
|
||||
items.iter().map(|v| (*v).to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_client_requests_covers_every_subcommand_and_rejection() {
|
||||
assert_eq!(parse_client_request("pending", &[]).unwrap(), Request::Pending { ack: false });
|
||||
assert_eq!(parse_client_request("pending", &s(&["--ack"])).unwrap(), Request::Pending { ack: true });
|
||||
assert!(parse_client_request("pending", &s(&["--ack", "--ack"])).is_err());
|
||||
assert!(parse_client_request("pending", &s(&["--bad"])).is_err());
|
||||
|
||||
assert_eq!(parse_client_request("tail", &[]).unwrap(), Request::Tail { room: None });
|
||||
assert_eq!(
|
||||
parse_client_request("tail", &s(&["--room", "#r:x"])).unwrap(),
|
||||
Request::Tail { room: Some("#r:x".into()) }
|
||||
);
|
||||
assert!(parse_client_request("tail", &s(&["--room", "a", "--room", "b"])).is_err());
|
||||
|
||||
assert_eq!(
|
||||
parse_client_request("say", &s(&["--room", "#r:x", "--text", "hi"])).unwrap(),
|
||||
Request::Say { room: "#r:x".into(), text: Some("hi".into()), resend: None }
|
||||
);
|
||||
assert_eq!(
|
||||
parse_client_request("say", &s(&["--room", "#r:x", "--resend", "mc-1"])).unwrap(),
|
||||
Request::Say { room: "#r:x".into(), text: None, resend: Some("mc-1".into()) }
|
||||
);
|
||||
assert!(parse_client_request("say", &s(&["--room", "#r:x"])).is_err());
|
||||
assert!(parse_client_request("say", &s(&["--room", "#r:x", "--text", "hi", "--resend", "mc-1"])).is_err());
|
||||
|
||||
assert_eq!(parse_client_request("ack", &s(&["--through", "42"])).unwrap(), Request::Ack { through: 42 });
|
||||
assert!(parse_client_request("ack", &s(&["--through", "nope"])).is_err());
|
||||
assert!(parse_client_request("ack", &[]).is_err());
|
||||
|
||||
assert_eq!(
|
||||
parse_client_request("mark-read", &s(&["--room", "!r:x", "--event", "$e1", "--at", "99"])).unwrap(),
|
||||
Request::MarkRead { room: "!r:x".into(), event: "$e1".into(), at_unix_ms: 99 }
|
||||
);
|
||||
assert!(parse_client_request("mark-read", &s(&["--room", "!r:x", "--event", "$e1", "--at", "x"])).is_err());
|
||||
|
||||
assert_eq!(
|
||||
parse_client_request("open-direct", &s(&["--user", "@u:x", "--text", "hello"])).unwrap(),
|
||||
Request::OpenDirect { user: "@u:x".into(), text: "hello".into() }
|
||||
);
|
||||
assert!(parse_client_request("open-direct", &s(&["--user", "@u:x"])).is_err());
|
||||
|
||||
assert_eq!(parse_client_request("status", &[]).unwrap(), Request::Status {});
|
||||
assert!(parse_client_request("status", &s(&["extra"])).is_err());
|
||||
assert!(parse_client_request("unknown", &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_gate_args_and_helpers() {
|
||||
assert_eq!(split_csv(" @a:x , , @b:x "), s(&["@a:x", "@b:x"]));
|
||||
assert_eq!(split_csv(" , "), Vec::<String>::new());
|
||||
assert!(now_ms() > 1_700_000_000_000);
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
restrict_umask();
|
||||
// SAFETY: restores the prior umask after observing restrict_umask().
|
||||
let prev = unsafe { libc::umask(0o022) };
|
||||
assert_eq!(prev, 0o077);
|
||||
}
|
||||
|
||||
let no_env = |_: &str| None;
|
||||
let (cfg, sock) = parse_gate_args(
|
||||
&s(&[
|
||||
"--instance",
|
||||
"nibu",
|
||||
"--socket",
|
||||
"/tmp/g.sock",
|
||||
"--state-dir",
|
||||
"/tmp/st",
|
||||
"--minds",
|
||||
"@nibu:x,@eureka:x",
|
||||
"--operators",
|
||||
"@meta:x",
|
||||
"--own-sender",
|
||||
"@nibu:x",
|
||||
"--daily-cap",
|
||||
"12",
|
||||
]),
|
||||
&no_env,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cfg.instance.0, "nibu");
|
||||
assert_eq!(sock, PathBuf::from("/tmp/g.sock"));
|
||||
assert_eq!(cfg.state_dir, PathBuf::from("/tmp/st"));
|
||||
assert_eq!(cfg.minds, s(&["@nibu:x", "@eureka:x"]));
|
||||
assert_eq!(cfg.operators, s(&["@meta:x"]));
|
||||
assert_eq!(cfg.own_sender, "@nibu:x");
|
||||
assert_eq!(cfg.daily_cap, Some(12));
|
||||
|
||||
let from_env = |k: &str| match k {
|
||||
"MIND_PERSONA_MINDS" => Some("@a:x,@b:x".into()),
|
||||
"MIND_PERSONA_OPERATOR" => Some("@op:x".into()),
|
||||
"MIND_PERSONA_SELF_SENDER" => Some("@a:x".into()),
|
||||
"MIND_CHAT_DAILY_CAP" => Some("5".into()),
|
||||
_ => None,
|
||||
};
|
||||
let (env_cfg, _) = parse_gate_args(
|
||||
&s(&["--instance", "a", "--socket", "/tmp/s", "--state-dir", "/tmp/d"]),
|
||||
&from_env,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(env_cfg.minds, s(&["@a:x", "@b:x"]));
|
||||
assert_eq!(env_cfg.operators, s(&["@op:x"]));
|
||||
assert_eq!(env_cfg.own_sender, "@a:x");
|
||||
assert_eq!(env_cfg.daily_cap, Some(5));
|
||||
|
||||
assert!(parse_gate_args(&s(&["--instance", "nibu", "--socket", "/s", "--state-dir", "/d", "--own-sender", "@a", "--daily-cap", "bad"]), &no_env).is_err());
|
||||
assert!(parse_gate_args(&s(&["--socket", "/s", "--state-dir", "/d", "--own-sender", "@a"]), &no_env).is_err());
|
||||
assert!(parse_gate_args(&s(&["--instance", "nibu", "--state-dir", "/d", "--own-sender", "@a"]), &no_env).is_err());
|
||||
assert!(parse_gate_args(&s(&["--instance", "nibu", "--socket", "/s", "--own-sender", "@a"]), &no_env).is_err());
|
||||
assert!(parse_gate_args(&s(&["--instance", "nibu", "--socket", "/s", "--state-dir", "/d"]), &no_env).is_err());
|
||||
}
|
||||
}
|
||||
1776
crates/mind-body/src/chat_gate.rs
Normal file
1776
crates/mind-body/src/chat_gate.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -35,6 +35,7 @@
|
|||
|
||||
mod address;
|
||||
pub mod chat_client;
|
||||
pub mod chat_gate;
|
||||
#[allow(dead_code, reason = "the loader is kept for the three-stage turn's perception (map C3): its first caller removes this allow; `Image` is live through `self_run::session`")]
|
||||
mod chat_image;
|
||||
pub mod chat_rudp;
|
||||
|
|
|
|||
129
crates/mind-body/tests/mind_chat_bin.rs
Normal file
129
crates/mind-body/tests/mind_chat_bin.rs
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
//! Subprocess boundary checks for the `mind-chat` binary (`main`, `setting`, `required_env`, `run_gate`, `MIND_CHAT_SOCKET`).
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn run(envs: &[(&str, &str)], args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_mind-chat"))
|
||||
.args(args)
|
||||
.env_clear()
|
||||
.envs(envs.iter().copied())
|
||||
.output()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn text(bytes: &[u8]) -> String {
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mind_chat_binary_modes_env_handling_and_usage() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
// 1. Empty args and --help print usage and exit 0.
|
||||
for help_args in [&[][..], &["--help"][..]] {
|
||||
let out = run(&[], help_args);
|
||||
assert_eq!(out.status.code(), Some(0), "{help_args:?}: {}", text(&out.stderr));
|
||||
assert!(text(&out.stdout).contains("usage:"), "{}", text(&out.stdout));
|
||||
}
|
||||
|
||||
// 2. Client usage errors exit 2.
|
||||
let bad_client = run(&[], &["say", "--room", "#r:x"]);
|
||||
assert_eq!(bad_client.status.code(), Some(2), "{}", text(&bad_client.stderr));
|
||||
assert!(text(&bad_client.stderr).starts_with("InvalidInput:"), "{}", text(&bad_client.stderr));
|
||||
|
||||
// 3. `gate` dispatches cleanly and validates required settings (no ok(()) bypass).
|
||||
let bad_gate = run(&[], &["gate", "--unknown"]);
|
||||
assert_eq!(bad_gate.status.code(), Some(2));
|
||||
assert!(text(&bad_gate.stderr).starts_with("mind-chat:"), "{}", text(&bad_gate.stderr));
|
||||
|
||||
let sock_path = dir.path().join("gate.sock");
|
||||
let state_dir = dir.path().join("state");
|
||||
let missing_endpoint = run(
|
||||
&[],
|
||||
&[
|
||||
"gate",
|
||||
"--instance",
|
||||
"nibu",
|
||||
"--socket",
|
||||
sock_path.to_str().unwrap(),
|
||||
"--state-dir",
|
||||
state_dir.to_str().unwrap(),
|
||||
"--own-sender",
|
||||
"@nibu:gamecult.org",
|
||||
],
|
||||
);
|
||||
assert_eq!(missing_endpoint.status.code(), Some(2));
|
||||
assert!(
|
||||
text(&missing_endpoint.stderr).contains("BIFROST_CHAT_ENDPOINT is not set"),
|
||||
"{}",
|
||||
text(&missing_endpoint.stderr)
|
||||
);
|
||||
|
||||
// 4. Empty MIND_CHAT_SOCKET falls back to direct mode (Misconfigured exit 2);
|
||||
// missing socket path connects over Unix socket (Unavailable exit 3).
|
||||
for envs in [&[][..], &[("MIND_CHAT_SOCKET", "")][..]] {
|
||||
let empty_sock = run(envs, &["status"]);
|
||||
assert_eq!(empty_sock.status.code(), Some(2), "{envs:?}: {}", text(&empty_sock.stderr));
|
||||
assert!(
|
||||
text(&empty_sock.stderr).contains("EUREKA_INSTANCE is not set"),
|
||||
"{}",
|
||||
text(&empty_sock.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
let missing_sock = run(&[("MIND_CHAT_SOCKET", sock_path.to_str().unwrap())], &["status"]);
|
||||
assert_eq!(missing_sock.status.code(), Some(3));
|
||||
assert!(text(&missing_sock.stderr).starts_with("Unavailable:"), "{}", text(&missing_sock.stderr));
|
||||
|
||||
// 5. Direct mode checks BIFROST_CHAT_KEY_FILE via required_env (Misconfigured exit 2, not Unavailable).
|
||||
let missing_key = run(
|
||||
&[
|
||||
("EUREKA_INSTANCE", "nibu"),
|
||||
("STATE_DIRECTORY", state_dir.to_str().unwrap()),
|
||||
("BIFROST_CHAT_ENDPOINT", "rudp://127.0.0.1:9"),
|
||||
],
|
||||
&["status"],
|
||||
);
|
||||
assert_eq!(missing_key.status.code(), Some(2), "{}", text(&missing_key.stderr));
|
||||
assert!(
|
||||
text(&missing_key.stderr).contains("BIFROST_CHAT_KEY_FILE is not set"),
|
||||
"{}",
|
||||
text(&missing_key.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn mind_chat_client_relays_socket_stdout_stderr_and_exit_code() {
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::os::unix::net::UnixListener;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let sock = dir.path().join("mock-gate.sock");
|
||||
let listener = UnixListener::bind(&sock).unwrap();
|
||||
|
||||
let srv = std::thread::spawn(move || {
|
||||
for reply in [
|
||||
r#"{"exit":0,"stdout":"ok-status","stderr":""}"#,
|
||||
r#"{"exit":1,"stdout":"","stderr":"refused-detail"}"#,
|
||||
] {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(&stream).read_line(&mut line).unwrap();
|
||||
writeln!(stream, "{reply}").unwrap();
|
||||
stream.flush().unwrap();
|
||||
}
|
||||
});
|
||||
|
||||
let ok = run(&[("MIND_CHAT_SOCKET", sock.to_str().unwrap())], &["status"]);
|
||||
assert_eq!(ok.status.code(), Some(0));
|
||||
assert_eq!(text(&ok.stdout), "ok-status\n");
|
||||
assert_eq!(text(&ok.stderr), "");
|
||||
|
||||
let refused = run(&[("MIND_CHAT_SOCKET", sock.to_str().unwrap())], &["pending"]);
|
||||
assert_eq!(refused.status.code(), Some(1));
|
||||
assert_eq!(text(&refused.stdout), "");
|
||||
assert_eq!(text(&refused.stderr), "refused-detail\n");
|
||||
|
||||
srv.join().unwrap();
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
mind_body: mod chat_client
|
||||
mind_body: mod chat_gate
|
||||
mind_body: mod chat_rudp
|
||||
mind_body: mod cli
|
||||
mind_body: mod connector
|
||||
|
|
@ -100,6 +101,18 @@ mind_body::chat_client: struct MouthRefused # [derive (Clone , Copy , Debug , Pa
|
|||
mind_body::chat_client: struct ReplyTo # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[event_id: String, sender: String, excerpt: Option < String >, at_cap: bool]
|
||||
mind_body::chat_client: struct SendBasis # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[seen_event_id: Option < String >, since_unix_ms: u64]
|
||||
mind_body::chat_client: struct TailLine # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[room: String, event_id: String, at_unix_ms: u64, sender: String, form: Form, basis: Option < Basis >, body: String, reply_to: ReplyLink]
|
||||
mind_body::chat_gate: # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] # [serde (tag = "op" , rename_all = "snake_case" , deny_unknown_fields)] pub enum Request { Pending { ack : bool } , Tail { room : Option < String > } , Say { room : String , text : Option < String > , resend : Option < String > } , Ack { through : u64 } , MarkRead { room : String , event : String , at_unix_ms : u64 } , OpenDirect { user : String , text : String } , Status { } , }
|
||||
mind_body::chat_gate: const STATE_FILE : & str
|
||||
mind_body::chat_gate: const UNSETTLED_WINDOW_S : i64
|
||||
mind_body::chat_gate: fn call_socket (socket : & Path , request : & Request) -> Result < Answer >
|
||||
mind_body::chat_gate: fn serve_gate (config : Config , chat : impl Chat , socket : & Path , now_ms : impl Fn () -> u64) -> Result < () >
|
||||
mind_body::chat_gate: impl Answer
|
||||
mind_body::chat_gate: impl Engine < C >: fn handle (& mut self , request : Request , now_ms : u64) -> Result < Answer >
|
||||
mind_body::chat_gate: impl Engine < C >: fn open (config : Config , chat : C , now_ms : u64) -> Result < Self >
|
||||
mind_body::chat_gate: impl< C : Chat > Engine < C >
|
||||
mind_body::chat_gate: struct Answer # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[exit: u8, stdout: String, stderr: String]
|
||||
mind_body::chat_gate: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[instance: Slug, state_dir: PathBuf, minds: Vec < String >, operators: Vec < String >, own_sender: String, daily_cap: Option < u32 >]
|
||||
mind_body::chat_gate: struct Engine< C : Chat > pub-fields[]
|
||||
mind_body::chat_image: impl Skip
|
||||
mind_body::chat_rudp: fn connection_id (key_file_text : & str) -> u32
|
||||
mind_body::chat_rudp: impl Chat for RudpChat
|
||||
|
|
@ -218,7 +231,7 @@ mind_body::lease_client: struct LeaseRequest # [derive (Clone , Debug , PartialE
|
|||
mind_body::lease_client: struct SocketLender pub-fields[]
|
||||
mind_body::lease_client: struct TokenFd pub-fields[]
|
||||
mind_body::lease_client::socket: impl Lease for Granted
|
||||
mind_body::persona: # [derive (Debug , PartialEq , Eq)] pub enum Outcome { Dead (HeldReason) , Drained { wakes : usize , acked_through : Option < u64 > } , Failed (String) , }
|
||||
mind_body::persona: # [derive (Debug , PartialEq , Eq)] pub enum Outcome { Dead (HeldReason) , Drained { wakes : usize , turns : usize , ended : Option < End > , acked_through : Option < u64 > } , Held { until : DateTime < Utc > } , Failed (String) , }
|
||||
mind_body::persona: const AGENT : & str
|
||||
mind_body::persona: const ENV_MINDS : & str
|
||||
mind_body::persona: const ENV_MODEL : & str
|
||||
|
|
@ -244,11 +257,16 @@ mind_body::persona: impl TraceView for TraceSnapshot
|
|||
mind_body::persona: impl fmt :: Display for Outcome
|
||||
mind_body::persona: pub trait Trace : TraceView { fn record (& self , key : & str , record : & Value) -> Result < () > ; }
|
||||
mind_body::persona: pub trait TraceView { fn records (& self) -> Result < Vec < Value > > ; }
|
||||
mind_body::persona: pub use live :: End ;
|
||||
mind_body::persona: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[rooms: Vec < String >, operators: Vec < String >, minds: Vec < String >, own_sender: String, model: String, review_room: Option < String >]
|
||||
mind_body::persona: struct FileTrace pub-fields[]
|
||||
mind_body::persona: struct Start< C : Chat > pub-fields[config: Config, persona: Box < dyn PersonaStore >, chat: C, trace: Box < dyn Trace >, addressing: Option < Box < dyn HeartbeatView > >, model: Box < dyn Model >, agent: Box < dyn Steps >, domain: Option < Box < dyn DomainSource > >, reads: Option < Box < dyn ReadSource > >, tuning: PathBuf, session: PathBuf, box_socket: PathBuf, clock: Box < dyn Fn () -> DateTime < Utc > >]
|
||||
mind_body::persona: struct Start< C : Chat > pub-fields[config: Config, persona: Box < dyn PersonaStore >, chat: C, trace: Box < dyn Trace >, addressing: Option < Box < dyn HeartbeatView > >, model: Box < dyn Model >, agent: Box < dyn Steps >, domain: Option < Box < dyn DomainSource > >, reads: Option < Box < dyn ReadSource > >, tuning: PathBuf, session: PathBuf, box_socket: PathBuf, clock: Box < dyn Fn () -> DateTime < Utc > >, pause: Box < dyn Fn (std :: time :: Duration) >]
|
||||
mind_body::persona: struct TraceSnapshot pub-fields[]
|
||||
mind_body::persona: struct TurnRecord # [derive (Clone , Debug , PartialEq , DatabaseEntry)] pub-fields[value: Value]
|
||||
mind_body::persona::live: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum End { Failed , DayCap , Spend , Span , Idle , }
|
||||
mind_body::persona::live: impl End
|
||||
mind_body::persona::live: impl Hearing < '_ >
|
||||
mind_body::persona::live: impl std :: fmt :: Display for End
|
||||
mind_body::projection: # [derive (Clone , Copy , Debug , Default , PartialEq , Eq , serde :: Deserialize)] # [serde (rename_all = "snake_case")] pub enum Through { # [default] Projector , Persona , }
|
||||
mind_body::projection: # [derive (Debug , PartialEq , Eq)] pub enum Put { Committed , Stale , Refused (String) , }
|
||||
mind_body::projection: fn project (organs : & Organs , request : & Request , now : DateTime < Utc >) -> Result < Value >
|
||||
|
|
@ -301,7 +319,7 @@ mind_body::projection::agent: struct Receipt # [derive (Clone , Debug , PartialE
|
|||
mind_body::projection::agent: struct Session # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[items: Vec < InputItem >, digest: String, retention: CacheRetention, created_at: DateTime < Utc >, last_call_at: DateTime < Utc >, last_usage: Option < Spent >]
|
||||
mind_body::projection::agent: struct TraceLedger< 'a > pub-fields[]
|
||||
mind_body::projection::agent: struct Turn # [derive (Clone , Debug , PartialEq)] pub-fields[ended: Ended, text: String, receipts: Vec < Receipt >, model_calls: usize, tool_calls: usize, usd: f64]
|
||||
mind_body::projection::agent: struct Wake< 'a > pub-fields[id: & 'a str, instructions: & 'a str, input: & 'a str, fresh: & 'a str]
|
||||
mind_body::projection::agent: struct Wake< 'a > pub-fields[id: & 'a str, wake: & 'a str, instructions: & 'a str, opening: & 'a str, input: & 'a str, fresh: & 'a str, first: bool]
|
||||
mind_body::projection::agent::read: impl Executor for Read < '_ >
|
||||
mind_body::projection::agent::read: struct Read< 'a > pub-fields[source: Option < & 'a dyn ReadSource >, since: DateTime < Utc >]
|
||||
mind_body::projection::agent::request_tool: impl Executor for RequestTool
|
||||
|
|
@ -394,6 +412,8 @@ mind_body::projection::select: impl< 'a > Inputs < 'a >
|
|||
mind_body::projection::simulate: fn simulate (harness : & Harness , plan_path : & Path) -> Result < String >
|
||||
mind_body::projection::simulate: impl HeartbeatView for Names < '_ >
|
||||
mind_body::projection::simulate: impl MouthReader for View < '_ >
|
||||
mind_body::projection::simulate: impl PersonaSource for InRun
|
||||
mind_body::projection::simulate: impl PersonaStore for InRun
|
||||
mind_body::projection::simulate: impl ReadSource for CastReads < '_ >
|
||||
mind_body::projection::tuning: const TUNING_FILE : & str
|
||||
mind_body::projection::tuning: const TUNING_ROOT : & str
|
||||
|
|
@ -410,7 +430,7 @@ mind_body::projection::tuning: impl Default for SelectTuning
|
|||
mind_body::projection::tuning: impl Default for Tuning
|
||||
mind_body::projection::tuning: impl Price
|
||||
mind_body::projection::tuning: impl Tuning
|
||||
mind_body::projection::tuning: struct AgentTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, tool_calls: usize, model_calls: usize, wake_usd: f64, day_usd: f64, max_session_tokens: u64, retention: CacheRetention, ttl_s: CacheTtl, cache_min_tokens: u64, prices: BTreeMap < String , Price >]
|
||||
mind_body::projection::tuning: struct AgentTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, tool_calls: usize, model_calls: usize, wake_usd: f64, day_usd: f64, unmetered_usd: f64, idle_s: u64, span_s: u64, max_session_tokens: u64, retention: CacheRetention, ttl_s: CacheTtl, cache_min_tokens: u64, prices: BTreeMap < String , Price >]
|
||||
mind_body::projection::tuning: struct CacheTtl # [derive (Clone , Copy , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[short: u64, long: u64]
|
||||
mind_body::projection::tuning: struct InterpreterTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String]
|
||||
mind_body::projection::tuning: struct LensWeights # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[body_and_hour: f64, person_present: f64, unresolved_want: f64, memory_surfacing: f64, wondering: f64]
|
||||
|
|
|
|||
|
|
@ -264,6 +264,61 @@
|
|||
"required": [
|
||||
"RootsTouched"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Escalates a follow-up brief from a Persona session to Self on the persona door.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"EscalateGoal": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"campaign": {
|
||||
"$ref": "#/$defs/Slug"
|
||||
},
|
||||
"instance": {
|
||||
"$ref": "#/$defs/Slug"
|
||||
},
|
||||
"item": {
|
||||
"$ref": "#/$defs/Line"
|
||||
},
|
||||
"label": {
|
||||
"$ref": "#/$defs/Label"
|
||||
},
|
||||
"origin": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/$defs/MemoryOrigin"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"provenance": {
|
||||
"$ref": "#/$defs/PipelineProvenance"
|
||||
},
|
||||
"repo": {
|
||||
"$ref": "#/$defs/OrgRepo"
|
||||
},
|
||||
"why_it_can_wait": {
|
||||
"$ref": "#/$defs/Line"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"instance",
|
||||
"provenance",
|
||||
"campaign",
|
||||
"label",
|
||||
"repo",
|
||||
"item",
|
||||
"why_it_can_wait"
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"EscalateGoal"
|
||||
]
|
||||
}
|
||||
],
|
||||
"$defs": {
|
||||
|
|
|
|||
Loading…
Reference in a new issue