diff --git a/oxa/docs/lead-facts-store.md b/oxa/docs/lead-facts-store.md index 4912aa26e..02f259171 100644 --- a/oxa/docs/lead-facts-store.md +++ b/oxa/docs/lead-facts-store.md @@ -25,6 +25,11 @@ it retains no unbounded per-task tombstones. Retrying the latest source/revision fact returns its original event and timestamp, even after journal rotation. Different facts under that identity and stale revisions are errors. Sequence exhaustion is an error. +Standing initialization reserves one of those 16 slots before its first mutation; +ordinary producers cannot consume that reservation. The `standing` checkpoint +source, `StandingChanged` observations and `standing:` ask-ID namespace belong +to the standing store's protected prepared-append path, not public `Facts::append`. + Each append validates the projected situation before reserving the event. It then saves a pending observation in `facts.json`, appends and syncs the journal line, commits the source cursor and atomically replaces `situation.json`. Atomic replacements sync the file and directory. diff --git a/oxa/docs/standing.md b/oxa/docs/standing.md new file mode 100644 index 000000000..3168417fc --- /dev/null +++ b/oxa/docs/standing.md @@ -0,0 +1,139 @@ +# Standing rules and owner decisions + +`oxa_work::standing` stores the owner's rules, holds and questions for one repository. It +never opens runner task state, starts a model, writes a task receipt or creates a background +thread. The runner owns command/action wiring; the lead owns cards and tool registration. + +## Protected root and revisions + +The trusted frontend supplies a fixed per-repository root in owner configuration, outside +workspace and writable Git binds, and the repository's `Facts` instance. Neither path comes +from tool JSON. `Standing::initialize(root, Authority::Owner, facts)` is explicit. `open` +never turns missing, partial, corrupt, unsafe or inconsistent enforcement data into empty rules. +The existing private directory/file/no-follow primitives are reused. + +`read()` returns the current revision, entries, asks and explicit history-truncation flag. +`read_facts()` returns that view paired with a shared situation checked at the same standing +revision. Cards use this pair rather than joining independently read versions. +`live_rules()` excludes superseded/retired rules and released constraints; `open_asks()` +excludes answered questions. Active rules and unanswered asks share a 128-item limit. Up to +16 terminal records are retained; they may shrink to fit the 256 KiB read view. Pending +metadata is capped at 1 MiB. Active data is never dropped to make room. + +An owner can close a question even when its answer would exceed the view's byte budget. +The close observation is captured before answered history is trimmed. If that new answer +is immediately trimmed, pending metadata retains that one exact answered question until +the fact commits. Recovery validates its original question and answer revision; absent or +changed evidence cannot turn a missing unanswered question into a silent close. + +Every mutation supplies the document revision it read. A stale revision refuses without +changing the store. A live collision of kind/scope requires its exact `supersedes` ID. +IDs are derived from the checked revision, not from model text or time. Released and retired +records are not live: only a live entry can be verified as applied, answered or reminded. + +## Authority, values and checked application + +`Authority` is supplied separately by the trusted interface. It is absent from `Rule`, +`Question` and `AnswerRequest`. A model cannot claim owner authority by adding a JSON field +or quoting a message. The frontend checks the source reference and binds owner operations to +actual owner input. `said` preserves those words; `said_by` attributes them separately from +inherited hold protection. Sources name a command or saved session entry. + +Kinds are goal, priority, freeze, hold, budget, model, placement, gate, eligible, decided, +reserve and note. Text policy values remain explicit data. Budgets use integer USD micros +per day; the frontend presents/parses ordinary USD amounts. Gates contain an ordered T1/T2/T3 +tier and a closed set of additional evidence requirements. They supplement existing policy +floors. Reserve values use the closed public/paid/credentials/destructive/desktop classes. + +Only the owner raises a budget, establishes an initial positive budget/gate, weakens a gate, +changes reserves, or releases an owner constraint. Lead reductions and conjunctive gate +strengthening are allowed. An owner hold keeps its protection through a lead replacement; +replacing it cannot turn it into a releasable lead hold or change its release condition. + +Storing a rule gives it `Stored` state. Gateway caps, model profiles, placement, eligibility, +priority and merge-policy application belong to their existing runner/runtime adapters. +They consume the locked read view; this store does not invent another policy engine. +`verify` accepts only a frontend-owned checker reporting the exact current revision, scope, +actual value and evidence reference. Mismatches leave the rule Stored. An accepted proposal +also starts Stored; it does not claim a runtime was reconfigured. + +Reminders require owner context and a checked source. Counts, the latest source/time and +incident observations persist. After two reminders a live note reports that a conversion +should be offered. It is never converted automatically. An explicit owner decision may +supersede that note with an enforced kind. + +## One action guard + +`with_guard(action, subject, callback)` reloads and establishes the current policy's durability +under its stable lock. Subject identity is resolved by the trusted frontend; a missing PR +means checked absence, and a known PR must always be supplied. Admission can precede a PR. +Approve/enqueue/update require a positive PR identity. There is no head-dependent hold key. + +A live hold refuses admit, push, approve, enqueue and update. Freeze refuses approve/enqueue. +Both apply immediately while Stored. `is_held(pr)` is a read for presentation; a preceding +read never authorizes an effect. Callback receives `&Read` with the exact guarded revision, +including the other policy values for their owning adapters, and runs only after guard success. +It must not recursively read/write this Standing instance. + +The lock covers one effect and its result, never an entire worker, loop or batch. The caller +owns bounded execution/cancellation, side-effect idempotency and its receipt containing the +guarded revision. It must invoke another guard before the next effect. The store's guard +does not override existing tool, sandbox, gateway or publishing policy. + +## Questions and proposals + +The existing ask tool's payload is reused: question, 2–4 unique label/detail options and an +exact-label recommendation. Stored asks add ID, question revision, scope, time/source, +optional meanwhile plan and an optional owner answer. Unknown meanwhile remains `None`. +The existing UI/journal adapter is not replaced by a second tool in this module. + +`ask` records the question. A recommendation never answers it or grants permission. +`answer` requires owner context, the current document revision and the exact question +revision. Option labels are checked; free text is stored as free text. Answers preserve the +owner's actual words/source. A generic answer labelled "Release" cannot release a hold. + +`propose` binds an exact typed Rule to an ask and an accept label. Cards **must render that +rule's actual kind, scope and value**, not only model-written labels/details. Scope must match +the question. Only selecting that label through the owner interface applies the bound rule; +it cannot substitute a new value. A changed/superseded target refuses without closing the ask. +Free text has no implicit accept meaning. Other answers close only the question. This changes +standing data, never performs a GitHub/paid/tool side effect. + +A named `PrMerged(N)` condition can release a hold/freeze without asking for a second decision +already authorized by the owner. `release_when` uses a frontend-owned checker and requires the +exact matching `PrMerged` Event retained in this same Facts store. The runner records that +verified merge first. Wrong PRs, invented events and unavailable observations refuse; prose, +a successful worker and a changed head are insufficient. The resulting release retains its +source words and records checked merge evidence. Only the separate merge fact is landed work. + +## Durable fact handoff + +One fixed `standing` emitter uses the document revision. `StandingChanged` projects revision, +goal, one ask transition and an optional incident. Full rule/option/answer data stays in this +protected file. It does not emit two different facts under one source/revision. + +Event pages honor both the requested count (at most 64) and the serialized byte limit. +Large valid observations return smaller pages with `next` at the last included event; +readers keep advancing through retained history and receive explicit retention gaps. + +Under Standing → Facts lock order, the facts module validates capacity/semantics and durably +reserves an unpublished observation **before** the callback saves the pending policy. Other +appenders cannot consume its projection capacity, even if the process dies in the callback. +Only after the policy is durable is the reservation made replayable and its fact appended; +the current policy is committed last. Ordinary facts keep their existing append path. + +Recovery syncs a visible prepared policy, completes its reserved fact once, commits the policy +and establishes durability before another action. If the durable policy has no pending +mutation, a matching unpublished next-revision reservation has no prepared data: recovery +discards only that reservation, preserving the current rules, revision and committed facts. +A rejected initial projection leaves no policy mutation. A failed fact reservation therefore +cannot strand an ask; the owner can still answer an existing ask to free capacity. + +Recover standing before replaying runner callbacks that append facts. A facts-only read reports +the last committed sequence; it never publishes an unfinished standing preparation. The +standing read/guard APIs perform this recovery under their stable lock. No background worker +or task-state writer is added, and a failed observation stops before an effect. + +The runner owns `oxa work rule|hold|ask`, actual action guards and local command proofs. The +lead joins detailed asks by ID from `Read` with the small shared situation. These adapters +must be wired and proven before claiming the complete #629 L2 user flow is delivered. diff --git a/oxa/oxa-proto/src/work.rs b/oxa/oxa-proto/src/work.rs index 95ce43366..a9b004e7b 100644 --- a/oxa/oxa-proto/src/work.rs +++ b/oxa/oxa-proto/src/work.rs @@ -417,6 +417,16 @@ record!( ); record!(AskClosed { id: String } | s | { atom(&s.id, 128) }); record!(Incident { id: String, subject: Subject, kind: IncidentKind, evidence: Option } |s| { atom(&s.id, 256) }); +record!( + /// One durable standing revision. Ask details/answers stay in the protected standing file. + StandingChanged { + revision: u64, goal: Option, ask_opened: Option, + ask_closed: Option, incident: Option + } |s| { + require(s.revision > 0, "standing revision must be positive")?; + require(s.ask_opened.is_none() || s.ask_closed.is_none(), "standing mutation has two ask transitions") + } +); record!( Mechanical { subject: Subject, @@ -441,6 +451,7 @@ tagged!( AskOpened(Ask) => "ask_opened", AskClosed(AskClosed) => "ask_closed", Incident(Incident) => "incident", + StandingChanged(StandingChanged) => "standing_changed", Mechanical(Mechanical) => "mechanical", } ); @@ -451,6 +462,11 @@ impl Fact { Self::Mechanical(_) => EventClass::Mechanical, Self::Blocked(_) | Self::AskOpened(_) => EventClass::Attention, Self::Incident(incident) => incident.kind.class(), + Self::StandingChanged(change) if change.ask_opened.is_some() => EventClass::Attention, + Self::StandingChanged(change) => change + .incident + .as_ref() + .map_or(EventClass::Routine, |incident| incident.kind.class()), _ => EventClass::Routine, } } @@ -463,8 +479,14 @@ record!( at_ms: u64, checkpoint: Checkpoint, fact: Fact - } | s - | { require(s.seq > 0, "event sequence must be positive") } + } |s| { + require(s.seq > 0, "event sequence must be positive")?; + if let Fact::StandingChanged(change) = &s.fact { + require(s.checkpoint.source == "standing" && s.checkpoint.revision == change.revision, "standing checkpoint identity disagrees")?; + } + require(s.checkpoint.source != "standing" || matches!(s.fact, Fact::StandingChanged(_)), "standing source is reserved for standing revisions")?; + Ok(()) + } ); record!( /// A bounded materialized read view, not task state. Never drop running/blocked/asks to fit. diff --git a/oxa/oxa-work/src/events.rs b/oxa/oxa-work/src/events.rs index 6f45883a4..8d480a0d9 100644 --- a/oxa/oxa-work/src/events.rs +++ b/oxa/oxa-work/src/events.rs @@ -1,7 +1,9 @@ //! Durable facts journal and its bounded read view. Never opens runner task-state files. use crate::facts_io::Root; use crate::{situation, Result}; -use oxa_proto::work::{Checkpoint, Event, EventPage, Fact, Snapshot, MAX_EVENT_BYTES, MAX_SNAPSHOT_BYTES}; +use oxa_proto::work::{ + Checkpoint, Event, EventPage, Fact, Snapshot, MAX_EVENT_BYTES, MAX_PAGE_BYTES, MAX_SNAPSHOT_BYTES, +}; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::path::Path; @@ -23,12 +25,23 @@ struct State { last_by_source: Vec, // Write-ahead observation: a crash can replay it even if the journal line was torn. pending: Option, + // A cross-store reservation is unpublished until its owner syncs prepared data. + #[serde(default, skip_serializing_if = "not_preparing")] + preparing: bool, + #[serde(default, skip_serializing_if = "not_preparing")] + standing_reserved: bool, +} +fn not_preparing(value: &bool) -> bool { + !value } impl State { fn sources(&self) -> Result> { if self.version != 1 || self.last_by_source.len() > MAX_SOURCES { return Err("unsupported facts metadata or source capacity".into()); } + if self.preparing && self.pending.is_none() { + return Err("facts preparation has no reserved observation".into()); + } let events: Vec = self .last_by_source .iter() @@ -59,6 +72,7 @@ impl State { self.last_seq = event.seq; self.last_by_source = sources.iter().map(event_value).collect::>()?; self.pending = None; + self.preparing = false; Ok(()) } fn bytes(&self) -> Result> { @@ -136,31 +150,102 @@ impl Facts { /// Stop before the next action if this call fails. Replaying the same checkpoint repairs /// a lost acknowledgement, a torn last line or an interrupted snapshot replacement. pub fn append(&self, checkpoint: Checkpoint, at_ms: u64, fact: Fact) -> Result { + let reserved_ask = match &fact { + Fact::AskOpened(ask) => ask.id.starts_with("standing:"), + Fact::AskClosed(ask) => ask.id.starts_with("standing:"), + _ => false, + }; + if checkpoint.source == "standing" || matches!(fact, Fact::StandingChanged(_)) || reserved_ask { + return Err("standing observations require the protected prepared path".into()); + } + self.append_with(checkpoint, at_ms, fact, None:: Result<()>>) + } + /// Reserve capacity under the facts lock without inventing a standing event. + /// A failed initialization can retry the same reservation; ordinary stores + /// retain their full source capacity until standing explicitly claims a slot. + pub(crate) fn reserve_standing(&self) -> Result<()> { let _lock = self.root.lock(LOCK)?; - let (mut state, mut snapshot, journal) = self.recover()?; + let (mut state, _, _) = self.recover()?; let sources = state.sources()?; - if let Some(previous) = sources - .iter() - .find(|event| event.checkpoint.source == checkpoint.source) + if !sources.iter().any(|event| event.checkpoint.source == "standing") && sources.len() == MAX_SOURCES { - if checkpoint.revision == previous.checkpoint.revision { - return if previous.fact == fact { - Ok(previous.clone()) - } else { - Err("checkpoint identity has conflicting facts".into()) - }; + return Err("facts source capacity unavailable for standing".into()); + } + if state.standing_reserved { + // A previous rename may be visible even though its directory sync failed. + self.root.durable(STATE)?; + } else { + state.standing_reserved = true; + self.root.atomic(STATE, &state.bytes()?)?; + } + Ok(()) + } + /// Durably reserve capacity before the protected store prepares its mutation. A failed + /// preparation blocks other appenders until that store commits or cancels the reservation. + /// Never calls preparation for an already committed identity. + pub(crate) fn append_prepared( + &self, + checkpoint: Checkpoint, + at_ms: u64, + fact: Fact, + prepare: impl FnOnce(&Event) -> Result<()>, + ) -> Result { + self.append_with(checkpoint, at_ms, fact, Some(prepare)) + } + fn append_with( + &self, + checkpoint: Checkpoint, + at_ms: u64, + fact: Fact, + prepare: Option Result<()>>, + ) -> Result { + if prepare.is_some() && (!matches!(fact, Fact::StandingChanged(_)) || checkpoint.source != "standing") + { + return Err("only standing observations use protected preparation".into()); + } + let _lock = self.root.lock(LOCK)?; + let (mut state, mut snapshot, journal) = self.recover()?; + let sources = state.sources()?; + let reserved = state.preparing; + let event = if reserved { + if prepare.is_none() { + return Err("standing preparation must recover before another fact".into()); } - if checkpoint.revision < previous.checkpoint.revision { - return Err("stale facts checkpoint".into()); + let event = read_event_value(state.pending.as_ref().ok_or("missing reserved preparation")?)?; + if event.checkpoint != checkpoint || event.at_ms != at_ms || event.fact != fact { + return Err("another standing preparation is reserved".into()); + } + self.root.durable(STATE)?; + event + } else { + if let Some(previous) = sources + .iter() + .find(|event| event.checkpoint.source == checkpoint.source) + { + if checkpoint.revision == previous.checkpoint.revision { + return if previous.fact == fact { + Ok(previous.clone()) + } else { + Err("checkpoint identity has conflicting facts".into()) + }; + } + if checkpoint.revision < previous.checkpoint.revision { + return Err("stale facts checkpoint".into()); + } + } else if sources.len() == MAX_SOURCES + || (state.standing_reserved + && checkpoint.source != "standing" + && !sources.iter().any(|event| event.checkpoint.source == "standing") + && sources.len() == MAX_SOURCES - 1) + { + return Err("facts source capacity exceeded".into()); + } + Event { + seq: state.last_seq.checked_add(1).ok_or("facts sequence exhausted")?, + at_ms, + checkpoint, + fact, } - } else if sources.len() == MAX_SOURCES { - return Err("facts source capacity exceeded".into()); - } - let event = Event { - seq: state.last_seq.checked_add(1).ok_or("facts sequence exhausted")?, - at_ms, - checkpoint, - fact, }; let mut bytes = event.to_json().map_err(|error| error.to_string())?; bytes.push(b'\n'); @@ -169,8 +254,16 @@ impl Facts { } // Fail capacity/semantic checks before durably reserving an observation. situation::apply(&mut snapshot, &event)?; - state.pending = Some(event_value(&event)?); - self.root.atomic(STATE, &state.bytes()?)?; + if !reserved { + state.pending = Some(event_value(&event)?); + state.preparing = prepare.is_some(); + self.root.atomic(STATE, &state.bytes()?)?; + } + if let Some(prepare) = prepare { + prepare(&event)?; + state.preparing = false; + self.root.atomic(STATE, &state.bytes()?)?; + } if journal.current_bytes + bytes.len() > self.journal_bytes { self.root.rotate(CURRENT, PREVIOUS)?; } @@ -181,6 +274,27 @@ impl Facts { .atomic(SITUATION, &snapshot.to_json().map_err(|error| error.to_string())?)?; Ok(event) } + /// The standing lock is held and its durable document has no pending mutation. A matching + /// next-revision reservation therefore has no prepared data and can be discarded safely. + pub(crate) fn cancel_unprepared_standing(&self, revision: u64, goal: Option<&str>) -> Result { + let _lock = self.root.lock(LOCK)?; + let (mut state, snapshot, _) = self.recover()?; + if snapshot.standing_revision != revision || snapshot.goal.as_deref() != goal { + return Err("standing file disagrees with facts revision".into()); + } + if state.preparing { + let event = read_event_value(state.pending.as_ref().ok_or("missing reserved preparation")?)?; + if event.checkpoint.source != "standing" + || revision.checked_add(1) != Some(event.checkpoint.revision) + { + return Err("standing preparation disagrees with current policy".into()); + } + state.pending = None; + state.preparing = false; + self.root.atomic(STATE, &state.bytes()?)?; + } + Ok(snapshot) + } pub fn situation(&self) -> Result { let _lock = self.root.lock(LOCK)?; self.recover().map(|(_, snapshot, _)| snapshot) @@ -195,22 +309,39 @@ impl Facts { return Err("event cursor is ahead of the journal".into()); } let first_available = journal.events.first().map_or(1, |event| event.seq); - let events: Vec<_> = journal - .events - .into_iter() - .filter(|event| event.seq > after) - .take(limit) - .collect(); - let next = events - .last() - .map_or(after.max(first_available - 1), |event| event.seq); - let page = EventPage { + let mut page = EventPage { after, - events, - next, + events: Vec::new(), + next: after.max(first_available - 1), first_available, gap: after.saturating_add(1) < first_available, }; + // The envelope's next cursor can grow to last_seq. An event's standalone wire + // encoding bounds its nested encoding; counting one comma per event is conservative. + // Encode each candidate once instead of repeatedly serializing a growing page. + let mut bytes = page.to_json().map_err(|error| error.to_string())?.len() + + state + .last_seq + .to_string() + .len() + .saturating_sub(page.next.to_string().len()); + for event in journal + .events + .into_iter() + .filter(|event| event.seq > after) + .take(limit) + { + let event_bytes = event.to_json().map_err(|error| error.to_string())?.len() + 1; + if bytes + event_bytes > MAX_PAGE_BYTES { + if page.events.is_empty() { + return Err("event exceeds bounded page capacity".into()); + } + break; + } + bytes += event_bytes; + page.next = event.seq; + page.events.push(event); + } page.to_json().map_err(|error| error.to_string())?; Ok(page) } @@ -245,7 +376,7 @@ impl Facts { .map_err(|_| "invalid facts metadata")?; let sources = state.sources()?; let pending = state.pending.as_ref().map(read_event_value).transpose()?; - let mut journal = self.journal(pending.is_some())?; + let mut journal = self.journal(pending.is_some() && !state.preparing)?; let mut snapshot = Snapshot::from_json(&self.root.read(SITUATION, MAX_SNAPSHOT_BYTES)?) .map_err(|error| error.to_string())?; let original_seq = snapshot.as_of_seq; @@ -275,35 +406,47 @@ impl Facts { { return Err("invalid pending facts checkpoint".into()); } - situation::apply(&mut snapshot, &event)?; - if journal.last_seq() == state.last_seq { - if let Some(length) = journal.torn_at { - self.root.truncate(CURRENT, length)?; - journal.current_bytes = length as usize; - } - let mut bytes = event.to_json().map_err(|error| error.to_string())?; - bytes.push(b'\n'); - if bytes.len() > self.journal_bytes { - return Err("event exceeds journal capacity".into()); + if state.preparing { + if !matches!(event.fact, Fact::StandingChanged(_)) + || journal.last_seq() != state.last_seq + || journal.torn_at.is_some() + { + return Err("invalid unpublished standing preparation".into()); } - if journal.current_bytes + bytes.len() > self.journal_bytes { - self.root.rotate(CURRENT, PREVIOUS)?; - } - self.root.append(CURRENT, &bytes)?; - } else if journal.events.last() != Some(&event) || journal.torn_at.is_some() { - return Err("pending fact disagrees with the journal".into()); + // Reads report committed facts only. Append cannot consume this capacity; + // the owning standing store must first commit or cancel its preparation. + situation::apply(&mut snapshot.clone(), &event)?; } else { - // Visibility is not durability: the original append may have died before sync. - let leaf = if journal.current_bytes == 0 { - PREVIOUS + situation::apply(&mut snapshot, &event)?; + if journal.last_seq() == state.last_seq { + if let Some(length) = journal.torn_at { + self.root.truncate(CURRENT, length)?; + journal.current_bytes = length as usize; + } + let mut bytes = event.to_json().map_err(|error| error.to_string())?; + bytes.push(b'\n'); + if bytes.len() > self.journal_bytes { + return Err("event exceeds journal capacity".into()); + } + if journal.current_bytes + bytes.len() > self.journal_bytes { + self.root.rotate(CURRENT, PREVIOUS)?; + } + self.root.append(CURRENT, &bytes)?; + } else if journal.events.last() != Some(&event) || journal.torn_at.is_some() { + return Err("pending fact disagrees with the journal".into()); } else { - CURRENT - }; - self.root.append(leaf, b"")?; + // Visibility is not durability: the original append may have died before sync. + let leaf = if journal.current_bytes == 0 { + PREVIOUS + } else { + CURRENT + }; + self.root.append(leaf, b"")?; + } + state.committed(&event)?; + self.root.atomic(STATE, &state.bytes()?)?; + journal = self.journal(false)?; } - state.committed(&event)?; - self.root.atomic(STATE, &state.bytes()?)?; - journal = self.journal(false)?; } else if journal.last_seq() != state.last_seq { return Err("journal disagrees with committed facts".into()); } diff --git a/oxa/oxa-work/src/events/tests.rs b/oxa/oxa-work/src/events/tests.rs index 420a1e650..145e9afd9 100644 --- a/oxa/oxa-work/src/events/tests.rs +++ b/oxa/oxa-work/src/events/tests.rs @@ -70,6 +70,97 @@ fn reserve(facts: &Facts, fact: Fact) -> Event { event } +#[test] +fn a_crashed_preparation_keeps_its_projection_capacity_and_commits_once() { + const CHILD: &str = "OXA_FACTS_PREPARATION_CHILD"; + let observation = || { + Fact::StandingChanged(StandingChanged { + revision: 1, + goal: None, + ask_opened: Some(Ask { + id: "prepared-ask".into(), + subject: Subject::Repository, + question: "Choose an option".into(), + }), + ask_closed: None, + incident: None, + }) + }; + if let Some(root) = std::env::var_os(CHILD) { + let facts = Facts::open(Path::new(&root).join("facts").as_path()).unwrap(); + let policy = Root::open(Path::new(&root), false).unwrap(); + facts + .append_prepared(checkpoint("standing", 1), 500, observation(), |event| { + policy.atomic("prepared.json", &event.to_json().unwrap()).unwrap(); + std::process::exit(73); + }) + .unwrap(); + panic!("preparation did not reach its crash boundary"); + } + let fixture = Fixture::new(); + let facts = fixture.facts(); + for revision in 1..=127 { + facts + .append( + checkpoint("runner", revision), + revision, + Fact::TaskStarted(task(revision as usize)), + ) + .unwrap(); + } + let child = std::process::Command::new(std::env::current_exe().unwrap()) + .env_clear() + .env(CHILD, &fixture.0) + .args([ + "--exact", + "events::tests::a_crashed_preparation_keeps_its_projection_capacity_and_commits_once", + ]) + .output() + .unwrap(); + assert_eq!( + child.status.code(), + Some(73), + "{}", + String::from_utf8_lossy(&child.stderr) + ); + let recovered = Facts::open(&fixture.root()).unwrap(); + assert_eq!(recovered.situation().unwrap().as_of_seq, 127); + assert!(recovered + .append(checkpoint("runner", 128), 600, Fact::TaskStarted(task(128))) + .is_err()); + assert_eq!(recovered.events_after(127, 64).unwrap().events.len(), 0); + let committed = recovered + .append_prepared(checkpoint("standing", 1), 500, observation(), |event| { + assert_eq!( + fs::read(fixture.0.join("prepared.json")).unwrap(), + event.to_json().unwrap() + ); + Ok(()) + }) + .unwrap(); + assert_eq!(committed.seq, 128); + assert_eq!(recovered.situation().unwrap().asks.len(), 1); + let again = recovered + .append_prepared(checkpoint("standing", 1), 500, observation(), |_| { + panic!("prepared twice") + }) + .unwrap(); + assert_eq!(again, committed); + recovered + .append( + checkpoint("cleanup", 1), + 700, + Fact::AskClosed(AskClosed { + id: "prepared-ask".into(), + }), + ) + .unwrap(); + recovered + .append(checkpoint("runner", 128), 800, Fact::TaskStarted(task(128))) + .unwrap(); + assert_eq!(recovered.situation().unwrap().running.len(), 128); +} + #[test] fn lifecycle_facts_do_not_turn_worker_success_into_landed_work() { let env = Fixture::new(); @@ -346,6 +437,85 @@ fn rotation_is_bounded_and_cursor_gaps_are_explicit_without_resetting_sequences( assert!(facts.events_after(0, 0).is_err()); } +#[test] +fn large_valid_events_page_by_bytes_and_keep_advancing_across_retention_gaps() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let observation = |revision| { + Fact::StandingChanged(StandingChanged { + revision, + goal: Some("\"".repeat(1024)), + ask_opened: Some(Ask { + id: "ask".repeat(32), + subject: Subject::Repository, + question: "\"".repeat(512), + }), + ask_closed: None, + incident: Some(Incident { + id: "incident".repeat(32), + subject: Subject::Task("t".repeat(128)), + kind: IncidentKind::RuleReminder, + evidence: Some(Evidence { + kind: EvidenceKind::LocalCheck, + id: "e".repeat(256), + }), + }), + }) + }; + for revision in 1..=64 { + let event = facts + .append_prepared( + checkpoint("standing", revision), + revision, + observation(revision), + |_| Ok(()), + ) + .unwrap(); + assert!(event.to_json().unwrap().len() <= MAX_EVENT_BYTES); + } + let first = facts + .events_after(0, 64) + .expect("healthy large events must return a usable bounded page"); + assert!(!first.gap); + assert!(!first.events.is_empty() && first.events.len() < 64); + let mut cursor = 0; + let mut seen = Vec::new(); + while cursor < 64 { + let page = facts.events_after(cursor, 64).unwrap(); + assert!(page.to_json().unwrap().len() <= oxa_proto::work::MAX_PAGE_BYTES); + assert_eq!(page.next, page.events.last().unwrap().seq); + assert!(page.next > cursor); + seen.extend(page.events.iter().map(|event| event.seq)); + cursor = page.next; + } + assert_eq!(seen, (1..=64).collect::>()); + for revision in 65..=180 { + facts + .append_prepared( + checkpoint("standing", revision), + revision, + observation(revision), + |_| Ok(()), + ) + .unwrap(); + } + let page = facts.events_after(0, 64).unwrap(); + assert!(page.gap && page.first_available > 1); + let first_retained = page.first_available; + cursor = first_retained - 1; + seen.clear(); + while cursor < 180 { + let page = facts.events_after(cursor, 64).unwrap(); + assert!(page.to_json().unwrap().len() <= oxa_proto::work::MAX_PAGE_BYTES); + assert!(page.next > cursor); + assert_eq!(page.next, page.events.last().unwrap().seq); + seen.extend(page.events.iter().map(|event| event.seq)); + cursor = page.next; + } + assert_eq!(seen, (first_retained..=180).collect::>()); + assert!(facts.events_after(180, 64).unwrap().events.is_empty()); +} + #[test] fn concurrent_sources_get_unique_contiguous_repository_sequences() { let env = Fixture::new(); @@ -508,6 +678,45 @@ fn parent_directory_sync_error_blocks_initialization() { ); } +#[test] +fn retry_must_sync_a_visible_standing_reservation() { + const CHILD_ROOT: &str = "OXA_FACTS_TEST_STANDING_RESERVATION"; + if let Some(root) = std::env::var_os(CHILD_ROOT) { + let root = Path::new(&root); + let facts = Facts::initialize(root).unwrap(); + fs::set_permissions(root, fs::Permissions::from_mode(0o300)).unwrap(); + let first = facts.reserve_standing().expect_err("directory sync must fail"); + assert!(first.contains("directory"), "{first}"); + let visible: State = serde_json::from_slice(&facts.root.read(STATE, STATE_BYTES).unwrap()).unwrap(); + assert!(visible.standing_reserved, "rename must precede the sync failure"); + let retry = facts.reserve_standing(); + fs::set_permissions(root, fs::Permissions::from_mode(0o700)).unwrap(); + let retry = retry.expect_err("retry must finish syncing the reservation"); + assert!(retry.contains("directory"), "{retry}"); + facts.reserve_standing().unwrap(); + return; + } + let env = Fixture::new(); + let mut child = std::process::Command::new(std::env::current_exe().unwrap()); + child.env_clear().env(CHILD_ROOT, env.root()).args([ + "--exact", + "events::tests::retry_must_sync_a_visible_standing_reservation", + ]); + // SAFETY: geteuid has no arguments, pointers or failure mode. + if unsafe { libc::geteuid() } == 0 { + use std::os::unix::process::CommandExt; + std::os::unix::fs::chown(&env.0, Some(65534), Some(65534)).unwrap(); + child.uid(65534).gid(65534); + } + let output = child.output().unwrap(); + assert!( + output.status.success(), + "child failed: {}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + #[test] fn head_changes_and_unrelated_facts_do_not_silently_clear_blocks_or_asks() { let env = Fixture::new(); diff --git a/oxa/oxa-work/src/facts_io.rs b/oxa/oxa-work/src/facts_io.rs index 34029fd57..6bc3da81b 100644 --- a/oxa/oxa-work/src/facts_io.rs +++ b/oxa/oxa-work/src/facts_io.rs @@ -195,6 +195,15 @@ impl Root { self.sync()?; self.create(from, b"") } + pub(crate) fn durable(&self, leaf: &str) -> Result<()> { + let file = io( + self.options().read(true).write(true).open(self.path(leaf)), + "cannot open protected metadata", + )?; + private(&io(file.metadata(), "cannot inspect protected metadata")?, false)?; + io(file.sync_all(), "cannot sync protected metadata")?; + self.sync() + } fn sync(&self) -> Result<()> { sync_directory(&self.0) } diff --git a/oxa/oxa-work/src/lib.rs b/oxa/oxa-work/src/lib.rs index a79dd8df0..a5349c7e4 100644 --- a/oxa/oxa-work/src/lib.rs +++ b/oxa/oxa-work/src/lib.rs @@ -24,6 +24,7 @@ pub mod events; mod facts_io; pub mod incidents; pub mod situation; +pub mod standing; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] #[serde(deny_unknown_fields)] diff --git a/oxa/oxa-work/src/situation.rs b/oxa/oxa-work/src/situation.rs index fd9f67fef..bdae916e2 100644 --- a/oxa/oxa-work/src/situation.rs +++ b/oxa/oxa-work/src/situation.rs @@ -1,6 +1,6 @@ //! Bounded projection of typed facts. This module never reads or writes runner task state. use crate::Result; -use oxa_proto::work::{Event, Fact, Snapshot, TaskStep, MAX_ITEMS}; +use oxa_proto::work::{Ask, Event, Fact, Incident, Snapshot, TaskStep, MAX_ITEMS}; pub(crate) fn empty() -> Snapshot { Snapshot { @@ -73,23 +73,23 @@ pub(crate) fn apply(snapshot: &mut Snapshot, event: &Event) -> Result<()> { snapshot.blocked.push(block.clone()); } Fact::Unblocked(subject) => snapshot.blocked.retain(|row| &row.subject != subject), - Fact::AskOpened(ask) => { - if let Some(existing) = snapshot.asks.iter().find(|row| row.id == ask.id) { - if existing != ask { - return Err("ask id has conflicting contents".into()); - } - } else { - snapshot.asks.push(ask.clone()); - } - } + Fact::AskOpened(ask) => open_ask(snapshot, ask)?, Fact::AskClosed(ask) => snapshot.asks.retain(|row| row.id != ask.id), - Fact::Incident(incident) => { - if let Some(existing) = snapshot.incidents.iter().find(|row| row.id == incident.id) { - if existing != incident { - return Err("incident id has conflicting contents".into()); - } - } else { - snapshot.incidents.push(incident.clone()); + Fact::Incident(incident) => add_incident(snapshot, incident)?, + Fact::StandingChanged(change) => { + if change.revision <= snapshot.standing_revision { + return Err("stale standing projection revision".into()); + } + snapshot.standing_revision = change.revision; + snapshot.goal = change.goal.clone(); + if let Some(ask) = &change.ask_opened { + open_ask(snapshot, ask)?; + } + if let Some(ask) = &change.ask_closed { + snapshot.asks.retain(|row| row.id != ask.id); + } + if let Some(incident) = &change.incident { + add_incident(snapshot, incident)?; } } Fact::ExternalAcceptance(_) | Fact::Enqueued(_) | Fact::Mechanical(_) => {} @@ -130,6 +130,27 @@ pub(crate) fn apply(snapshot: &mut Snapshot, event: &Event) -> Result<()> { Ok(()) } +fn open_ask(snapshot: &mut Snapshot, ask: &Ask) -> Result<()> { + if let Some(existing) = snapshot.asks.iter().find(|row| row.id == ask.id) { + if existing != ask { + return Err("ask id has conflicting contents".into()); + } + } else { + snapshot.asks.push(ask.clone()); + } + Ok(()) +} +fn add_incident(snapshot: &mut Snapshot, incident: &Incident) -> Result<()> { + if let Some(existing) = snapshot.incidents.iter().find(|row| row.id == incident.id) { + if existing != incident { + return Err("incident id has conflicting contents".into()); + } + } else { + snapshot.incidents.push(incident.clone()); + } + Ok(()) +} + fn discard_history(snapshot: &mut Snapshot) -> bool { if !snapshot.landed.is_empty() { snapshot.landed.remove(0); diff --git a/oxa/oxa-work/src/standing.rs b/oxa/oxa-work/src/standing.rs new file mode 100644 index 000000000..3b9991c2a --- /dev/null +++ b/oxa/oxa-work/src/standing.rs @@ -0,0 +1,22 @@ +//! Owner standing data and action guards. Never reads or writes runner task state. +// Public Debug remains available without recursively exposing protected payloads. +macro_rules! private_debug { + ($($value:ty),+ $(,)?) => {$( + impl std::fmt::Debug for $value { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(concat!(stringify!($value), "()")) + } + } + )+}; +} +mod guard; +pub use guard::{Action, Refusal, RefusalReason, Scope, Subject}; +mod types; +pub use types::{ + Authority, Condition, Entry, EntryState, GateEvidence, Kind, Reminder, ReservedClass, ReviewTier, Rule, + Source, Value, +}; +mod store; +pub use store::{GuardError, Guarded, Read, Standing, Verification}; +mod asks; +pub use asks::{Answer, AnswerRequest, Ask, Choice, Proposal, Question, QuestionOption}; diff --git a/oxa/oxa-work/src/standing/asks.rs b/oxa/oxa-work/src/standing/asks.rs new file mode 100644 index 000000000..d221db52b --- /dev/null +++ b/oxa/oxa-work/src/standing/asks.rs @@ -0,0 +1,155 @@ +use super::{types, Rule, Scope, Source}; +use crate::Result; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct QuestionOption { + pub label: String, + pub detail: String, +} + +#[derive(Clone, PartialEq, Eq)] +pub struct Question { + pub scope: Scope, + pub question: String, + pub options: Vec, + pub recommended: String, + /// Unknown stays None; no default action or authority is inferred from prose here. + pub meanwhile: Option, + pub source: Source, +} +#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde( + tag = "kind", + content = "value", + rename_all = "snake_case", + deny_unknown_fields +)] +pub enum Choice { + Option(String), + Text(String), +} +#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Answer { + pub revision: u64, + pub question_revision: u64, + pub choice: Choice, + pub at: u64, + pub source: Source, + pub said: String, +} +pub struct AnswerRequest { + pub ask_id: String, + pub question_revision: u64, + pub choice: Choice, + pub source: Source, + pub said: String, +} +#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Proposal { + pub rule: Rule, + pub accept_label: String, +} +#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Ask { + pub id: String, + pub revision: u64, + pub scope: Scope, + pub question: String, + pub options: Vec, + pub recommended: String, + pub meanwhile: Option, + pub at: u64, + pub source: Source, + pub answer: Option, + pub proposal: Option, +} +impl Question { + pub(super) fn validate(&self) -> Result<()> { + self.scope.validate()?; + self.source.validate()?; + types::text(&self.question, 512)?; + types::text(&self.recommended, 64)?; + if let Some(value) = &self.meanwhile { + types::text(value, 512)?; + } + if !(2..=4).contains(&self.options.len()) { + return Err("ask requires 2 to 4 options".into()); + } + let mut labels = std::collections::HashSet::new(); + for option in &self.options { + types::text(&option.label, 64)?; + types::text(&option.detail, 512)?; + if !labels.insert(&option.label) { + return Err("ask option labels must be unique".into()); + } + } + if !labels.contains(&self.recommended) { + return Err("ask recommendation must name an option".into()); + } + Ok(()) + } +} +impl Ask { + pub(super) fn validate_choice(&self, choice: &Choice) -> Result<()> { + match choice { + Choice::Option(label) if self.options.iter().any(|option| option.label == *label) => Ok(()), + Choice::Option(_) => Err("answer does not name an ask option".into()), + Choice::Text(value) => types::text(value, 1024), + } + } + pub(super) fn validate(&self) -> Result<()> { + types::id(&self.id)?; + if self.revision == 0 { + return Err("ask revision must be positive".into()); + } + Question { + scope: self.scope.clone(), + question: self.question.clone(), + options: self.options.clone(), + recommended: self.recommended.clone(), + meanwhile: self.meanwhile.clone(), + source: self.source.clone(), + } + .validate()?; + if let Some(answer) = &self.answer { + if answer.question_revision != self.revision { + return Err("answer names a different question revision".into()); + } + answer.source.validate()?; + types::text(&answer.said, 1024)?; + self.validate_choice(&answer.choice)?; + } + if let Some(proposal) = &self.proposal { + proposal.rule.validate()?; + if proposal.rule.scope != self.scope + || !self + .options + .iter() + .any(|option| option.label == proposal.accept_label) + { + return Err("proposal is not bound to this question".into()); + } + } + Ok(()) + } + pub(super) fn fact(&self) -> oxa_proto::work::Ask { + let subject = match &self.scope { + Scope::PullRequest(pr) => oxa_proto::work::Subject::PullRequest(*pr), + Scope::Task(task) => oxa_proto::work::Subject::Task(task.clone()), + Scope::Host(host) => oxa_proto::work::Subject::Host(host.clone()), + Scope::Repository | Scope::Branch(_) | Scope::Path(_) => oxa_proto::work::Subject::Repository, + }; + oxa_proto::work::Ask { + id: self.id.clone(), + subject, + question: self.question.clone(), + } + } +} + +private_debug!(QuestionOption, Question, Choice, Answer, Proposal, Ask); diff --git a/oxa/oxa-work/src/standing/guard.rs b/oxa/oxa-work/src/standing/guard.rs new file mode 100644 index 000000000..6f1dd1de9 --- /dev/null +++ b/oxa/oxa-work/src/standing/guard.rs @@ -0,0 +1,237 @@ +use serde::{Deserialize, Serialize}; + +/// One side effect, never a worker or batch lifetime. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Action { + Admit, + Push, + Approve, + Enqueue, + Update, +} + +#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde( + tag = "kind", + content = "value", + rename_all = "snake_case", + deny_unknown_fields +)] +pub enum Scope { + Repository, + PullRequest(u64), + Task(String), + Branch(String), + Host(String), + Path(String), +} + +/// Identity resolved by the trusted frontend, not tool JSON. None means checked absence. +/// Supply the current PR whenever one exists; its head is deliberately not an identity field. +#[derive(Clone, Copy, Default)] +pub struct Subject<'a> { + pub pr: Option, + pub task: Option<&'a str>, + pub branch: Option<&'a str>, + pub host: Option<&'a str>, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RefusalReason { + Held, + Frozen, + InvalidSubject, +} + +#[derive(Clone, PartialEq, Eq)] +pub struct Refusal { + pub revision: u64, + pub rule_id: Option, + pub reason: RefusalReason, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ConstraintKind { + Hold, + Freeze, +} + +pub(super) struct Constraint<'a> { + pub rule_id: &'a str, + pub scope: &'a Scope, + pub kind: ConstraintKind, +} + +impl Scope { + fn matches(&self, subject: Subject<'_>) -> bool { + match self { + Self::Repository => true, + Self::PullRequest(pr) => subject.pr == Some(*pr), + Self::Task(task) => subject.task == Some(task.as_str()), + Self::Branch(branch) => subject.branch == Some(branch.as_str()), + Self::Host(host) => subject.host == Some(host.as_str()), + Self::Path(_) => false, // Path selectors are policy data, never hold identities. + } + } +} + +pub(super) fn check<'a>( + revision: u64, + constraints: impl IntoIterator>, + action: Action, + subject: Subject<'_>, +) -> Result<(), Refusal> { + let valid = subject.pr != Some(0) + && match action { + Action::Admit => { + subject.task.is_some_and(|id| !id.is_empty()) + && subject.branch.is_some_and(|branch| !branch.is_empty()) + } + Action::Push => subject.branch.is_some_and(|branch| !branch.is_empty()), + Action::Approve | Action::Enqueue | Action::Update => subject.pr.is_some(), + }; + if !valid { + return Err(Refusal { + revision, + rule_id: None, + reason: RefusalReason::InvalidSubject, + }); + } + for constraint in constraints { + let reason = match constraint.kind { + ConstraintKind::Hold => RefusalReason::Held, + ConstraintKind::Freeze if matches!(action, Action::Approve | Action::Enqueue) => { + RefusalReason::Frozen + } + ConstraintKind::Freeze => continue, + }; + if constraint.scope.matches(subject) { + return Err(Refusal { + revision, + rule_id: Some(constraint.rule_id.to_owned()), + reason, + }); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn subject() -> Subject<'static> { + Subject { + pr: Some(480), + task: Some("task"), + branch: Some("agent/task"), + host: Some("helper"), + } + } + + #[test] + fn a_pr_hold_refuses_every_effect_and_has_no_head_or_actor_bypass() { + let scope = Scope::PullRequest(480); + for action in [ + Action::Admit, + Action::Push, + Action::Approve, + Action::Enqueue, + Action::Update, + ] { + let result = check( + 7, + [Constraint { + rule_id: "R-7", + scope: &scope, + kind: ConstraintKind::Hold, + }], + action, + subject(), + ); + assert_eq!( + result, + Err(Refusal { + revision: 7, + rule_id: Some("R-7".into()), + reason: RefusalReason::Held + }) + ); + } + let different = Subject { + pr: Some(481), + ..subject() + }; + assert!(check( + 7, + [Constraint { + rule_id: "R-7", + scope: &scope, + kind: ConstraintKind::Hold + }], + Action::Update, + different + ) + .is_ok()); + } + + #[test] + fn freeze_refuses_only_approval_and_enqueue() { + let scope = Scope::Repository; + for action in [ + Action::Admit, + Action::Push, + Action::Approve, + Action::Enqueue, + Action::Update, + ] { + let result = check( + 3, + [Constraint { + rule_id: "R-3", + scope: &scope, + kind: ConstraintKind::Freeze, + }], + action, + subject(), + ); + assert_eq!( + result.is_err(), + matches!(action, Action::Approve | Action::Enqueue) + ); + } + } + + #[test] + fn pre_publication_admission_honors_task_branch_and_host_holds() { + let subject = Subject { + pr: None, + ..subject() + }; + for scope in [ + Scope::Task("task".into()), + Scope::Branch("agent/task".into()), + Scope::Host("helper".into()), + ] { + assert!(check( + 4, + [Constraint { + rule_id: "R-4", + scope: &scope, + kind: ConstraintKind::Hold + }], + Action::Admit, + subject + ) + .is_err()); + } + for action in [Action::Approve, Action::Enqueue, Action::Update] { + assert_eq!( + check(4, [], action, subject).unwrap_err().reason, + RefusalReason::InvalidSubject + ); + } + } +} + +private_debug!(Scope, Subject<'_>, Refusal); diff --git a/oxa/oxa-work/src/standing/store.rs b/oxa/oxa-work/src/standing/store.rs new file mode 100644 index 000000000..1fd625cc2 --- /dev/null +++ b/oxa/oxa-work/src/standing/store.rs @@ -0,0 +1,816 @@ +use super::guard::{self, Constraint, ConstraintKind}; +use super::types::{self, EntryState}; +use super::{ + Action, Answer, AnswerRequest, Ask, Authority, Choice, Entry, Kind, Proposal, Question, Refusal, Rule, + Scope, Subject, Value, +}; +use crate::{events::Facts, facts_io::Root, Result}; +use oxa_proto::work::{Checkpoint, Event, Fact, Incident, IncidentKind, StandingChanged}; +use serde::{Deserialize, Serialize}; +use std::{fmt, path::Path}; + +const FILE: &str = "standing.json"; +const LOCK: &str = ".standing.lock"; +const MAX_FILE: usize = 1024 * 1024; +const MAX_VIEW: usize = 256 * 1024; +const MAX_ACTIVE: usize = 128; +const HISTORY: usize = 16; + +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Read { + pub revision: u64, + pub at: u64, + pub entries: Vec, + pub asks: Vec, + pub history_truncated: bool, +} +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Pending { + after: Read, + observation: serde_json::Value, + // Keep evidence of a close until its fact commits, even if bounded history drops it. + #[serde(default, skip_serializing_if = "Option::is_none")] + trimmed_answer: Option>, +} +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Document { + version: u32, + current: Read, + pending: Option, +} +impl Document { + fn bytes(&self) -> Result> { + let bytes = serde_json::to_vec(self).map_err(|_| "cannot encode standing data")?; + if bytes.len() > MAX_FILE { + return Err("standing file capacity exceeded".into()); + } + Ok(bytes) + } +} +impl Pending { + fn difference(&self, before: &Read, incident: Option) -> Result { + let Some(closed) = self.trimmed_answer.as_deref() else { + return self.after.difference(before, incident); + }; + closed.validate()?; + let answer = closed.answer.as_ref().ok_or("trimmed ask has no owner answer")?; + let mut original = closed.clone(); + original.answer = None; + if !self.after.history_truncated + || self.after.asks.iter().any(|ask| ask.id == closed.id) + || !before.asks.contains(&original) + || answer.revision != self.after.revision + || answer.at != self.after.at + { + return Err("trimmed answer disagrees with the standing transition".into()); + } + let mut complete = self.after.clone(); + complete.asks.push(closed.clone()); + complete.difference(before, incident) + } +} +impl Read { + pub fn live_rules(&self) -> impl Iterator { + self.entries.iter().filter(|entry| entry.is_live()) + } + pub fn open_asks(&self) -> impl Iterator { + self.asks.iter().filter(|ask| ask.answer.is_none()) + } + fn validate(&self) -> Result<()> { + if self.entries.len() + self.asks.len() > MAX_ACTIVE + HISTORY { + return Err("standing entry capacity exceeded".into()); + } + let mut ids = std::collections::HashSet::new(); + let mut live = vec![]; + for entry in &self.entries { + entry.validate()?; + if !ids.insert(&entry.id) { + return Err("duplicate standing entry identity".into()); + } + if entry.is_live() { + if live + .iter() + .any(|(kind, scope)| *kind == entry.kind && *scope == &entry.scope) + { + return Err("conflicting live standing rules".into()); + } + live.push((entry.kind, &entry.scope)); + } + } + for ask in &self.asks { + ask.validate()?; + if !ids.insert(&ask.id) { + return Err("duplicate standing ask identity".into()); + } + if ask.revision > self.revision { + return Err("ask is ahead of standing revision".into()); + } + if ask + .answer + .as_ref() + .is_some_and(|answer| answer.revision <= ask.revision || answer.revision > self.revision) + { + return Err("answer is outside its standing revision".into()); + } + } + if live.len() + self.asks.iter().filter(|ask| ask.answer.is_none()).count() > MAX_ACTIVE { + return Err("active standing capacity exceeded".into()); + } + if serde_json::to_vec(self) + .map_err(|_| "cannot encode standing view")? + .len() + > MAX_VIEW + { + return Err("standing view byte capacity exceeded".into()); + } + Ok(()) + } + fn bounded(&mut self) -> Result<()> { + while self.entries.iter().filter(|entry| !entry.is_live()).count() + + self.asks.iter().filter(|ask| ask.answer.is_some()).count() + > HISTORY + { + self.discard_history()?; + } + while self.validate().is_err() { + self.discard_history()?; + } + self.validate() + } + fn discard_history(&mut self) -> Result<()> { + if let Some(index) = self.entries.iter().position(|entry| !entry.is_live()) { + self.entries.remove(index); + } else if let Some((index, _)) = self + .asks + .iter() + .enumerate() + .filter_map(|(index, ask)| ask.answer.as_ref().map(|answer| (index, answer.revision))) + .min_by_key(|(_, revision)| *revision) + { + self.asks.remove(index); + } else { + return Err("active standing capacity exceeded".into()); + } + self.history_truncated = true; + Ok(()) + } + fn next(&self, expected: u64, at: u64) -> Result { + if self.revision != expected { + return Err("standing revision changed; read it again".into()); + } + let mut next = self.clone(); + next.revision = self + .revision + .checked_add(1) + .ok_or("standing revision exhausted")?; + next.at = at; + Ok(next) + } + fn change(&self, incident: Option) -> StandingChanged { + let goal = self + .entries + .iter() + .find_map(|entry| match (&entry.kind, &entry.value) { + (Kind::Goal, Value::Text(value)) if entry.is_live() && entry.scope == Scope::Repository => { + Some(value.clone()) + } + _ => None, + }); + StandingChanged { + revision: self.revision, + goal, + ask_opened: None, + ask_closed: None, + incident, + } + } + fn difference(&self, before: &Read, incident: Option) -> Result { + let mut change = self.change(incident); + for ask in self + .asks + .iter() + .filter(|ask| ask.answer.is_none() && !before.asks.iter().any(|old| old.id == ask.id)) + { + if change.ask_opened.replace(ask.fact()).is_some() { + return Err("standing mutation opens multiple asks".into()); + } + } + for ask in before.asks.iter().filter(|ask| ask.answer.is_none()) { + if self + .asks + .iter() + .any(|new| new.id == ask.id && new.answer.is_some()) + { + if change + .ask_closed + .replace(oxa_proto::work::AskClosed { id: ask.id.clone() }) + .is_some() + { + return Err("standing mutation closes multiple asks".into()); + } + } else if !self.asks.iter().any(|new| new.id == ask.id) { + return Err("standing mutation drops an unanswered ask".into()); + } + } + Ok(change) + } +} + +#[derive(Clone)] +pub struct Standing { + root: Root, + facts: Facts, +} +pub enum GuardError { + Storage(String), + Refused(Refusal), +} +impl fmt::Display for GuardError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Storage(error) => write!(f, "standing data unavailable: {error}"), + Self::Refused(refusal) => write!( + f, + "standing revision {} refuses this action: {:?}", + refusal.revision, refusal.reason + ), + } + } +} +impl std::error::Error for GuardError {} +impl From for GuardError { + fn from(error: String) -> Self { + Self::Storage(error) + } +} +pub struct Guarded { + pub revision: u64, + pub result: Result, +} +pub struct Verification { + pub revision: u64, + pub scope: Scope, + pub value: Value, + pub at: u64, + pub evidence: String, +} +private_debug!(Read, Standing, GuardError); + +impl Standing { + /// Explicit owner initialization at a protected per-repository configuration root. + pub fn initialize(root: &Path, authority: Authority, facts: Facts) -> Result { + if authority != Authority::Owner { + return Err("owner initialization required".into()); + } + let root = Root::open(root, true)?; + let _lock = root.lock(LOCK)?; + if root.exists(FILE)? { + return Err("standing data already exists".into()); + } + if facts.situation()?.standing_revision != 0 { + return Err("standing facts already exist".into()); + } + facts.reserve_standing()?; + let document = Document { + version: 1, + current: Read { + revision: 0, + at: 0, + entries: vec![], + asks: vec![], + history_truncated: false, + }, + pending: None, + }; + root.create(FILE, &document.bytes()?)?; + Ok(Self { root, facts }) + } + pub fn open(root: &Path, facts: Facts) -> Result { + let standing = Self { + root: Root::open(root, false)?, + facts, + }; + standing.read()?; + standing.facts.reserve_standing()?; + Ok(standing) + } + pub fn read(&self) -> Result { + let _lock = self.root.lock(LOCK)?; + self.load() + } + /// One revision-consistent view for cards; never join independently read revisions. + pub fn read_facts(&self) -> Result<(Read, oxa_proto::work::Snapshot)> { + let _lock = self.root.lock(LOCK)?; + self.load_facts() + } + fn load(&self) -> Result { + self.load_facts().map(|(read, _)| read) + } + fn load_facts(&self) -> Result<(Read, oxa_proto::work::Snapshot)> { + let mut document: Document = serde_json::from_slice(&self.root.read(FILE, MAX_FILE)?) + .map_err(|_| "invalid standing document")?; + if document.version != 1 { + return Err("unsupported standing version".into()); + } + document.current.validate()?; + if let Some(pending) = &document.pending { + pending.after.validate()?; + if document.current.revision.checked_add(1) != Some(pending.after.revision) { + return Err("invalid pending standing revision".into()); + } + let event = Event::from_json( + &serde_json::to_vec(&pending.observation).map_err(|_| "invalid standing observation")?, + ) + .map_err(|error| error.to_string())?; + if event.checkpoint.source != "standing" + || event.checkpoint.revision != pending.after.revision + || event.at_ms != pending.after.at + { + return Err("pending standing identity disagrees".into()); + } + let Fact::StandingChanged(change) = &event.fact else { + return Err("invalid standing observation kind".into()); + }; + if change != &pending.difference(&document.current, change.incident.clone())? { + return Err("pending standing projection disagrees".into()); + } + // A prior rename may be visible after directory sync failed. Establish the + // prepared policy's durability before committing its separately stored fact. + self.root.durable(FILE)?; + self.facts + .append_prepared(event.checkpoint, event.at_ms, event.fact, |_| Ok(()))?; + document.current = pending.after.clone(); + document.pending = None; + self.root.atomic(FILE, &document.bytes()?)?; + } + // Establish durability after a prior post-rename sync failure before authorizing work. + self.root.durable(FILE)?; + let situation = self.facts.cancel_unprepared_standing( + document.current.revision, + document.current.change(None).goal.as_deref(), + )?; + Ok((document.current, situation)) + } + fn save(&self, before: Read, mut after: Read, incident: Option) -> Result { + let change = after.difference(&before, incident)?; + let closed = change + .ask_closed + .as_ref() + .and_then(|closed| after.asks.iter().find(|ask| ask.id == closed.id)) + .cloned(); + after.bounded()?; + let trimmed_answer = closed + .filter(|closed| !after.asks.iter().any(|ask| ask.id == closed.id)) + .map(Box::new); + let fact = Fact::StandingChanged(change); + let mut prepared = false; + self.facts.append_prepared( + Checkpoint { + source: "standing".into(), + revision: after.revision, + }, + after.at, + fact, + |event| { + let observation = + serde_json::from_slice(&event.to_json().map_err(|error| error.to_string())?) + .map_err(|_| "cannot encode standing observation")?; + let document = Document { + version: 1, + current: before, + pending: Some(Pending { + after: after.clone(), + observation, + trimmed_answer, + }), + }; + self.root.atomic(FILE, &document.bytes()?)?; + prepared = true; + Ok(()) + }, + )?; + if !prepared { + return Err("standing facts revision was already used".into()); + } + let document = Document { + version: 1, + current: after.clone(), + pending: None, + }; + self.root.atomic(FILE, &document.bytes()?)?; + Ok(after) + } + pub fn rule(&self, expected: u64, authority: Authority, at: u64, request: Rule) -> Result { + request.validate()?; + let _lock = self.root.lock(LOCK)?; + let before = self.load()?; + let mut after = before.next(expected, at)?; + let entry = Self::stage_rule(&mut after, authority, at, request)?; + self.save(before, after, None)?; + Ok(entry) + } + fn stage_rule(after: &mut Read, authority: Authority, at: u64, request: Rule) -> Result { + request.validate()?; + let target = after + .entries + .iter() + .position(|entry| entry.is_live() && entry.kind == request.kind && entry.scope == request.scope); + let conversion = if target.is_none() && request.kind != Kind::Note { + after.entries.iter().position(|entry| { + entry.is_live() + && entry.kind == Kind::Note + && entry.scope == request.scope + && request.supersedes.as_deref() == Some(&entry.id) + }) + } else { + None + }; + if conversion.is_some() && authority != Authority::Owner { + return Err("owner confirmation required to convert an advisory note".into()); + } + let prior = target.or(conversion).map(|index| &mut after.entries[index]); + if authority != Authority::Owner { + let owner_required = match (&request.kind, &request.value, prior.as_deref()) { + (Kind::Reserve, _, _) => true, + ( + Kind::Budget, + Value::Budget { + daily_usd_micros: new, + }, + Some(Entry { + value: + Value::Budget { + daily_usd_micros: old, + }, + .. + }), + ) => new > old, + (Kind::Budget, Value::Budget { daily_usd_micros: 0 }, None) => false, + (Kind::Budget, _, _) => true, + ( + Kind::Gate, + Value::Gate { + tier: new_tier, + evidence: new, + }, + Some(Entry { + value: + Value::Gate { + tier: old_tier, + evidence: old, + }, + .. + }), + ) => new_tier < old_tier || !old.iter().all(|required| new.contains(required)), + (Kind::Gate, _, _) => true, + _ => false, + }; + if owner_required { + return Err("this standing change requires owner authority; propose it instead".into()); + } + } + let mut protection = authority; + if let Some(prior) = prior { + if request.supersedes.as_deref() != Some(&prior.id) { + return Err("live standing collision requires named supersession".into()); + } + let releasing = matches!( + request.value, + Value::Retired + | Value::Constraint { + active: false, + until: None + } + ); + if matches!(request.kind, Kind::Hold | Kind::Freeze) && prior.authority == Authority::Owner { + if authority != Authority::Owner && prior.value != request.value { + return Err("only the owner changes this release condition".into()); + } + if releasing && authority != Authority::Owner { + return Err("only the owner releases this constraint".into()); + } + protection = Authority::Owner; + } + prior.state = EntryState::Superseded; + } else { + if request.supersedes.is_some() { + return Err("superseded standing entry is not live".into()); + } + if matches!( + request.value, + Value::Retired + | Value::Constraint { + active: false, + until: None + } + ) { + return Err("no live standing entry to release".into()); + } + } + let entry = Entry { + id: format!("R-{}", after.revision), + kind: request.kind, + scope: request.scope, + value: request.value, + said: request.said, + at, + said_by: authority, + source: request.source, + supersedes: request.supersedes, + state: EntryState::Stored, + reminders: 0, + last_reminder: None, + authority: protection, + }; + after.entries.push(entry.clone()); + Ok(entry) + } + pub fn remind( + &self, + expected: u64, + authority: Authority, + entry_id: &str, + at: u64, + source: super::Source, + ) -> Result { + if authority != Authority::Owner { + return Err("owner reminder context required".into()); + } + source.validate()?; + let _lock = self.root.lock(LOCK)?; + let before = self.load()?; + let mut after = before.next(expected, at)?; + let entry = after + .entries + .iter_mut() + .find(|entry| entry.id == entry_id && entry.is_live()) + .ok_or("standing entry is not live")?; + entry.reminders = entry + .reminders + .checked_add(1) + .ok_or("standing reminder count exhausted")?; + entry.last_reminder = Some(super::Reminder { at, source }); + let result = entry.clone(); + let subject = match &entry.scope { + Scope::PullRequest(pr) => oxa_proto::work::Subject::PullRequest(*pr), + Scope::Task(task) => oxa_proto::work::Subject::Task(task.clone()), + Scope::Host(host) => oxa_proto::work::Subject::Host(host.clone()), + Scope::Repository | Scope::Branch(_) | Scope::Path(_) => oxa_proto::work::Subject::Repository, + }; + let incident = Incident { + id: format!("{}-reminded-{}", entry.id, after.revision), + subject, + kind: IncidentKind::RuleReminder, + evidence: None, + }; + self.save(before, after, Some(incident))?; + Ok(result) + } + /// A trusted frontend checker supplies actual runtime values/evidence; tool JSON cannot. + pub fn verify( + &self, + expected: u64, + entry_id: &str, + check: impl FnOnce(&Entry) -> Result, + ) -> Result { + let _lock = self.root.lock(LOCK)?; + let before = self.load()?; + if before.revision != expected { + return Err("standing revision changed; read it again".into()); + } + let mut after = before.clone(); + let entry = after + .entries + .iter_mut() + // A released or retired rule stays Stored; never claim it was applied. + .find(|entry| entry.id == entry_id && entry.is_live()) + .ok_or("standing entry is not live")?; + let verified = check(entry)?; + types::text(&verified.evidence, 256)?; + if verified.revision != expected || verified.scope != entry.scope || verified.value != entry.value { + return Err("runtime evidence does not match the standing rule".into()); + } + if matches!(entry.state, EntryState::Applied { .. }) { + return Ok(entry.clone()); + } + entry.state = EntryState::Applied { + verified_at: verified.at, + evidence: verified.evidence, + }; + let result = entry.clone(); + after.revision = expected.checked_add(1).ok_or("standing revision exhausted")?; + after.at = verified.at; + self.save(before, after, None)?; + Ok(result) + } + pub fn ask(&self, expected: u64, at: u64, request: Question) -> Result { + self.open_question(expected, at, request, None) + } + pub fn propose( + &self, + expected: u64, + at: u64, + rule: Rule, + question: Question, + accept_label: String, + ) -> Result { + rule.validate()?; + self.open_question(expected, at, question, Some(Proposal { rule, accept_label })) + } + fn open_question( + &self, + expected: u64, + at: u64, + request: Question, + proposal: Option, + ) -> Result { + request.validate()?; + let _lock = self.root.lock(LOCK)?; + let before = self.load()?; + let mut after = before.next(expected, at)?; + let ask = Ask { + id: format!("standing:A-{}", after.revision), + revision: after.revision, + scope: request.scope, + question: request.question, + options: request.options, + recommended: request.recommended, + meanwhile: request.meanwhile, + at, + source: request.source, + answer: None, + proposal, + }; + ask.validate()?; + after.asks.push(ask.clone()); + self.save(before, after, None)?; + Ok(ask) + } + /// Only acceptance of the exact bound proposal changes a rule. Generic answers grant no + /// permission, and storing an accepted rule never claims it is applied to a runtime. + pub fn answer( + &self, + expected: u64, + authority: Authority, + at: u64, + request: AnswerRequest, + ) -> Result { + if authority != Authority::Owner { + return Err("only the owner answers standing asks".into()); + } + request.source.validate()?; + types::text(&request.said, 1024)?; + let _lock = self.root.lock(LOCK)?; + let before = self.load()?; + let mut after = before.next(expected, at)?; + let ask = after + .asks + .iter_mut() + .find(|ask| ask.id == request.ask_id) + .ok_or("standing ask was not found")?; + if ask.revision != request.question_revision || ask.answer.is_some() { + return Err("standing question changed or was already answered".into()); + } + ask.validate_choice(&request.choice)?; + let accepted = match (&ask.proposal, &request.choice) { + (Some(proposal), Choice::Option(label)) if *label == proposal.accept_label => { + Some(proposal.rule.clone()) + } + _ => None, + }; + let owner_source = request.source.clone(); + let owner_words = request.said.clone(); + ask.answer = Some(Answer { + revision: after.revision, + question_revision: request.question_revision, + choice: request.choice, + at, + source: request.source, + said: request.said, + }); + let result = ask.clone(); + if let Some(mut rule) = accepted { + rule.source = owner_source; + rule.said = owner_words; + Self::stage_rule(&mut after, Authority::Owner, at, rule)?; + } + self.save(before, after, None)?; + Ok(result) + } + pub fn is_held(&self, pr: u64) -> Result> { + if pr == 0 { + return Err("PR number must be positive".into()); + } + let read = self.read()?; + Ok(read + .entries + .iter() + .find(|entry| { + entry.is_live() + && entry.kind == Kind::Hold + && (entry.scope == Scope::Repository || entry.scope == Scope::PullRequest(pr)) + }) + .map(|entry| entry.id.clone())) + } + /// Verify a named immutable merge through a frontend-owned checker. The original condition + /// authorizes release; model prose and changed PR heads never supply this proof. + pub fn release_when( + &self, + expected: u64, + entry_id: &str, + at: u64, + check: impl FnOnce(&super::Condition) -> Result>, + ) -> Result> { + let _lock = self.root.lock(LOCK)?; + let before = self.load()?; + if before.revision != expected { + return Err("standing revision changed; read it again".into()); + } + let entry = before + .entries + .iter() + .find(|entry| entry.id == entry_id && entry.is_live()) + .ok_or("standing entry is not live")?; + let Value::Constraint { + active: true, + until: Some(condition), + } = &entry.value + else { + return Err("standing entry has no release condition".into()); + }; + let Some(observation) = check(condition)? else { + return Ok(None); + }; + let Fact::PrMerged(proof) = &observation.fact else { + return Err("condition requires a merge observation".into()); + }; + let super::Condition::PrMerged(pr) = condition; + if *pr != proof.pr.number { + return Err("merge proof names a different condition".into()); + } + let previous = observation + .seq + .checked_sub(1) + .ok_or("invalid merge observation sequence")?; + let page = self.facts.events_after(previous, 1)?; + if page.gap || page.events.first() != Some(&observation) { + return Err("merge observation is not retained in this facts store".into()); + } + let mut after = before.next(expected, at)?; + let rule = Rule { + kind: entry.kind, + scope: entry.scope.clone(), + value: Value::Constraint { + active: false, + until: None, + }, + said: entry.said.clone(), + source: entry.source.clone(), + supersedes: Some(entry.id.clone()), + }; + let mut released = Self::stage_rule(&mut after, entry.authority, at, rule)?; + released.said_by = entry.said_by; + released.state = EntryState::Applied { + verified_at: at, + evidence: format!("merged-pr:{pr}:{}", proof.merge_commit), + }; + *after.entries.last_mut().expect("new release entry") = released.clone(); + self.save(before, after, None)?; + Ok(Some(released)) + } + pub fn with_guard( + &self, + action: Action, + subject: Subject<'_>, + effect: impl FnOnce(&Read) -> Result, + ) -> std::result::Result, GuardError> { + let _lock = self.root.lock(LOCK)?; + let read = self.load()?; + let constraints = read.entries.iter().filter_map(|entry| { + if !entry.is_live() { + return None; + } + let kind = match entry.kind { + Kind::Hold => ConstraintKind::Hold, + Kind::Freeze => ConstraintKind::Freeze, + _ => return None, + }; + Some(Constraint { + rule_id: &entry.id, + scope: &entry.scope, + kind, + }) + }); + guard::check(read.revision, constraints, action, subject).map_err(GuardError::Refused)?; + Ok(Guarded { + revision: read.revision, + result: effect(&read), + }) + } +} + +#[cfg(test)] +mod tests; diff --git a/oxa/oxa-work/src/standing/store/tests.rs b/oxa/oxa-work/src/standing/store/tests.rs new file mode 100644 index 000000000..3a1d18f90 --- /dev/null +++ b/oxa/oxa-work/src/standing/store/tests.rs @@ -0,0 +1,1441 @@ +use super::*; +use std::{ + fs, + os::unix::fs::DirBuilderExt, + path::PathBuf, + sync::atomic::{AtomicU64, AtomicUsize, Ordering}, +}; + +struct Fixture(PathBuf); +impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + loop { + let root = std::env::temp_dir().join(format!( + "oxa-standing-test-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + match fs::DirBuilder::new().mode(0o700).create(&root) { + Ok(()) => return Self(root), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("create private fixture: {error}"), + } + } + } + fn facts(&self) -> Facts { + Facts::initialize(&self.0.join("facts")).unwrap() + } + fn standing(&self, facts: Facts) -> Standing { + Standing::initialize(&self.0.join("standing"), Authority::Owner, facts).unwrap() + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} +fn hold(active: bool, supersedes: Option<&str>) -> Rule { + Rule { + kind: Kind::Hold, + scope: Scope::PullRequest(480), + value: Value::Constraint { active, until: None }, + said: "Hold this PR until released".into(), + source: super::super::Source::Command { + command: "hold 480".into(), + }, + supersedes: supersedes.map(str::to_owned), + } +} +fn subject() -> Subject<'static> { + Subject { + pr: Some(480), + task: Some("task"), + branch: Some("agent/task"), + host: Some("helper"), + } +} + +#[test] +fn debug_never_formats_private_standing_text_or_nested_payloads() { + let fixture = Fixture::new(); + let standing = fixture.standing(fixture.facts()); + let marker = "synthetic-private-standing-value"; + let mut rule = hold(true, None); + rule.said = marker.into(); + rule.source = super::super::Source::Command { + command: marker.into(), + }; + let entry = standing.rule(0, Authority::Owner, 1, rule.clone()).unwrap(); + let mut request = question(); + request.question = marker.into(); + request.meanwhile = Some(marker.into()); + let ask = standing.ask(1, 2, request.clone()).unwrap(); + let answered = standing.answer(2, Authority::Owner, 3, answer(&ask)).unwrap(); + let read = standing.read().unwrap(); + for output in [ + format!("{read:?}"), + format!("{entry:?}"), + format!("{rule:?}"), + format!("{:?}", rule.source), + format!("{request:?}"), + format!("{answered:?}"), + format!("{:?}", Value::Text(marker.into())), + format!("{:?}", Scope::Branch(marker.into())), + format!("{:?}", super::super::Choice::Text(marker.into())), + format!( + "{:?}", + super::super::QuestionOption { + label: marker.into(), + detail: marker.into() + } + ), + ] { + assert!(!output.contains(marker), "Debug exposed private standing data"); + } + assert_eq!(read.entries[0].said, marker); + assert!(serde_json::to_string(&read).unwrap().contains(marker)); +} + +#[test] +fn ordinary_facts_cannot_publish_standing_revisions() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + let change = Fact::StandingChanged(StandingChanged { + revision: 1, + goal: None, + ask_opened: None, + ask_closed: None, + incident: None, + }); + assert!(facts + .append( + Checkpoint { + source: "other".into(), + revision: 1 + }, + 1, + change + ) + .is_err()); + assert_eq!(facts.situation().unwrap().standing_revision, 0); + standing.rule(0, Authority::Owner, 2, hold(true, None)).unwrap(); + assert_eq!(standing.read().unwrap().revision, 1); +} + +#[test] +fn standing_asks_do_not_collide_with_another_producers_common_id() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + let external = oxa_proto::work::Ask { + id: "A-1".into(), + subject: oxa_proto::work::Subject::Repository, + question: "A separate producer question".into(), + }; + facts + .append( + Checkpoint { + source: "runner".into(), + revision: 1, + }, + 1, + Fact::AskOpened(external.clone()), + ) + .unwrap(); + let ask = standing.ask(0, 2, question()).unwrap(); + assert_ne!(ask.id, external.id); + standing.answer(1, Authority::Owner, 3, answer(&ask)).unwrap(); + assert_eq!(facts.situation().unwrap().asks, [external]); +} + +fn fill_fact_sources(facts: &Facts, count: usize) { + for index in 0..count { + facts + .append( + Checkpoint { + source: format!("producer-{index}"), + revision: 1, + }, + index as u64, + Fact::Unblocked(oxa_proto::work::Subject::Repository), + ) + .unwrap(); + } +} + +#[test] +fn initialization_reserves_source_capacity_before_the_first_rule() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + fill_fact_sources(&facts, 15); + let standing = fixture.standing(facts.clone()); + let late = facts.append( + Checkpoint { + source: "late-producer".into(), + revision: 1, + }, + 16, + Fact::Unblocked(oxa_proto::work::Subject::Repository), + ); + assert!( + late.is_err(), + "ordinary producer consumed the reserved standing slot" + ); + assert_eq!(facts.situation().unwrap().as_of_seq, 15); + standing.rule(0, Authority::Owner, 17, hold(true, None)).unwrap(); + assert_eq!(facts.situation().unwrap().as_of_seq, 16); + assert_eq!(standing.read().unwrap().revision, 1); +} + +#[test] +fn initialization_refuses_an_already_full_nonstanding_source_table() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + fill_fact_sources(&facts, 16); + let root = fixture.0.join("standing"); + assert!(Standing::initialize(&root, Authority::Owner, facts.clone()).is_err()); + assert!(!root.join("standing.json").exists()); + assert_eq!(facts.situation().unwrap().as_of_seq, 16); +} + +#[test] +fn a_fresh_hold_blocks_each_effect_in_a_handle_opened_before_it() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + let old_handle = Standing::open(&fixture.0.join("standing"), facts.clone()).unwrap(); + let effects = AtomicUsize::new(0); + old_handle + .with_guard(Action::Update, subject(), |_| { + effects.fetch_add(1, Ordering::SeqCst); + Ok(()) + }) + .unwrap() + .result + .unwrap(); + let entry = standing.rule(0, Authority::Owner, 10, hold(true, None)).unwrap(); + assert_eq!(entry.state, EntryState::Stored); + for action in [ + Action::Admit, + Action::Push, + Action::Approve, + Action::Enqueue, + Action::Update, + ] { + let result = old_handle.with_guard(action, subject(), |_| { + effects.fetch_add(1, Ordering::SeqCst); + Ok(()) + }); + assert!(matches!( + result, + Err(GuardError::Refused(Refusal { + reason: super::super::RefusalReason::Held, + revision: 1, + .. + })) + )); + } + assert_eq!(effects.load(Ordering::SeqCst), 1); + assert_eq!(old_handle.is_held(480).unwrap(), Some(entry.id)); + assert_eq!(facts.situation().unwrap().standing_revision, 1); +} + +#[test] +fn supersession_cannot_launder_owner_hold_authority() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts); + let first = standing.rule(0, Authority::Owner, 1, hold(true, None)).unwrap(); + assert!(standing.rule(1, Authority::Lead, 2, hold(false, None)).is_err()); + let second = standing + .rule(1, Authority::Lead, 2, hold(true, Some(&first.id))) + .unwrap(); + assert!(standing + .rule(2, Authority::Lead, 3, hold(false, Some(&second.id))) + .is_err()); + let mut retired = hold(false, Some(&second.id)); + retired.value = Value::Retired; + assert!(standing.rule(2, Authority::Lead, 3, retired).is_err()); + assert_eq!(standing.read().unwrap().revision, 2); + standing + .rule(2, Authority::Owner, 3, hold(false, Some(&second.id))) + .unwrap(); + assert!(standing.is_held(480).unwrap().is_none()); + assert!(standing.rule(2, Authority::Owner, 4, hold(true, None)).is_err()); + standing + .with_guard(Action::Approve, subject(), |read| Ok(read.revision)) + .unwrap() + .result + .unwrap(); +} + +#[test] +fn missing_corrupt_or_symlinked_policy_never_authorizes_the_callback() { + for poison in ["missing", "corrupt", "symlink"] { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + let path = fixture.0.join("standing/standing.json"); + fs::remove_file(&path).unwrap(); + let target = fixture.0.join("outside"); + fs::write(&target, b"keep outside").unwrap(); + match poison { + "missing" => {} + "corrupt" => fs::write(&path, b"PRIVATE_REJECTED_CONTENT").unwrap(), + "symlink" => std::os::unix::fs::symlink(&target, &path).unwrap(), + _ => unreachable!(), + } + let effects = AtomicUsize::new(0); + let result = standing.with_guard(Action::Update, subject(), |_| { + effects.fetch_add(1, Ordering::SeqCst); + Ok(()) + }); + assert!(matches!(result, Err(GuardError::Storage(_)))); + assert_eq!(effects.load(Ordering::SeqCst), 0); + assert_eq!(fs::read(&target).unwrap(), b"keep outside"); + assert!(Standing::open(&fixture.0.join("standing"), facts).is_err()); + } +} + +#[test] +fn pending_revisions_recover_before_or_after_the_fact_without_duplicate_delivery() { + for appended in [false, true] { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + let before = standing.read().unwrap(); + let mut after = before.next(0, 9).unwrap(); + let request = hold(true, None); + after.entries.push(Entry { + id: "R-1".into(), + kind: request.kind, + scope: request.scope, + value: request.value, + said: request.said, + at: 9, + said_by: Authority::Owner, + source: request.source, + supersedes: None, + state: EntryState::Stored, + reminders: 0, + last_reminder: None, + authority: Authority::Owner, + }); + let event = Event { + seq: 1, + at_ms: 9, + checkpoint: Checkpoint { + source: "standing".into(), + revision: 1, + }, + fact: Fact::StandingChanged(after.change(None)), + }; + let observation = serde_json::from_slice(&event.to_json().unwrap()).unwrap(); + if appended { + facts + .append_prepared(event.checkpoint, event.at_ms, event.fact, |_| Ok(())) + .unwrap(); + } + let document = Document { + version: 1, + current: before, + pending: Some(Pending { + after, + observation, + trimmed_answer: None, + }), + }; + standing.root.atomic(FILE, &document.bytes().unwrap()).unwrap(); + let reopened = Standing::open(&fixture.0.join("standing"), facts.clone()).unwrap(); + assert_eq!(reopened.read().unwrap().revision, 1); + assert_eq!(reopened.is_held(480).unwrap().as_deref(), Some("R-1")); + assert_eq!(facts.events_after(0, 64).unwrap().events.len(), 1); + assert_eq!(facts.situation().unwrap().standing_revision, 1); + } +} + +#[test] +fn applied_requires_matching_runtime_value_scope_and_revision() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts); + let request = Rule { + kind: Kind::Goal, + scope: Scope::Repository, + value: Value::Text("Finish Rust".into()), + said: "Finish Rust".into(), + source: super::super::Source::Command { + command: "goal Finish Rust".into(), + }, + supersedes: None, + }; + let entry = standing.rule(0, Authority::Owner, 1, request).unwrap(); + let observed = fixture.0.join("runtime.json"); + fs::write(&observed, br#"{"goal":"different"}"#).unwrap(); + let checker = |entry: &Entry| -> Result { + let actual: serde_json::Value = serde_json::from_slice(&fs::read(&observed).unwrap()).unwrap(); + Ok(Verification { + revision: 1, + scope: entry.scope.clone(), + value: Value::Text(actual["goal"].as_str().unwrap().into()), + at: 2, + evidence: "synthetic-runtime:1".into(), + }) + }; + assert!(standing.verify(1, &entry.id, checker).is_err()); + assert_eq!(standing.read().unwrap().entries[0].state, EntryState::Stored); + fs::write(&observed, br#"{"goal":"Finish Rust"}"#).unwrap(); + let applied = standing.verify(1, &entry.id, checker).unwrap(); + assert!(matches!( + applied.state, + EntryState::Applied { verified_at: 2, .. } + )); + assert_eq!(standing.read().unwrap().revision, 2); +} + +#[test] +fn verify_refuses_released_and_retired_rules() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts); + let held = standing.rule(0, Authority::Owner, 1, hold(true, None)).unwrap(); + let released = standing + .rule(1, Authority::Owner, 2, hold(false, Some(&held.id))) + .unwrap(); + let request = Rule { + kind: Kind::Note, + scope: Scope::Repository, + value: Value::Text("Keep notes brief".into()), + said: "Keep notes brief".into(), + source: super::super::Source::Command { + command: "note".into(), + }, + supersedes: None, + }; + let note = standing.rule(2, Authority::Owner, 3, request).unwrap(); + let request = Rule { + kind: Kind::Note, + scope: Scope::Repository, + value: Value::Retired, + said: "Retire the note".into(), + source: super::super::Source::Command { + command: "retire".into(), + }, + supersedes: Some(note.id.clone()), + }; + let retired = standing.rule(3, Authority::Owner, 4, request).unwrap(); + assert!(!released.is_live() && !retired.is_live()); + for entry in [&released, &retired] { + let result = standing.verify(4, &entry.id, |entry: &Entry| { + Ok(Verification { + revision: 4, + scope: entry.scope.clone(), + value: entry.value.clone(), + at: 5, + evidence: "synthetic-runtime:4".into(), + }) + }); + assert!(result.is_err(), "verified a non-live rule: {}", entry.id); + } + let read = standing.read().unwrap(); + assert_eq!(read.revision, 4); + // The refused verification leaves the released and retired records as stored; only the + // records they supersede carry `Superseded`. + for refused in [&released.id, &retired.id] { + let entry = read + .entries + .iter() + .find(|entry| &entry.id == refused) + .expect("refused entry is still recorded"); + assert_eq!(entry.state, EntryState::Stored); + } +} + +#[test] +fn reminders_create_incidents_and_offer_without_changing_advisory_rules() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + let request = Rule { + kind: Kind::Note, + scope: Scope::Repository, + value: Value::Text("Keep it brief".into()), + said: "Keep it brief".into(), + source: super::super::Source::Command { + command: "note Keep it brief".into(), + }, + supersedes: None, + }; + let note = standing.rule(0, Authority::Owner, 1, request).unwrap(); + assert!(!standing + .remind( + 1, + Authority::Owner, + ¬e.id, + 2, + super::super::Source::Command { + command: "remind".into() + } + ) + .unwrap() + .needs_conversion_offer()); + assert!(standing + .remind( + 2, + Authority::Owner, + ¬e.id, + 3, + super::super::Source::Command { + command: "remind".into() + } + ) + .unwrap() + .needs_conversion_offer()); + let read = standing.read().unwrap(); + assert_eq!(read.entries[0].kind, Kind::Note); + assert_eq!(read.entries[0].reminders, 2); + assert_eq!(facts.situation().unwrap().incidents.len(), 2); +} + +fn question() -> Question { + Question { + scope: Scope::PullRequest(480), + question: "Release this hold?".into(), + options: vec![ + super::super::QuestionOption { + label: "Keep".into(), + detail: "Keep the hold".into(), + }, + super::super::QuestionOption { + label: "Release".into(), + detail: "Request an explicit release".into(), + }, + ], + recommended: "Keep".into(), + meanwhile: None, + source: super::super::Source::Command { + command: "ask 480".into(), + }, + } +} +fn answer(ask: &Ask) -> super::super::AnswerRequest { + super::super::AnswerRequest { + ask_id: ask.id.clone(), + question_revision: ask.revision, + choice: super::super::Choice::Option("Release".into()), + source: super::super::Source::Command { + command: "decide Release".into(), + }, + said: "Release".into(), + } +} + +#[test] +fn answers_are_owner_bound_to_a_question_and_do_not_release_holds() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + standing.rule(0, Authority::Owner, 1, hold(true, None)).unwrap(); + let ask = standing.ask(1, 2, question()).unwrap(); + assert!(ask.meanwhile.is_none()); + assert_eq!(facts.situation().unwrap().asks[0].id, ask.id); + assert!(standing.answer(2, Authority::Lead, 3, answer(&ask)).is_err()); + let mut stale = answer(&ask); + stale.question_revision += 1; + assert!(standing.answer(2, Authority::Owner, 3, stale).is_err()); + let mut invalid = answer(&ask); + invalid.choice = super::super::Choice::Option("missing".into()); + assert!(standing.answer(2, Authority::Owner, 3, invalid).is_err()); + let result = standing.answer(2, Authority::Owner, 3, answer(&ask)).unwrap(); + assert!(result.answer.is_some()); + assert!(facts.situation().unwrap().asks.is_empty()); + assert!(standing.is_held(480).unwrap().is_some()); + assert!(standing + .with_guard(Action::Enqueue, subject(), |_| Ok(())) + .is_err()); + assert!(standing.answer(3, Authority::Owner, 4, answer(&ask)).is_err()); +} + +fn fill_view_with_open_asks(standing: &Standing) -> Vec { + standing.rule(0, Authority::Owner, 1, hold(true, None)).unwrap(); + let initial = standing.read().unwrap(); + let mut request = question(); + request.question = "\"".repeat(512); + request.meanwhile = Some("\"".repeat(512)); + request.source = super::super::Source::Command { + command: "\"".repeat(512), + }; + request.options.push(super::super::QuestionOption { + label: "Later".into(), + detail: String::new(), + }); + request.options.push(super::super::QuestionOption { + label: "Reconsider".into(), + detail: String::new(), + }); + for width in (1..=512).rev() { + for option in &mut request.options { + option.detail = "\"".repeat(width); + } + let mut projected = initial.clone(); + projected.revision = 41; + projected.at = 41; + projected.asks = (2..=41) + .map(|revision| Ask { + id: format!("A-{revision}"), + revision, + scope: request.scope.clone(), + question: request.question.clone(), + options: request.options.clone(), + recommended: request.recommended.clone(), + meanwhile: request.meanwhile.clone(), + at: revision, + source: request.source.clone(), + answer: None, + proposal: None, + }) + .collect(); + if serde_json::to_vec(&projected).unwrap().len() <= MAX_VIEW - 1024 { + break; + } + } + let asks: Vec<_> = (2..=41) + .map(|revision| standing.ask(revision - 1, revision, request.clone()).unwrap()) + .collect(); + let before = standing.read().unwrap(); + let mut projected = before.next(41, 42).unwrap(); + let mut rule = Rule { + kind: Kind::Note, + scope: Scope::Repository, + value: Value::Text("p".into()), + said: "Keep the owner instructions".into(), + source: super::super::Source::Command { + command: "note".into(), + }, + supersedes: None, + }; + Standing::stage_rule(&mut projected, Authority::Owner, 42, rule.clone()).unwrap(); + let padding = MAX_VIEW - 16 - serde_json::to_vec(&projected).unwrap().len(); + assert!(padding < 1024, "remaining padding: {padding}"); + rule.value = Value::Text("p".repeat(padding + 1)); + standing.rule(41, Authority::Owner, 42, rule).unwrap(); + let read = standing.read().unwrap(); + assert_eq!(serde_json::to_vec(&read).unwrap().len(), MAX_VIEW - 16); + assert!(!read.history_truncated); + assert_eq!(read.open_asks().count(), 40); + asks +} + +#[test] +fn answering_near_the_byte_limit_closes_the_ask_even_when_its_history_is_trimmed() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + let asks = fill_view_with_open_asks(&standing); + let cursor = facts.situation().unwrap().as_of_seq; + let answered = standing + .answer(42, Authority::Owner, 43, answer(&asks[0])) + .expect("the owner must be able to close an ask to free capacity"); + assert!(answered.answer.is_some()); + let reopened = Standing::open(&fixture.0.join("standing"), facts.clone()).unwrap(); + let (read, situation) = reopened.read_facts().unwrap(); + assert_eq!(read.revision, 43); + assert!(read.history_truncated); + assert_eq!(read.open_asks().count(), 39); + assert!(!read.asks.iter().any(|ask| ask.id == asks[0].id)); + assert_eq!(situation.standing_revision, 43); + assert_eq!(situation.asks.len(), 39); + assert!(!situation.asks.iter().any(|ask| ask.id == asks[0].id)); + let events = facts.events_after(cursor, 64).unwrap().events; + assert_eq!(events.len(), 1); + let Fact::StandingChanged(change) = &events[0].fact else { + panic!("standing change") + }; + assert_eq!(change.ask_closed.as_ref().unwrap().id, asks[0].id); + assert!(reopened.is_held(480).unwrap().is_some()); + assert!(reopened + .with_guard(Action::Update, subject(), |_| Ok(())) + .is_err()); +} + +#[test] +fn pending_trimmed_answers_recover_once_and_require_the_exact_prior_question() { + for phase in [ + "prepared", + "fact_committed", + "missing", + "changed", + "wrong_revision", + ] { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + let asks = fill_view_with_open_asks(&standing); + let before = standing.read().unwrap(); + let cursor = facts.situation().unwrap().as_of_seq; + let mut after = before.next(42, 43).unwrap(); + let request = answer(&asks[0]); + after.asks[0].answer = Some(Answer { + revision: 43, + question_revision: request.question_revision, + choice: request.choice, + at: 43, + source: request.source, + said: request.said, + }); + let closed = after.asks[0].clone(); + let fact = Fact::StandingChanged(after.difference(&before, None).unwrap()); + after.bounded().unwrap(); + assert!(!after.asks.iter().any(|ask| ask.id == closed.id)); + // Persist the real reserved/prepared boundary, then interrupt before publication. + let interrupted = facts.append_prepared( + Checkpoint { + source: "standing".into(), + revision: 43, + }, + 43, + fact.clone(), + |event| { + let pending = Pending { + after: after.clone(), + observation: serde_json::from_slice(&event.to_json().unwrap()).unwrap(), + trimmed_answer: Some(Box::new(closed.clone())), + }; + let document = Document { + version: 1, + current: before.clone(), + pending: Some(pending), + }; + standing.root.atomic(FILE, &document.bytes()?)?; + Err("interrupted after preparing the owner answer".into()) + }, + ); + assert!(interrupted.is_err()); + assert_eq!(facts.situation().unwrap().as_of_seq, cursor); + if phase == "fact_committed" { + facts + .append_prepared( + Checkpoint { + source: "standing".into(), + revision: 43, + }, + 43, + fact, + |_| Ok(()), + ) + .unwrap(); + } + let valid_pending = standing.root.read(FILE, MAX_FILE).unwrap(); + if matches!(phase, "missing" | "changed" | "wrong_revision") { + let mut document: Document = serde_json::from_slice(&valid_pending).unwrap(); + let pending = document.pending.as_mut().unwrap(); + match phase { + "missing" => pending.trimmed_answer = None, + "changed" => pending.trimmed_answer.as_mut().unwrap().question = "different question".into(), + "wrong_revision" => { + pending + .trimmed_answer + .as_mut() + .unwrap() + .answer + .as_mut() + .unwrap() + .revision += 1 + } + _ => unreachable!(), + } + standing.root.atomic(FILE, &document.bytes().unwrap()).unwrap(); + assert!(Standing::open(&fixture.0.join("standing"), facts.clone()).is_err()); + assert!(matches!( + standing.with_guard(Action::Update, subject(), |_| Ok(())), + Err(GuardError::Storage(_)) + )); + assert_eq!(facts.situation().unwrap().as_of_seq, cursor); + standing.root.atomic(FILE, &valid_pending).unwrap(); + } + let reopened = Standing::open(&fixture.0.join("standing"), facts.clone()).unwrap(); + let (read, situation) = reopened.read_facts().unwrap(); + assert_eq!((read.revision, situation.standing_revision), (43, 43)); + assert_eq!((read.open_asks().count(), situation.asks.len()), (39, 39)); + assert_eq!(facts.events_after(cursor, 64).unwrap().events.len(), 1); + assert!(reopened.is_held(480).unwrap().is_some()); + assert_eq!(reopened.read().unwrap().revision, 43); + assert_eq!(facts.events_after(cursor, 64).unwrap().events.len(), 1); + reopened + .answer(43, Authority::Owner, 44, answer(&asks[1])) + .unwrap(); + assert_eq!(reopened.read().unwrap().open_asks().count(), 38); + } +} + +#[test] +fn an_ask_capacity_refusal_does_not_reserve_a_stuck_standing_revision() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + for index in 0..128 { + facts + .append( + Checkpoint { + source: "runner".into(), + revision: index + 1, + }, + 1, + Fact::TaskStarted(oxa_proto::work::Running { + task: format!("task-{index}"), + host: "helper".into(), + branch: format!("agent/task-{index}"), + worktree: "~/project".into(), + session_id: None, + step: oxa_proto::work::TaskStep::Preparing, + }), + ) + .unwrap(); + } + assert!(standing.ask(0, 2, question()).is_err()); + assert_eq!(standing.read().unwrap().revision, 0); + assert!(standing.read().unwrap().asks.is_empty()); + let document: Document = serde_json::from_slice(&standing.root.read(FILE, MAX_FILE).unwrap()).unwrap(); + assert!(document.pending.is_none()); + facts + .append( + Checkpoint { + source: "runner".into(), + revision: 129, + }, + 3, + Fact::TaskTransition(oxa_proto::work::TaskTransition { + task: "task-0".into(), + step: oxa_proto::work::TaskStep::Finished, + session_id: None, + reason: Some(oxa_proto::work::StepReason::Interrupted), + }), + ) + .unwrap(); + let ask = standing.ask(0, 4, question()).unwrap(); + assert_eq!(facts.situation().unwrap().asks.len(), 1); + standing.answer(1, Authority::Owner, 5, answer(&ask)).unwrap(); + assert!(facts.situation().unwrap().asks.is_empty()); +} + +#[test] +fn a_late_answer_is_retained_even_when_its_question_is_the_oldest() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts); + let oldest = standing.ask(0, 100, question()).unwrap(); + let mut revision = 1; + for _ in 0..16 { + let ask = standing.ask(revision, 100, question()).unwrap(); + revision += 1; + standing + .answer(revision, Authority::Owner, 100, answer(&ask)) + .unwrap(); + revision += 1; + } + standing + .answer(revision, Authority::Owner, 1, answer(&oldest)) + .unwrap(); + let read = standing.read().unwrap(); + assert!(read.history_truncated); + assert_eq!(read.asks.len(), 16); + assert!(read + .asks + .iter() + .find(|ask| ask.id == oldest.id) + .unwrap() + .answer + .is_some()); +} + +#[test] +fn a_failed_fact_reservation_cannot_strand_policy_at_projection_capacity() { + use std::os::unix::fs::PermissionsExt; + // SAFETY: geteuid takes no arguments and cannot fail. + if unsafe { libc::geteuid() } == 0 { + use std::os::unix::process::CommandExt; + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .env_clear() + .args([ + "--exact", + "standing::store::tests::a_failed_fact_reservation_cannot_strand_policy_at_projection_capacity", + ]) + .uid(65534) + .gid(65534) + .output() + .unwrap(); + assert!( + result.status.success(), + "{}{}", + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr) + ); + return; + } + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + standing.rule(0, Authority::Owner, 1, hold(true, None)).unwrap(); + let existing = standing.ask(1, 2, question()).unwrap(); + for revision in 1..=126 { + facts + .append( + Checkpoint { + source: "runner".into(), + revision, + }, + revision + 10, + Fact::TaskStarted(oxa_proto::work::Running { + task: format!("busy-{revision}"), + host: "local".into(), + branch: format!("agent/busy-{revision}"), + worktree: "/tmp/synthetic".into(), + session_id: None, + step: oxa_proto::work::TaskStep::Preparing, + }), + ) + .unwrap(); + } + let root = fixture.0.join("facts"); + fs::set_permissions(&root, fs::Permissions::from_mode(0o500)).unwrap(); + let failed = standing.ask(2, 500, question()); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + assert!(failed.is_err(), "facts reservation unexpectedly succeeded"); + facts + .append( + Checkpoint { + source: "runner".into(), + revision: 127, + }, + 600, + Fact::TaskStarted(oxa_proto::work::Running { + task: "last-slot".into(), + host: "local".into(), + branch: "agent/last-slot".into(), + worktree: "/tmp/synthetic".into(), + session_id: None, + step: oxa_proto::work::TaskStep::Preparing, + }), + ) + .unwrap(); + let read = standing + .read() + .expect("a failed reservation stranded every standing operation"); + assert_eq!(read.revision, 2); + assert_eq!(read.open_asks().count(), 1); + standing + .answer(2, Authority::Owner, 700, answer(&existing)) + .unwrap(); + assert!(standing.read().unwrap().open_asks().next().is_none()); + assert_eq!(facts.situation().unwrap().running.len(), 127); + assert!(matches!( + standing.with_guard(Action::Update, subject(), |_| Ok(())), + Err(GuardError::Refused(_)) + )); +} + +#[test] +fn failed_policy_preparation_cancels_only_the_unpublished_reservation() { + use std::os::unix::fs::PermissionsExt; + // SAFETY: geteuid takes no arguments and cannot fail. + if unsafe { libc::geteuid() } == 0 { + use std::os::unix::process::CommandExt; + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .env_clear() + .args([ + "--exact", + "standing::store::tests::failed_policy_preparation_cancels_only_the_unpublished_reservation", + ]) + .uid(65534) + .gid(65534) + .output() + .unwrap(); + assert!( + result.status.success(), + "{}{}", + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr) + ); + return; + } + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + let held = standing.rule(0, Authority::Owner, 1, hold(true, None)).unwrap(); + let root = fixture.0.join("standing"); + fs::set_permissions(&root, fs::Permissions::from_mode(0o500)).unwrap(); + let failed = standing.rule(1, Authority::Owner, 2, hold(false, Some(&held.id))); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + assert!(failed.is_err()); + assert_eq!( + facts.situation().unwrap().standing_revision, + 1, + "unprepared policy was published" + ); + let reopened = Standing::open(&root, Facts::open(&fixture.0.join("facts")).unwrap()).unwrap(); + assert_eq!(reopened.read().unwrap().revision, 1); + assert!(matches!( + reopened.with_guard(Action::Update, subject(), |_| Ok(())), + Err(GuardError::Refused(_)) + )); + reopened + .rule(1, Authority::Owner, 3, hold(false, Some(&held.id))) + .unwrap(); + assert!(reopened.is_held(480).unwrap().is_none()); + assert_eq!(facts.situation().unwrap().standing_revision, 2); +} + +#[test] +fn recovery_syncs_the_prepared_policy_before_committing_its_fact() { + use std::os::unix::fs::PermissionsExt; + // SAFETY: geteuid has no arguments, pointers or failure mode. + if unsafe { libc::geteuid() } == 0 { + use std::os::unix::process::CommandExt; + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .env_clear() + .args([ + "--exact", + "standing::store::tests::recovery_syncs_the_prepared_policy_before_committing_its_fact", + ]) + .uid(65534) + .gid(65534) + .output() + .unwrap(); + assert!( + result.status.success(), + "{}{}", + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr) + ); + return; + } + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + let before = standing.read().unwrap(); + let mut after = before.next(0, 9).unwrap(); + let request = hold(true, None); + after.entries.push(Entry { + id: "R-1".into(), + kind: request.kind, + scope: request.scope, + value: request.value, + said: request.said, + at: 9, + said_by: Authority::Owner, + source: request.source, + supersedes: None, + state: EntryState::Stored, + reminders: 0, + last_reminder: None, + authority: Authority::Owner, + }); + let event = Event { + seq: 1, + at_ms: 9, + checkpoint: Checkpoint { + source: "standing".into(), + revision: 1, + }, + fact: Fact::StandingChanged(after.change(None)), + }; + let document = Document { + version: 1, + current: before, + pending: Some(Pending { + after, + observation: serde_json::from_slice(&event.to_json().unwrap()).unwrap(), + trimmed_answer: None, + }), + }; + standing.root.atomic(FILE, &document.bytes().unwrap()).unwrap(); + let path = fixture.0.join("standing/standing.json"); + let original = fs::read(&path).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o400)).unwrap(); + let recovered = standing.read(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + assert!( + recovered.is_err(), + "policy was acknowledged before its prepared data could be synced" + ); + assert_eq!(fs::read(&path).unwrap(), original); + assert_eq!(facts.situation().unwrap().standing_revision, 0); + assert_eq!(standing.read().unwrap().revision, 1); + assert_eq!(facts.events_after(0, 64).unwrap().events.len(), 1); +} + +#[test] +fn a_concurrent_owner_hold_waits_for_one_effect_then_blocks_the_next() { + const CHILD_ROOT: &str = "OXA_STANDING_GUARD_CHILD"; + if let Some(root) = std::env::var_os(CHILD_ROOT) { + let root = PathBuf::from(root); + let facts = Facts::open(&root.join("facts")).unwrap(); + fs::write(root.join("child-ready"), b"ready").unwrap(); + let standing = Standing::open(&root.join("standing"), facts).unwrap(); + standing.rule(0, Authority::Owner, 1, hold(true, None)).unwrap(); + return; + } + struct Child(std::process::Child); + impl Drop for Child { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts); + let mut child = None; + let completed = standing.with_guard(Action::Update, subject(), |read| { + let process = std::process::Command::new(std::env::current_exe().unwrap()) + .env_clear().env(CHILD_ROOT, &fixture.0) + .args(["--exact", "standing::store::tests::a_concurrent_owner_hold_waits_for_one_effect_then_blocks_the_next"]) + .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped()).spawn().unwrap(); + child = Some(Child(process)); + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + while !fixture.0.join("child-ready").exists() { + assert!(std::time::Instant::now() < until, "child failed to start"); + assert!(child.as_mut().unwrap().0.try_wait().unwrap().is_none()); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + std::thread::sleep(std::time::Duration::from_millis(50)); + assert!(child.as_mut().unwrap().0.try_wait().unwrap().is_none(), "hold writer passed the live effect guard"); + let document: Document = serde_json::from_slice(&standing.root.read(FILE, MAX_FILE).unwrap()).unwrap(); + assert_eq!(document.current.revision, read.revision); + Ok(read.revision) + }).unwrap(); + assert_eq!(completed.result.unwrap(), 0); + let child = child.as_mut().unwrap(); + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + if let Some(status) = child.0.try_wait().unwrap() { + assert!(status.success()); + break; + } + assert!( + std::time::Instant::now() < until, + "hold writer did not acquire the released guard" + ); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(standing + .with_guard(Action::Update, subject(), |_| Ok(())) + .is_err()); +} + +fn policy(kind: Kind, scope: Scope, value: Value, supersedes: Option<&str>) -> Rule { + Rule { + kind, + scope, + value, + said: "Synthetic owner rule".into(), + source: super::super::Source::Command { + command: "rule".into(), + }, + supersedes: supersedes.map(str::to_owned), + } +} + +#[test] +fn budget_increases_gate_weakening_and_reserves_require_owner_authority() { + use super::super::{GateEvidence as E, ReservedClass, ReviewTier as T}; + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts); + let host = Scope::Host("helper".into()); + let first = standing + .rule( + 0, + Authority::Owner, + 1, + policy( + Kind::Budget, + host.clone(), + Value::Budget { + daily_usd_micros: 200_000_000, + }, + None, + ), + ) + .unwrap(); + let lower = standing + .rule( + 1, + Authority::Lead, + 2, + policy( + Kind::Budget, + host.clone(), + Value::Budget { + daily_usd_micros: 100_000_000, + }, + Some(&first.id), + ), + ) + .unwrap(); + assert!(standing + .rule( + 2, + Authority::Lead, + 3, + policy( + Kind::Budget, + host.clone(), + Value::Budget { + daily_usd_micros: 150_000_000 + }, + Some(&lower.id) + ) + ) + .is_err()); + assert!(standing + .rule( + 2, + Authority::Lead, + 3, + policy(Kind::Budget, host, Value::Retired, Some(&lower.id)) + ) + .is_err()); + let path = Scope::Path("engine/**".into()); + let gate = standing + .rule( + 2, + Authority::Owner, + 3, + policy( + Kind::Gate, + path.clone(), + Value::Gate { + tier: T::T2, + evidence: vec![E::LocalChecks, E::PrBuild], + }, + None, + ), + ) + .unwrap(); + let stronger = standing + .rule( + 3, + Authority::Lead, + 4, + policy( + Kind::Gate, + path.clone(), + Value::Gate { + tier: T::T3, + evidence: vec![E::LocalChecks, E::PrBuild, E::HardwareMeasurement], + }, + Some(&gate.id), + ), + ) + .unwrap(); + for value in [ + Value::Gate { + tier: T::T2, + evidence: vec![E::LocalChecks, E::PrBuild, E::HardwareMeasurement], + }, + Value::Gate { + tier: T::T3, + evidence: vec![E::LocalChecks, E::PrBuild], + }, + Value::Retired, + ] { + assert!(standing + .rule( + 4, + Authority::Lead, + 5, + policy(Kind::Gate, path.clone(), value, Some(&stronger.id)) + ) + .is_err()); + } + let reserve = policy( + Kind::Reserve, + Scope::Repository, + Value::Reserve { + classes: vec![ReservedClass::Paid], + }, + None, + ); + assert!(standing.rule(4, Authority::Lead, 5, reserve.clone()).is_err()); + let reserve = standing.rule(4, Authority::Owner, 5, reserve).unwrap(); + assert!(standing + .rule( + 5, + Authority::Lead, + 6, + policy( + Kind::Reserve, + Scope::Repository, + Value::Retired, + Some(&reserve.id) + ) + ) + .is_err()); + assert_eq!(standing.read().unwrap().revision, 5); +} + +#[test] +fn only_accepting_the_bound_proposal_applies_its_exact_rule() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + let prior = standing.rule(0, Authority::Owner, 1, hold(true, None)).unwrap(); + let ask = standing + .propose(1, 2, hold(false, Some(&prior.id)), question(), "Release".into()) + .unwrap(); + assert!(standing.is_held(480).unwrap().is_some()); + assert!(standing.answer(2, Authority::Lead, 3, answer(&ask)).is_err()); + let mut accepted = answer(&ask); + accepted.said = "Yes, release this hold".into(); + standing.answer(2, Authority::Owner, 3, accepted).unwrap(); + let read = standing.read().unwrap(); + let released = read.entries.iter().find(|entry| entry.id == "R-3").unwrap(); + assert_eq!(released.said, "Yes, release this hold"); + assert_eq!( + released.value, + Value::Constraint { + active: false, + until: None + } + ); + assert_eq!(released.state, EntryState::Stored); + assert!(standing.is_held(480).unwrap().is_none()); + assert_eq!(facts.situation().unwrap().standing_revision, 3); + assert!(facts.situation().unwrap().asks.is_empty()); +} + +#[test] +fn a_proposal_cannot_replace_a_rule_changed_after_the_question() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts); + let prior = standing.rule(0, Authority::Owner, 1, hold(true, None)).unwrap(); + let ask = standing + .propose(1, 2, hold(false, Some(&prior.id)), question(), "Release".into()) + .unwrap(); + let current = standing + .rule(2, Authority::Owner, 3, hold(true, Some(&prior.id))) + .unwrap(); + assert!(standing.answer(3, Authority::Owner, 4, answer(&ask)).is_err()); + let read = standing.read().unwrap(); + assert_eq!(read.revision, 3); + assert!(read.asks[0].answer.is_none()); + assert_eq!(standing.is_held(480).unwrap(), Some(current.id)); +} + +#[test] +fn an_advisory_conversion_requires_an_explicit_owner_decision() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts); + let note = standing + .rule( + 0, + Authority::Owner, + 1, + policy( + Kind::Note, + Scope::PullRequest(480), + Value::Text("Pause this PR".into()), + None, + ), + ) + .unwrap(); + let source = super::super::Source::Command { + command: "remind".into(), + }; + assert!(standing + .remind(1, Authority::Lead, ¬e.id, 2, source.clone()) + .is_err()); + standing + .remind(1, Authority::Owner, ¬e.id, 2, source.clone()) + .unwrap(); + let reminded = standing + .remind(2, Authority::Owner, ¬e.id, 3, source.clone()) + .unwrap(); + assert!(reminded.needs_conversion_offer()); + assert_eq!(reminded.last_reminder.unwrap().source, source); + assert!(standing.is_held(480).unwrap().is_none()); + let conversion = hold(true, Some(¬e.id)); + assert!(standing.rule(3, Authority::Lead, 4, conversion.clone()).is_err()); + let mut prompt = question(); + prompt.question = "Enforce the advisory pause?".into(); + prompt.options[0].label = "Keep advisory".into(); + prompt.options[0].detail = "Leave the note advisory".into(); + prompt.options[1].label = "Enforce".into(); + prompt.options[1].detail = "Create the exact PR hold shown in this proposal".into(); + prompt.recommended = "Keep advisory".into(); + let ask = standing + .propose(3, 4, conversion, prompt, "Enforce".into()) + .unwrap(); + let mut accepted = answer(&ask); + accepted.choice = super::super::Choice::Option("Enforce".into()); + accepted.said = "Enforce".into(); + standing.answer(4, Authority::Owner, 5, accepted).unwrap(); + let read = standing.read().unwrap(); + assert!(!read.live_rules().any(|entry| entry.kind == Kind::Note)); + assert!(standing.is_held(480).unwrap().is_some()); +} + +#[test] +fn a_named_release_needs_the_matching_durable_merge_observation() { + let fixture = Fixture::new(); + let facts = fixture.facts(); + let standing = fixture.standing(facts.clone()); + let mut request = hold(true, None); + request.said = "Hold until PR 478 is merged".into(); + request.value = Value::Constraint { + active: true, + until: Some(super::super::Condition::PrMerged(478)), + }; + let entry = standing.rule(0, Authority::Owner, 1, request).unwrap(); + let mut changed = hold(true, Some(&entry.id)); + assert!(standing.rule(1, Authority::Lead, 2, changed.clone()).is_err()); + changed.value = Value::Constraint { + active: true, + until: Some(super::super::Condition::PrMerged(1)), + }; + assert!(standing.rule(1, Authority::Lead, 2, changed).is_err()); + assert!(standing + .release_when(1, &entry.id, 2, |_| Ok(None)) + .unwrap() + .is_none()); + let proof = Event { + seq: 2, + at_ms: 3, + checkpoint: Checkpoint { + source: "github".into(), + revision: 1, + }, + fact: Fact::PrMerged(oxa_proto::work::Landed { + pr: oxa_proto::work::PullRequest { + number: 478, + head: "a".repeat(40), + }, + merge_commit: "b".repeat(40), + merged_at_ms: 3, + }), + }; + assert!(standing + .release_when(1, &entry.id, 3, |_| Ok(Some(proof.clone()))) + .is_err()); + assert!(standing.is_held(480).unwrap().is_some()); + let observed = facts + .append(proof.checkpoint.clone(), proof.at_ms, proof.fact.clone()) + .unwrap(); + assert_eq!(observed, proof); + let release = standing + .release_when(1, &entry.id, 4, |condition| { + assert_eq!(*condition, super::super::Condition::PrMerged(478)); + Ok(Some(observed.clone())) + }) + .unwrap() + .unwrap(); + assert!(matches!(release.state, EntryState::Applied { .. })); + assert_eq!(release.said, "Hold until PR 478 is merged"); + assert!(standing.is_held(480).unwrap().is_none()); + assert_eq!(facts.situation().unwrap().landed[0].pr.number, 478); +} diff --git a/oxa/oxa-work/src/standing/types.rs b/oxa/oxa-work/src/standing/types.rs new file mode 100644 index 000000000..e0d4b15c3 --- /dev/null +++ b/oxa/oxa-work/src/standing/types.rs @@ -0,0 +1,302 @@ +use super::Scope; +use crate::Result; +use serde::{Deserialize, Serialize}; + +/// Supplied by a trusted frontend; this is not a field in a rule/tool request. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Authority { + Owner, + Lead, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + Goal, + Priority, + Freeze, + Hold, + Budget, + Model, + Placement, + Gate, + Eligible, + Decided, + Reserve, + Note, +} + +/// A source reference is selected/checked by the frontend, never inferred from tool success. +#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum Source { + Command { command: String }, + SessionEntry { session_id: String, entry_id: String }, +} + +#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde( + tag = "kind", + content = "value", + rename_all = "snake_case", + deny_unknown_fields +)] +pub enum Value { + Text(String), + /// An explicit release is a new entry which supersedes the hold/freeze it releases. + Constraint { + active: bool, + until: Option, + }, + Retired, + Budget { + daily_usd_micros: u64, + }, + Gate { + tier: ReviewTier, + evidence: Vec, + }, + Reserve { + classes: Vec, + }, +} +#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde( + tag = "kind", + content = "value", + rename_all = "snake_case", + deny_unknown_fields +)] +pub enum Condition { + PrMerged(u64), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ReviewTier { + T1, + T2, + T3, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum GateEvidence { + LocalChecks, + PrBuild, + Review, + Queue, + HardwareMeasurement, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ReservedClass { + Public, + Paid, + Credentials, + Destructive, + Desktop, +} + +#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Rule { + pub kind: Kind, + pub scope: Scope, + pub value: Value, + pub said: String, + pub source: Source, + pub supersedes: Option, +} + +#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum EntryState { + Stored, + Applied { verified_at: u64, evidence: String }, + Superseded, +} + +#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Entry { + pub id: String, + pub kind: Kind, + pub scope: Scope, + pub value: Value, + pub said: String, + pub at: u64, + pub said_by: Authority, + pub source: Source, + pub supersedes: Option, + pub state: EntryState, + pub reminders: u32, + pub last_reminder: Option, + // Inherited by a strengthening replacement: a lead cannot launder an owner's live hold + // into its own hold and then release it. Request source remains attributed separately. + pub(super) authority: Authority, +} +#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Reminder { + pub at: u64, + pub source: Source, +} + +pub(super) fn text(value: &str, maximum: usize) -> Result<()> { + if value.trim().is_empty() + || value.len() > maximum + || value + .chars() + .any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')) + { + return Err("standing text must be bounded and single-line".into()); + } + Ok(()) +} +pub(super) fn id(value: &str) -> Result<()> { + if value.is_empty() + || value.len() > 128 + || !value + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"-_.:/".contains(&c)) + { + return Err("invalid standing identifier".into()); + } + Ok(()) +} +impl Scope { + pub(super) fn validate(&self) -> Result<()> { + match self { + Self::Repository => Ok(()), + Self::PullRequest(number) if *number > 0 => Ok(()), + Self::PullRequest(_) => Err("standing PR number must be positive".into()), + Self::Task(value) | Self::Host(value) => id(value), + Self::Branch(value) => { + text(value, 256)?; + if value.starts_with('-') { + return Err("invalid standing branch".into()); + } + Ok(()) + } + Self::Path(value) => { + text(value, 256)?; + if value.starts_with('/') || value.split('/').any(|part| matches!(part, "" | "." | "..")) { + return Err("standing path selector must be repository-relative".into()); + } + Ok(()) + } + } + } +} +impl Source { + pub(super) fn validate(&self) -> Result<()> { + match self { + Self::Command { command } => text(command, 512), + Self::SessionEntry { session_id, entry_id } => { + id(session_id)?; + id(entry_id) + } + } + } +} +impl Rule { + pub(super) fn validate(&self) -> Result<()> { + self.scope.validate()?; + self.source.validate()?; + text(&self.said, 1024)?; + if let Some(prior) = &self.supersedes { + id(prior)?; + } + if let Value::Constraint { + active, + until: Some(Condition::PrMerged(pr)), + } = &self.value + { + if !active || *pr == 0 { + return Err("invalid standing release condition".into()); + } + } + match (&self.kind, &self.value) { + (_, Value::Retired) => Ok(()), + (Kind::Hold | Kind::Freeze, Value::Constraint { .. }) + if !matches!(self.scope, Scope::Path(_)) => + { + Ok(()) + } + (Kind::Budget, Value::Budget { .. }) => Ok(()), + (Kind::Gate, Value::Gate { evidence, .. }) => { + if evidence.len() > 5 + || evidence + .iter() + .enumerate() + .any(|(i, value)| evidence[..i].contains(value)) + { + return Err("invalid gate requirements".into()); + } + Ok(()) + } + (Kind::Reserve, Value::Reserve { classes }) => { + if classes.is_empty() + || classes.len() > 5 + || classes + .iter() + .enumerate() + .any(|(i, value)| classes[..i].contains(value)) + { + return Err("invalid reserved classes".into()); + } + Ok(()) + } + ( + Kind::Goal + | Kind::Priority + | Kind::Model + | Kind::Placement + | Kind::Eligible + | Kind::Decided + | Kind::Note, + Value::Text(value), + ) => text(value, 1024), + _ => Err("standing kind and value schema disagree".into()), + } + } +} +impl Entry { + pub fn is_live(&self) -> bool { + self.state != EntryState::Superseded + && !matches!( + self.value, + Value::Retired | Value::Constraint { active: false, .. } + ) + } + pub fn needs_conversion_offer(&self) -> bool { + self.kind == Kind::Note && self.reminders >= 2 && self.state != EntryState::Superseded + } + pub(super) fn rule(&self) -> Rule { + Rule { + kind: self.kind, + scope: self.scope.clone(), + value: self.value.clone(), + said: self.said.clone(), + source: self.source.clone(), + supersedes: self.supersedes.clone(), + } + } + pub(super) fn validate(&self) -> Result<()> { + id(&self.id)?; + self.rule().validate()?; + if (self.reminders == 0) != self.last_reminder.is_none() { + return Err("standing reminder metadata disagrees".into()); + } + if let Some(reminder) = &self.last_reminder { + reminder.source.validate()?; + } + if let EntryState::Applied { evidence, .. } = &self.state { + text(evidence, 256)?; + } + Ok(()) + } +} + +private_debug!(Source, Value, Condition, Rule, EntryState, Entry, Reminder);