Skip to main content

agentmux_srv_core/backend/
operator_config_seed.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Operator Config seed engine: keeps AgentMux's own shipped Global Memory
5//! entries (`is_system=1` rows — see docs/specs/SPEC_GLOBAL_MEMORY_
6//! SYSTEM_TIER_2026_08_24.md for the isolation, docs/specs/SPEC_SYSTEM_
7//! TIER_GLOBAL_MEMORY_SEEDING_2026_09_15.md for this module's own design)
8//! in sync with a compiled-in manifest, every startup — not a one-time
9//! seed like `mcp_seed.rs`, because stale Operator Config
10//! (describing a since-changed MuxAPI) would actively mislead an agent
11//! rather than merely being absent.
12//!
13//! The reseed decision (§3.3 of the spec above) is ownership-based, not a
14//! field diff like `agent_seed.rs`'s own `reseed_if_needed`: a human can
15//! edit an Operator Config entry today via Memory → Global's
16//! editor (`GlobalMemoryFullView`), and the *entire* value of an entry is
17//! its content, so
18//! there is no separate "identity field" to diff against safely. Instead
19//! `Store::bundle_reseed_system_if_owned` looks at the latest `db_bundle_
20//! versions` row for each manifest id — if `written_by` is this module's
21//! own reserved identity (`WRITTEN_BY`), it's safe to overwrite; if it's
22//! anything else (an `armory-ui` human edit), the manifest update is
23//! skipped and logged rather than clobbering it. That check-and-write
24//! happens atomically at the `Store` layer, not as two separate calls
25//! composed here — see that method's own doc comment (ReAgent P1, PR
26//! #3244, a check-then-act race in an earlier version of this module).
27//!
28//! "In sync" also covers removal: `prune_entries_removed_from_manifest`
29//! deletes any seeder-owned row whose manifest entry a later AgentMux
30//! release dropped or renamed, so a retired Operator Config note doesn't
31//! keep being injected into every future agent forever (Codex P2, PR
32//! #3244) — mirroring `agent_seed.rs`'s own "remove a seeded agent not in
33//! the manifest" behavior. A human-edited row meets the same fate as
34//! everywhere else in this module: left alone, never deleted out from
35//! under the human who edited it.
36
37use std::sync::Arc;
38
39use serde::Deserialize;
40
41use super::audience::{Audience, HostCap, RuntimeCaps};
42use super::runtime_adapter::RuntimeKind;
43use super::storage::bundles::Bundle;
44use super::storage::store::Store;
45use super::storage::{BundleReseedOutcome, StoreError};
46
47/// The reserved `written_by` identity this seeder stamps on every version it
48/// writes. Never used by any other caller — an agent's own write stamps its
49/// real `AGENTMUX_AGENT_ID`, a human edit in Memory stamps
50/// `"armory-ui"` (`bundle.rs`'s `upsertsystemmemory` handler, via `bundle_
51/// upsert_system_with_version`) — so seeing this exact value on the latest
52/// version is what tells `bundle_reseed_system_if_owned` that nothing but
53/// AgentMux itself has touched the row since.
54pub const WRITTEN_BY: &str = "agentmux-operator-config-seed";
55
56const SEED_MANIFEST: &str = include_str!("../../operator-config-seed.json");
57
58#[derive(Debug, Deserialize)]
59struct SeedManifest {
60    /// The primary reseed decision is still content-hash-based, not this
61    /// number (see this module's own doc comment) — but `version` also
62    /// travels into each write's `source_detail` as a monotonic generation
63    /// guard: `bundle_reseed_system_if_owned` refuses to let a write whose
64    /// generation is lower than what's already recorded win, so an older
65    /// AgentMux build's own (older) manifest can never downgrade a row a
66    /// newer build already seeded on a shared store.db (Codex P2, PR #3244).
67    version: u32,
68    entries: Vec<SeedEntry>,
69}
70
71#[derive(Debug, Deserialize)]
72struct SeedEntry {
73    id: String,
74    name: String,
75    instructions: String,
76    /// The agent kinds this entry is delivered to: `"host"` and/or
77    /// `"container"` (see [`agent_kind`]). Absent or empty means every agent.
78    /// Lives only in the manifest, not in `db_bundles`: a new column would
79    /// bump the schema version, and `check_schema_compat` then locks every
80    /// older build out of a shared store.db
81    /// (SPEC_LAUNCH_CONTEXT_WORKSPACE_RULE_AND_STARTUP_FILES_2026_09_30.md
82    /// §3.2). A local edit of the entry keeps its id, so it keeps its target.
83    #[serde(default)]
84    agent_types: Vec<String>,
85}
86
87/// Why a host-only entry is not delivered to a container agent. These entries describe working on the
88/// host (the agent's workspace folder, building and installing widgets there).
89const HOST_ONLY_ENTRY: &str = "this entry describes working on the host, which a container agent cannot do.";
90
91impl SeedEntry {
92    /// Who the entry is for, as an [`Audience`]: no `agent_types` (or both kinds) is everyone, `["host"]`
93    /// needs the host (`host_write`: the entries tell an agent to put files on the machine),
94    /// `["container"]` is for container agents. `None` when the list is not empty but names neither kind
95    /// (a typo): the entry reaches nobody, as it always did.
96    fn audience(&self) -> Option<Audience> {
97        let named = |kind: &str| self.agent_types.iter().any(|t| t == kind);
98        match (named("host"), named("container")) {
99            (true, false) => Some(Audience::NativeOnly(HostCap::Write, HOST_ONLY_ENTRY)),
100            (false, true) => Some(Audience::ContainerOnly),
101            (false, false) if !self.agent_types.is_empty() => None,
102            _ => Some(Audience::Everyone),
103        }
104    }
105}
106
107/// The kind of agent a Global Memory entry can be targeted at: `"container"`
108/// for a Docker agent, `"host"` for everything else (`agent_type` is
109/// `"host"`, `"standalone"` or `"container"`; the block's `agentMode` carries
110/// the same value, defaulting to `"host"`).
111pub fn agent_kind(agent_mode: &str) -> &'static str {
112    match RuntimeKind::of_agent_mode(agent_mode) {
113        RuntimeKind::Container => "container",
114        RuntimeKind::Host => "host",
115    }
116}
117
118/// The `agentMode` of the agent on `block_id`, for the delivery paths that
119/// know only the block (the SessionStart hook, `globalmemory:sections`).
120/// `"host"` when the block or the key is missing — srv's default for
121/// `agentMode` everywhere else.
122pub fn agent_mode_of_block(mstore: &Store, block_id: &str) -> String {
123    match mstore.get::<crate::backend::obj::Block>(block_id) {
124        Ok(Some(block)) => crate::backend::obj::meta_get_string(&block.meta, "agentMode", "host"),
125        Ok(None) => "host".to_string(),
126        Err(e) => {
127            tracing::warn!(block_id, error = %e, "operator config: block lookup failed — delivering as a host agent");
128            "host".to_string()
129        }
130    }
131}
132
133/// The [`agent_kind`] of the agent on `block_id`, or `None` when the block
134/// can't be read, for a caller that would rather say nothing than guess (the
135/// LAN fleet feed's `agent_kinds`).
136pub fn agent_kind_of_block(mstore: &Store, block_id: &str) -> Option<&'static str> {
137    let block = mstore.get::<crate::backend::obj::Block>(block_id).ok()??;
138    Some(agent_kind(&crate::backend::obj::meta_get_string(&block.meta, "agentMode", "host")))
139}
140
141/// The embedded manifest, parsed once for [`global_bundles_for_agent`].
142/// `None` if it doesn't parse — `embedded_manifest_parses` pins that it does.
143fn embedded_manifest() -> Option<&'static SeedManifest> {
144    static MANIFEST: std::sync::OnceLock<Option<SeedManifest>> = std::sync::OnceLock::new();
145    MANIFEST.get_or_init(|| serde_json::from_str(SEED_MANIFEST).ok()).as_ref()
146}
147
148/// Global Memory narrowed to what an agent of `agent_mode` is given: drops a
149/// system entry whose manifest entry targets other agent kinds. Workspace
150/// entries and system entries this build's manifest doesn't know always stay.
151///
152/// Every place that composes Global Memory for an agent calls this before
153/// `format_global_bundle_block`/`global_bundle_sections` — the startup file
154/// (both launch paths), the SessionStart hook and `globalmemory:sections` —
155/// so they stay the same block byte for byte.
156pub fn global_bundles_for_agent(bundles: Vec<Bundle>, agent_mode: &str) -> Vec<Bundle> {
157    let caps = RuntimeCaps::of(RuntimeKind::of_agent_mode(agent_mode).is_container());
158    match embedded_manifest() {
159        Some(manifest) => filter_for_runtime(bundles, manifest, caps),
160        None => bundles,
161    }
162}
163
164fn filter_for_runtime(bundles: Vec<Bundle>, manifest: &SeedManifest, caps: RuntimeCaps) -> Vec<Bundle> {
165    bundles
166        .into_iter()
167        .filter(|b| {
168            !b.is_system
169                || manifest
170                    .entries
171                    .iter()
172                    .find(|e| e.id == b.id)
173                    .is_none_or(|e| e.audience().is_some_and(|a| a.permits(caps)))
174        })
175        .collect()
176}
177
178/// Run Operator Config seeding on startup. Unconditional, every boot, no
179/// feature flag — called from `bootstrap/stores.rs` next to `agent_seed`'s own
180/// call.
181pub fn auto_seed_on_startup(store: &Arc<Store>) {
182    let manifest: SeedManifest = match serde_json::from_str(SEED_MANIFEST) {
183        Ok(m) => m,
184        Err(e) => {
185            tracing::error!("operator config seed: failed to parse manifest: {e}");
186            return;
187        }
188    };
189    seed_from_manifest(store, &manifest);
190}
191
192/// The actual seed pass, separated from `auto_seed_on_startup` purely so
193/// tests can exercise it against a hand-built `SeedManifest` instead of the
194/// embedded JSON.
195fn seed_from_manifest(store: &Arc<Store>, manifest: &SeedManifest) {
196    // Prune BEFORE seeding, not after: when a release renames a manifest
197    // entry's id while keeping the same (UNIQUE) display `name`, the old
198    // id's row must be gone before the new id's INSERT is attempted, or
199    // that insert fails on the name collision with no retry — leaving the
200    // renamed entry absent until the NEXT startup happens to prune the old
201    // row first (Codex P2, PR #3244).
202    prune_entries_removed_from_manifest(store, manifest);
203
204    let mut tally = SeedTally::default();
205
206    // A collision here can be purely an ordering artifact WITHIN this same
207    // manifest, independent of pruning: entry B wants the display name
208    // entry A is about to release via its own update (A kept its id, only
209    // its `name` changed), but B happens to appear before A in the
210    // manifest array, so B's INSERT hits A's still-current name and fails.
211    //
212    // A single retry pass only resolves a 2-entry swap — a longer
213    // dependency CHAIN (C wants a name B is about to release, B wants a
214    // name A is about to release, A releases first) can still leave an
215    // entry stranded after exactly one retry, depending on which order the
216    // chain happens to be walked in. So: keep retrying the still-failing
217    // subset until a full pass makes literally zero progress (nothing in
218    // it succeeded) — each successful entry in a pass can only unblock
219    // entries later in the SAME OR A SUBSEQUENT pass, so a pass with no
220    // successes at all means every remaining failure is a real collision
221    // (e.g. an unrelated user bundle already owns the name), not an
222    // ordering artifact. Bounded by the number of entries: each pass either
223    // shrinks the pending set by at least one or terminates the loop.
224    // Codex P2, PR #3244.
225    let mut pending: Vec<&SeedEntry> = manifest.entries.iter().collect();
226    loop {
227        let mut still_pending = Vec::new();
228        let mut made_progress = false;
229        for entry in pending {
230            if seed_and_tally(store, entry, manifest.version, &mut tally, false) {
231                made_progress = true;
232            } else {
233                still_pending.push(entry);
234            }
235        }
236        if still_pending.is_empty() {
237            break;
238        }
239        if !made_progress {
240            // No entry in this pass succeeded — every remaining failure is
241            // a genuine collision, not something a further pass could
242            // resolve. Log each as such.
243            for entry in still_pending {
244                seed_and_tally(store, entry, manifest.version, &mut tally, true);
245            }
246            break;
247        }
248        pending = still_pending;
249    }
250
251    tally.log(manifest.version);
252}
253
254/// Tallies from a startup seed pass, logged once at the end (`log`).
255#[derive(Default)]
256struct SeedTally {
257    created: usize,
258    updated: usize,
259    unchanged: usize,
260    skipped_local: usize,
261    skipped_older: usize,
262    skipped_collision: usize,
263}
264
265impl SeedTally {
266    fn log(&self, manifest_version: u32) {
267        let Self { created, updated, unchanged, skipped_local, skipped_older, skipped_collision } = *self;
268        if created + updated + skipped_local + skipped_older + skipped_collision > 0 {
269            tracing::info!(
270                "operator config seed: manifest v{manifest_version}: {created} created, {updated} updated, \
271                 {unchanged} unchanged, {skipped_local} skipped (local edit), \
272                 {skipped_older} skipped (older generation), {skipped_collision} skipped (collision)",
273            );
274        }
275    }
276}
277
278/// Seeds one entry and records its outcome in `tally`. Returns `false` only
279/// for a collision-type error (`Err`) — the caller's signal to retry once
280/// more after the full first pass, in case another entry processed later
281/// would have released the colliding name. `is_retry` only affects
282/// logging: a first-pass failure is silent (might still resolve), a
283/// second-pass failure is a real, logged collision.
284fn seed_and_tally(store: &Arc<Store>, entry: &SeedEntry, manifest_version: u32, tally: &mut SeedTally, is_retry: bool) -> bool {
285    match seed_one(store, entry, manifest_version) {
286        Ok(BundleReseedOutcome::Created) => { tally.created += 1; true }
287        Ok(BundleReseedOutcome::Updated) => { tally.updated += 1; true }
288        Ok(BundleReseedOutcome::Unchanged) => { tally.unchanged += 1; true }
289        Ok(BundleReseedOutcome::SkippedLocalEdit) => {
290            tally.skipped_local += 1;
291            tracing::info!(
292                id = %entry.id,
293                "operator config seed: skipping — entry has a local (non-AgentMux) edit, not overwriting"
294            );
295            true
296        }
297        Ok(BundleReseedOutcome::SkippedOlderGeneration) => {
298            tally.skipped_older += 1;
299            tracing::info!(
300                id = %entry.id,
301                manifest_version,
302                "operator config seed: skipping — a newer manifest generation already seeded this row \
303                 (this build's own manifest is older; likely a different AgentMux version sharing this store)"
304            );
305            true
306        }
307        Ok(BundleReseedOutcome::SkippedRetired) => {
308            tally.skipped_older += 1;
309            tracing::info!(
310                id = %entry.id,
311                manifest_version,
312                "operator config seed: skipping — a newer manifest generation already retired this id \
313                 (this build's own manifest still lists it; not resurrecting it)"
314            );
315            true
316        }
317        Err(e) => {
318            if is_retry {
319                tally.skipped_collision += 1;
320                tracing::warn!(
321                    id = %entry.id,
322                    name = %entry.name,
323                    error = %e,
324                    "operator config seed: skipping entry due to upsert error (name collision?)"
325                );
326            }
327            false
328        }
329    }
330}
331
332/// A row for an entry AgentMux itself removed (or renamed to a new id) in a
333/// later release must not linger as a seeder-owned `is_system` row forever —
334/// it would keep being injected into every future agent indefinitely,
335/// exactly the "stale Operator Config actively misleads an agent" failure
336/// mode this whole seeding mechanism exists to prevent (Codex P2, PR #3244).
337/// Only prunes rows still owned by this seeder AND whose own recorded
338/// generation is <= this process's manifest version (`bundle_delete_system_
339/// if_owned` checks both atomically) — on a machine sharing store.db across
340/// multiple AgentMux builds/versions, an OLDER build's manifest simply
341/// doesn't mention an entry a NEWER build already added; without the
342/// generation gate, the older build would misread "not in my manifest" as
343/// "removed" and delete the newer build's own addition. Same "never clobber
344/// a local edit" posture as the reseed path for a human-edited row: left in
345/// place, orphaned from the manifest but not clobbered, for a human to
346/// clean up. Codex P2, PR #3244.
347fn prune_entries_removed_from_manifest(store: &Arc<Store>, manifest: &SeedManifest) {
348    let manifest_ids: std::collections::HashSet<&str> =
349        manifest.entries.iter().map(|e| e.id.as_str()).collect();
350
351    let existing_ids = match store.bundle_list_system_ids() {
352        Ok(ids) => ids,
353        Err(e) => {
354            tracing::error!("operator config seed: failed to list existing system entries for pruning: {e}");
355            return;
356        }
357    };
358
359    let mut pruned = 0usize;
360    for id in existing_ids {
361        if manifest_ids.contains(id.as_str()) {
362            continue;
363        }
364        match store.bundle_delete_system_if_owned(&id, WRITTEN_BY, manifest.version) {
365            Ok(true) => {
366                pruned += 1;
367                tracing::info!(id = %id, "operator config seed: pruned an entry no longer in the manifest");
368            }
369            Ok(false) => {
370                tracing::info!(
371                    id = %id,
372                    "operator config seed: an entry is no longer in this manifest but was left in place \
373                     (either it has a local edit, or its own generation is newer than this manifest's — \
374                     likely a different, newer AgentMux build sharing this store)"
375                );
376            }
377            Err(e) => {
378                tracing::warn!(id = %id, error = %e, "operator config seed: failed to prune an entry no longer in the manifest");
379            }
380        }
381    }
382    if pruned > 0 {
383        tracing::info!("operator config seed: pruned {pruned} entries no longer in the manifest");
384    }
385}
386
387fn seed_one(store: &Arc<Store>, entry: &SeedEntry, manifest_version: u32) -> Result<BundleReseedOutcome, StoreError> {
388    let now = agentmux_common::time::now_ms();
389    let bundle = Bundle {
390        id: entry.id.clone(),
391        name: entry.name.clone(),
392        description: String::new(),
393        is_blank: false,
394        is_global: true,
395        provider: String::new(),
396        model: String::new(),
397        instructions: entry.instructions.clone(),
398        instructions_by_provider: "{}".to_string(),
399        context_files: "[]".to_string(),
400        mcp_servers: "[]".to_string(),
401        skills: "[]".to_string(),
402        sort_order: 0,
403        created_at: now,
404        updated_at: now,
405        is_system: true,
406    };
407
408    // manifest_version travels in source_detail so bundle_reseed_system_if_
409    // owned can refuse to let an older AgentMux build's own (older) manifest
410    // downgrade a newer build's already-seeded content on a shared store.db
411    // (Codex P2, PR #3244).
412    let source_detail = format!(r#"{{"manifest_version":{manifest_version}}}"#);
413    store.bundle_reseed_system_if_owned(&bundle, WRITTEN_BY, "agentmux_operator_config_seed", &source_detail)
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419
420    fn test_store() -> Arc<Store> {
421        Arc::new(Store::open_in_memory().unwrap())
422    }
423
424    fn entry(id: &str, name: &str, instructions: &str) -> SeedEntry {
425        SeedEntry {
426            id: id.to_string(),
427            name: name.to_string(),
428            instructions: instructions.to_string(),
429            agent_types: Vec::new(),
430        }
431    }
432
433    #[test]
434    fn embedded_manifest_parses() {
435        let manifest: SeedManifest = serde_json::from_str(SEED_MANIFEST).expect("valid JSON");
436        assert!(!manifest.entries.is_empty());
437        for e in &manifest.entries {
438            assert!(!e.id.is_empty());
439            assert!(!e.name.is_empty());
440            assert!(!e.instructions.trim().is_empty());
441        }
442    }
443
444    #[test]
445    fn fresh_install_creates_every_entry() {
446        let store = test_store();
447        let e = entry("op-1", "Operator One", "body one");
448        let outcome = seed_one(&store, &e, 1).unwrap();
449        assert!(matches!(outcome, BundleReseedOutcome::Created));
450
451        let bundle = store.bundle_get("op-1").unwrap().expect("row exists");
452        assert!(bundle.is_system);
453        assert!(bundle.is_global);
454        assert_eq!(bundle.instructions, "body one");
455
456        let history = store.bundle_version_list("op-1").unwrap();
457        assert_eq!(history.len(), 1);
458        assert_eq!(history[0].written_by, WRITTEN_BY);
459    }
460
461    #[test]
462    fn unchanged_manifest_is_a_no_op() {
463        let store = test_store();
464        let e = entry("op-1", "Operator One", "body one");
465        seed_one(&store, &e, 1).unwrap();
466
467        let outcome = seed_one(&store, &e, 1).unwrap();
468        assert!(matches!(outcome, BundleReseedOutcome::Unchanged));
469        assert_eq!(store.bundle_version_list("op-1").unwrap().len(), 1, "no new version on no-op");
470    }
471
472    /// Codex P2, PR #3244: content being unchanged must not mean the
473    /// recorded generation stays stale — a newer manifest generation whose
474    /// text happens to match what's already stored (e.g. a revert to an
475    /// earlier generation's exact wording) still needs to record that a
476    /// newer generation has now confirmed this content, or a concurrently
477    /// running build on a generation in between could later pass the
478    /// generation check against the stale recorded value and downgrade it.
479    #[test]
480    fn unchanged_content_still_advances_the_recorded_generation() {
481        let store = test_store();
482        seed_one(&store, &entry("op-1", "Operator One", "the text"), 1).unwrap();
483
484        // Generation 3's manifest text happens to be identical to
485        // generation 1's (a revert).
486        let outcome = seed_one(&store, &entry("op-1", "Operator One", "the text"), 3).unwrap();
487        assert!(matches!(outcome, BundleReseedOutcome::Unchanged), "content itself really is unchanged");
488        assert_eq!(store.bundle_version_list("op-1").unwrap().len(), 2, "the generation bump must still be recorded as a version");
489
490        // A generation-2 build, with its own different text, must not be
491        // able to downgrade generation 3's already-confirmed content just
492        // because 2 > the ORIGINAL (now-stale) recorded generation of 1.
493        let outcome = seed_one(&store, &entry("op-1", "Operator One", "generation 2's own different text"), 2).unwrap();
494        assert!(matches!(outcome, BundleReseedOutcome::SkippedOlderGeneration));
495        assert_eq!(store.bundle_get("op-1").unwrap().unwrap().instructions, "the text");
496    }
497
498    #[test]
499    fn changed_manifest_content_overwrites_when_seeder_owns_it() {
500        let store = test_store();
501        let e1 = entry("op-1", "Operator One", "body one");
502        seed_one(&store, &e1, 1).unwrap();
503
504        let e2 = entry("op-1", "Operator One", "body TWO");
505        let outcome = seed_one(&store, &e2, 2).unwrap();
506        assert!(matches!(outcome, BundleReseedOutcome::Updated));
507
508        let bundle = store.bundle_get("op-1").unwrap().unwrap();
509        assert_eq!(bundle.instructions, "body TWO");
510        assert_eq!(store.bundle_version_list("op-1").unwrap().len(), 2);
511    }
512
513    /// Codex P2, PR #3244: a compatible-schema OLDER build sharing this
514    /// store might still run a pre-#3244 `upsertsystemmemory` handler that
515    /// calls the unversioned `bundle_upsert_system` directly — changing the
516    /// live row's content without ever touching `db_bundle_versions`. The
517    /// latest version would then (wrongly) still show the seeder as the
518    /// last writer. seed_one must notice the live content no longer
519    /// matches what that version claims, and refuse to overwrite it as if
520    /// nothing had happened.
521    #[test]
522    fn unrecorded_edit_from_an_unversioned_writer_is_never_overwritten() {
523        let store = test_store();
524        seed_one(&store, &entry("op-1", "Operator One", "seeded body"), 1).unwrap();
525
526        // Simulate an older build's unversioned write path: bundle_upsert_
527        // system changes db_bundles directly, recording no version at all.
528        let mut edited = store.bundle_get("op-1").unwrap().unwrap();
529        edited.instructions = "edited by an older, unversioned build".to_string();
530        store.bundle_upsert_system(&edited).unwrap();
531
532        // db_bundle_versions still shows the seeder as the last writer —
533        // the whole point of this test.
534        let history = store.bundle_version_list("op-1").unwrap();
535        assert_eq!(history.len(), 1, "the unversioned write left no trace in the version table");
536        assert_eq!(history[0].written_by, WRITTEN_BY);
537
538        let outcome = seed_one(&store, &entry("op-1", "Operator One", "a real manifest update"), 2).unwrap();
539        assert!(matches!(outcome, BundleReseedOutcome::SkippedLocalEdit));
540
541        let bundle = store.bundle_get("op-1").unwrap().unwrap();
542        assert_eq!(bundle.instructions, "edited by an older, unversioned build", "the unrecorded edit must survive");
543    }
544
545    /// ReAgent P2, PR #3244: a row that exists but has ZERO version history
546    /// at all (possible via the still-present unversioned bundle_upsert_
547    /// system, with no prior seed_one call to have created one) must be
548    /// left alone by seed_one, same conservative policy bundle_delete_
549    /// system_if_owned already implements for the identical edge case —
550    /// not silently overwritten by falling through to the unconditional
551    /// upsert.
552    #[test]
553    fn row_with_zero_version_history_is_never_overwritten() {
554        let store = test_store();
555        // Created via the plain, unversioned path directly — no seed_one
556        // call precedes this, so db_bundle_versions has nothing for "op-1".
557        let bundle = Bundle {
558            id: "op-1".to_string(),
559            name: "Operator One".to_string(),
560            description: String::new(),
561            is_blank: false,
562            is_global: true,
563            provider: String::new(),
564            model: String::new(),
565            instructions: "content with no version history".to_string(),
566            instructions_by_provider: "{}".to_string(),
567            context_files: "[]".to_string(),
568            mcp_servers: "[]".to_string(),
569            skills: "[]".to_string(),
570            sort_order: 0,
571            created_at: 0,
572            updated_at: 0,
573            is_system: true,
574        };
575        store.bundle_upsert_system(&bundle).unwrap();
576        assert!(store.bundle_version_list("op-1").unwrap().is_empty(), "precondition: no version history at all");
577
578        let outcome = seed_one(&store, &entry("op-1", "Operator One", "a manifest update"), 1).unwrap();
579        assert!(matches!(outcome, BundleReseedOutcome::SkippedLocalEdit));
580        assert_eq!(store.bundle_get("op-1").unwrap().unwrap().instructions, "content with no version history");
581    }
582
583    /// Codex P2, PR #3244: two AgentMux builds sharing store.db (a supported
584    /// configuration — see "Multiple Instances Run in Parallel" in this
585    /// repo's own CLAUDE.md) must not let an older build's own older
586    /// manifest downgrade a row a newer build already seeded, even though
587    /// both share the same `written_by` seeder identity.
588    #[test]
589    fn older_manifest_generation_never_downgrades_a_newer_seed() {
590        let store = test_store();
591        let e_v3 = entry("op-1", "Operator One", "content from generation 3");
592        seed_one(&store, &e_v3, 3).unwrap();
593
594        // A different (older) AgentMux build, running its own older
595        // manifest (generation 1), starts up and reseeds the same row.
596        let e_v1 = entry("op-1", "Operator One", "content from generation 1");
597        let outcome = seed_one(&store, &e_v1, 1).unwrap();
598        assert!(matches!(outcome, BundleReseedOutcome::SkippedOlderGeneration));
599
600        let bundle = store.bundle_get("op-1").unwrap().unwrap();
601        assert_eq!(bundle.instructions, "content from generation 3", "newer generation's content must survive");
602    }
603
604    /// The load-bearing guarantee (spec §3.3, §5 test plan): a human edit
605    /// through Memory must survive the next startup's reseed even
606    /// though the manifest content differs from what's stored. Simulated via
607    /// `bundle_upsert_system_with_version(..., "armory-ui", ...)` — the exact
608    /// call `upsertsystemmemory` (`bundle.rs`) now makes for a real UI save —
609    /// not a raw `bundle_version_insert`, so this test actually exercises the
610    /// bug ReAgent/Codex flagged on PR #3244: an earlier revision of the real
611    /// handler called the non-versioned `bundle_upsert_system`, which left no
612    /// version behind at all, so the ownership check never saw the edit and
613    /// would have silently overwritten it on the next reseed.
614    #[test]
615    fn locally_edited_entry_is_never_overwritten() {
616        let store = test_store();
617        let e1 = entry("op-1", "Operator One", "body one");
618        seed_one(&store, &e1, 1).unwrap();
619
620        // Simulate a human editing this system entry via the real Memory pane
621        // save path (`upsertsystemmemory` -> `bundle_upsert_system_with_version`).
622        let edited = Bundle {
623            id: "op-1".to_string(),
624            name: "Operator One".to_string(),
625            description: String::new(),
626            is_blank: false,
627            is_global: true,
628            provider: String::new(),
629            model: String::new(),
630            instructions: "human-edited body".to_string(),
631            instructions_by_provider: "{}".to_string(),
632            context_files: "[]".to_string(),
633            mcp_servers: "[]".to_string(),
634            skills: "[]".to_string(),
635            sort_order: 0,
636            created_at: 0,
637            updated_at: 0,
638            is_system: true,
639        };
640        store.bundle_upsert_system_with_version(&edited, "armory-ui", "human", "{}").unwrap();
641
642        let e2 = entry("op-1", "Operator One", "AgentMux wants to change this");
643        let outcome = seed_one(&store, &e2, 2).unwrap();
644        assert!(matches!(outcome, BundleReseedOutcome::SkippedLocalEdit));
645
646        let bundle = store.bundle_get("op-1").unwrap().unwrap();
647        assert_eq!(bundle.instructions, "human-edited body", "seed_one made no db_bundles write on skip");
648    }
649
650    /// Codex P2, PR #3244: an entry AgentMux itself removes from a later
651    /// manifest (renamed id, retired content, ...) must not linger forever
652    /// as a seeder-owned row, still injected into every future agent.
653    #[test]
654    fn seeder_owned_entry_removed_from_manifest_is_pruned() {
655        let store = test_store();
656        seed_one(&store, &entry("op-old", "Old Entry", "old content"), 1).unwrap();
657        assert!(store.bundle_get("op-old").unwrap().is_some());
658
659        // This release's manifest no longer mentions "op-old" at all.
660        let manifest = SeedManifest { version: 2, entries: vec![entry("op-new", "New Entry", "new content")] };
661        // seed_one for the still-present entry, then run the prune pass
662        // directly (mirrors what auto_seed_on_startup does after its loop).
663        seed_one(&store, &manifest.entries[0], manifest.version).unwrap();
664        prune_entries_removed_from_manifest(&store, &manifest);
665
666        assert!(store.bundle_get("op-old").unwrap().is_none(), "seeder-owned, manifest-removed entry must be pruned");
667        assert!(store.bundle_get("op-new").unwrap().is_some(), "entries still in the manifest are untouched");
668    }
669
670    /// ReAgent P1, PR #3244: the delete-side mirror of `unrecorded_edit_
671    /// from_an_unversioned_writer_is_never_overwritten` — a compatible-
672    /// schema OLDER build's unversioned write leaves `written_by` stale at
673    /// the seeder's identity in `db_bundle_versions`, even though the live
674    /// row is now a human's edit. Pruning must notice the live content
675    /// doesn't match what that stale version claims and refuse to delete —
676    /// deleting an unrecorded edit is strictly worse than overwriting one.
677    #[test]
678    fn prune_does_not_delete_an_unrecorded_edit_from_an_unversioned_writer() {
679        let store = test_store();
680        seed_one(&store, &entry("op-old", "Old Entry", "seeded content"), 1).unwrap();
681
682        // Simulate an older build's unversioned write path.
683        let mut edited = store.bundle_get("op-old").unwrap().unwrap();
684        edited.instructions = "edited by an older, unversioned build".to_string();
685        store.bundle_upsert_system(&edited).unwrap();
686
687        // This release's manifest no longer mentions "op-old" — an
688        // ordinary prune would otherwise delete it outright.
689        let manifest = SeedManifest { version: 2, entries: vec![] };
690        prune_entries_removed_from_manifest(&store, &manifest);
691
692        let bundle = store.bundle_get("op-old").unwrap();
693        assert!(bundle.is_some(), "an unrecorded edit must never be deleted");
694        assert_eq!(bundle.unwrap().instructions, "edited by an older, unversioned build");
695    }
696
697    /// The same "never clobber a local edit" guarantee applies to pruning:
698    /// a human-edited entry that AgentMux later removes from its manifest
699    /// must be left in place, not silently deleted out from under them.
700    #[test]
701    fn locally_edited_entry_removed_from_manifest_is_not_pruned() {
702        let store = test_store();
703        seed_one(&store, &entry("op-old", "Old Entry", "old content"), 1).unwrap();
704
705        let edited = {
706            let mut b = store.bundle_get("op-old").unwrap().unwrap();
707            b.instructions = "a human edit worth keeping".to_string();
708            b
709        };
710        store.bundle_upsert_system_with_version(&edited, "armory-ui", "human", "{}").unwrap();
711
712        let manifest = SeedManifest { version: 2, entries: vec![] };
713        prune_entries_removed_from_manifest(&store, &manifest);
714
715        let bundle = store.bundle_get("op-old").unwrap();
716        assert!(bundle.is_some(), "a human-edited entry must survive even after its manifest entry is removed");
717        assert_eq!(bundle.unwrap().instructions, "a human edit worth keeping");
718    }
719
720    /// ReAgent/Codex P2, PR #3244: pruning deliberately retires a row — an
721    /// OLDER build's own manifest (which still lists the retired id) must
722    /// not resurrect it just because the row is gone. Without the
723    /// retirement tombstone, "no db_bundles row" reads exactly like "never
724    /// existed," which is precisely the bug this test guards against.
725    #[test]
726    fn seed_one_does_not_resurrect_an_entry_retired_by_a_newer_generation() {
727        let store = test_store();
728        seed_one(&store, &entry("op-old", "Old Entry", "old content"), 1).unwrap();
729
730        // A newer build (generation 5) prunes it — its own manifest no
731        // longer lists "op-old" at all.
732        assert!(store.bundle_delete_system_if_owned("op-old", WRITTEN_BY, 5).unwrap());
733        assert!(store.bundle_get("op-old").unwrap().is_none());
734
735        // An older build, still on generation 3, whose OWN manifest still
736        // lists "op-old", starts up and tries to seed it.
737        let outcome = seed_one(&store, &entry("op-old", "Old Entry", "old content"), 3).unwrap();
738        assert!(matches!(outcome, BundleReseedOutcome::SkippedRetired));
739        assert!(store.bundle_get("op-old").unwrap().is_none(), "a retired entry must not be resurrected by an older manifest");
740    }
741
742    /// The mirror case: once this process's own manifest generation has
743    /// caught up to (or passed) the retirement generation, and its own
744    /// manifest legitimately re-adds the id, creation must proceed
745    /// normally — a tombstone blocks resurrection by a STALE manifest, not
746    /// a deliberate re-introduction by a manifest that's caught up.
747    #[test]
748    fn seed_one_recreates_a_retired_entry_once_caller_generation_catches_up() {
749        let store = test_store();
750        seed_one(&store, &entry("op-old", "Old Entry", "old content"), 1).unwrap();
751        assert!(store.bundle_delete_system_if_owned("op-old", WRITTEN_BY, 5).unwrap());
752
753        let outcome = seed_one(&store, &entry("op-old", "Reintroduced Entry", "new content"), 5).unwrap();
754        assert!(matches!(outcome, BundleReseedOutcome::Created));
755        assert_eq!(store.bundle_get("op-old").unwrap().unwrap().instructions, "new content");
756    }
757
758    /// An ORDINARY human delete in Memory (`bundle_delete_system`,
759    /// via `deletesystemmemory` — records no version at all) must not leave
760    /// a tombstone behind; a manually deleted entry still comes back
761    /// exactly as before this fix (`deleted_entry_is_recreated_...` below).
762    /// Only a generation-aware prune (`bundle_delete_system_if_owned`)
763    /// leaves a tombstone.
764    #[test]
765    fn seed_one_still_recreates_after_an_ordinary_human_delete_no_tombstone() {
766        let store = test_store();
767        seed_one(&store, &entry("op-old", "Old Entry", "old content"), 1).unwrap();
768        assert!(store.bundle_delete_system("op-old").unwrap());
769
770        let outcome = seed_one(&store, &entry("op-old", "Old Entry", "old content"), 1).unwrap();
771        assert!(matches!(outcome, BundleReseedOutcome::Created));
772    }
773
774    /// Codex P2, PR #3244: on a machine sharing store.db across two
775    /// AgentMux builds, an OLDER build's prune pass must not delete an
776    /// entry a NEWER build already added just because the older build's
777    /// own manifest doesn't mention it yet — "not in my manifest" only
778    /// means "removed" when this process's own generation has caught up to
779    /// (or passed) the row's.
780    #[test]
781    fn prune_does_not_delete_an_entry_from_a_newer_generation_it_does_not_know_about() {
782        let store = test_store();
783        // A newer AgentMux build (generation 5) seeds an entry its own
784        // manifest introduced.
785        seed_one(&store, &entry("op-new", "New Entry", "added in gen 5"), 5).unwrap();
786
787        // An older build, still on generation 3, starts up. Its own
788        // manifest has no idea "op-new" exists.
789        let older_manifest = SeedManifest { version: 3, entries: vec![] };
790        prune_entries_removed_from_manifest(&store, &older_manifest);
791
792        assert!(
793            store.bundle_get("op-new").unwrap().is_some(),
794            "an older build must not delete a newer build's own addition"
795        );
796    }
797
798    /// The mirror-image case: once a build's own manifest generation has
799    /// genuinely caught up to (or passed) an entry's generation, and that
800    /// entry is still absent from its manifest, it really was removed —
801    /// pruning must proceed.
802    #[test]
803    fn prune_still_deletes_once_this_process_generation_has_caught_up() {
804        let store = test_store();
805        seed_one(&store, &entry("op-old", "Old Entry", "added in gen 1"), 1).unwrap();
806
807        let later_manifest = SeedManifest { version: 3, entries: vec![] };
808        prune_entries_removed_from_manifest(&store, &later_manifest);
809
810        assert!(store.bundle_get("op-old").unwrap().is_none(), "a genuinely-removed entry must still be pruned");
811    }
812
813    /// Codex P2, PR #3244: `bundle_delete_system` removes only `db_bundles`,
814    /// leaving the append-only version history behind. A reseed must notice
815    /// the row itself is gone and recreate it, not take the "unchanged"
816    /// shortcut just because the stale history's content hash still matches.
817    #[test]
818    fn deleted_entry_is_recreated_even_when_manifest_content_is_unchanged() {
819        let store = test_store();
820        let e = entry("op-1", "Operator One", "body one");
821        seed_one(&store, &e, 1).unwrap();
822        assert!(store.bundle_delete_system("op-1").unwrap(), "row deleted");
823        assert!(store.bundle_get("op-1").unwrap().is_none());
824        assert_eq!(store.bundle_version_list("op-1").unwrap().len(), 1, "history survives the delete");
825
826        let outcome = seed_one(&store, &e, 1).unwrap();
827        assert!(matches!(outcome, BundleReseedOutcome::Created), "row existence, not history, gates recreation");
828        assert!(store.bundle_get("op-1").unwrap().is_some());
829    }
830
831    #[test]
832    fn name_collision_with_existing_ordinary_bundle_is_skipped_not_fatal() {
833        let store = test_store();
834        // An ordinary (non-system) bundle already owns this name — db_bundles.name is UNIQUE table-wide.
835        let existing = Bundle {
836            id: "user-bundle-1".to_string(),
837            name: "Operator One".to_string(),
838            description: String::new(),
839            is_blank: false,
840            is_global: false,
841            provider: String::new(),
842            model: String::new(),
843            instructions: "unrelated user content".to_string(),
844            instructions_by_provider: "{}".to_string(),
845            context_files: "[]".to_string(),
846            mcp_servers: "[]".to_string(),
847            skills: "[]".to_string(),
848            sort_order: 0,
849            created_at: 0,
850            updated_at: 0,
851            is_system: false,
852        };
853        store.bundle_upsert(&existing).unwrap();
854
855        let e = entry("op-1", "Operator One", "body one");
856        let result = seed_one(&store, &e, 1);
857        assert!(result.is_err(), "name UNIQUE constraint should surface as an error, not silently create op-1");
858        assert!(store.bundle_get("op-1").unwrap().is_none());
859    }
860
861    /// Codex P2, PR #3244: entry B (a brand-new id) wants the display name
862    /// entry A (an existing id, unchanged) is about to release via its own
863    /// update in this SAME manifest — but B appears first in manifest
864    /// order, so its INSERT hits A's still-current name on the first pass.
865    /// The retry pass must resolve this without either entry ending up
866    /// missing, independent of manifest array order.
867    #[test]
868    fn seeding_succeeds_regardless_of_entry_order_within_one_manifest() {
869        let store = test_store();
870        seed_one(&store, &entry("op-a", "Name X", "original A content"), 1).unwrap();
871
872        // Generation 2: A keeps its id but its name changes to "Name Y",
873        // freeing up "Name X" for the brand-new "op-b". B is listed BEFORE
874        // A in this manifest — the ordering this fix must not depend on.
875        let manifest = SeedManifest {
876            version: 2,
877            entries: vec![
878                entry("op-b", "Name X", "B content"),
879                entry("op-a", "Name Y", "updated A content"),
880            ],
881        };
882        seed_from_manifest(&store, &manifest);
883
884        let a = store.bundle_get("op-a").unwrap().expect("A must still exist");
885        assert_eq!(a.name, "Name Y");
886        assert_eq!(a.instructions, "updated A content");
887
888        let b = store.bundle_get("op-b").unwrap().expect("B must exist despite the first-pass ordering collision");
889        assert_eq!(b.name, "Name X");
890        assert_eq!(b.instructions, "B content");
891    }
892
893    /// Codex P2, PR #3244: a single retry pass only resolves a 2-entry
894    /// name swap — a 3-entry dependency CHAIN (C wants B's name, B wants
895    /// A's name, A releases first) needs the retry to repeat until a full
896    /// pass makes no further progress, or the entry at the far end of the
897    /// chain (C here) is stranded until the next startup.
898    #[test]
899    fn seeding_resolves_a_three_entry_name_dependency_chain() {
900        let store = test_store();
901        seed_one(&store, &entry("op-a", "Name A", "original A"), 1).unwrap();
902        seed_one(&store, &entry("op-b", "Name B", "original B"), 1).unwrap();
903
904        // Worst-case order: C (wants B's name) and B (wants A's name) both
905        // appear BEFORE A (the one entry that can succeed outright on pass 1).
906        let manifest = SeedManifest {
907            version: 2,
908            entries: vec![
909                entry("op-c", "Name B", "C content"),
910                entry("op-b", "Name A", "updated B"),
911                entry("op-a", "Name C", "updated A"),
912            ],
913        };
914        seed_from_manifest(&store, &manifest);
915
916        assert_eq!(store.bundle_get("op-a").unwrap().unwrap().name, "Name C");
917        assert_eq!(store.bundle_get("op-b").unwrap().unwrap().name, "Name A");
918        let c = store.bundle_get("op-c").unwrap().expect("C must exist despite being at the end of the dependency chain");
919        assert_eq!(c.name, "Name B");
920        assert_eq!(c.instructions, "C content");
921    }
922
923    #[test]
924    fn auto_seed_on_startup_does_not_panic_on_real_manifest() {
925        // Smoke test: the real embedded manifest seeds cleanly into an
926        // empty store end-to-end (parse -> seed_one -> db writes).
927        let store = test_store();
928        auto_seed_on_startup(&store);
929        let manifest: SeedManifest = serde_json::from_str(SEED_MANIFEST).unwrap();
930        for e in &manifest.entries {
931            let bundle = store.bundle_get(&e.id).unwrap().expect("seeded");
932            assert!(bundle.is_system);
933        }
934    }
935
936    fn global(id: &str, is_system: bool) -> Bundle {
937        Bundle {
938            id: id.to_string(),
939            name: id.to_string(),
940            description: String::new(),
941            is_blank: false,
942            is_global: true,
943            provider: String::new(),
944            model: String::new(),
945            instructions: format!("{id} body"),
946            instructions_by_provider: "{}".to_string(),
947            context_files: "[]".to_string(),
948            mcp_servers: "[]".to_string(),
949            skills: "[]".to_string(),
950            sort_order: 0,
951            created_at: 0,
952            updated_at: 0,
953            is_system,
954        }
955    }
956
957    fn ids(bundles: &[Bundle]) -> Vec<&str> {
958        bundles.iter().map(|b| b.id.as_str()).collect()
959    }
960
961    #[test]
962    fn agent_kind_is_container_only_for_container() {
963        assert_eq!(agent_kind("container"), "container");
964        for mode in ["host", "standalone", "", "anything"] {
965            assert_eq!(agent_kind(mode), "host", "{mode:?}");
966        }
967    }
968
969    #[test]
970    fn targeted_system_entry_reaches_only_its_kind() {
971        let mut host_only = entry("op-host", "Host", "h");
972        host_only.agent_types = vec!["host".to_string()];
973        let manifest = SeedManifest { version: 1, entries: vec![entry("op-all", "All", "a"), host_only] };
974        let bundles = || vec![global("op-all", true), global("op-host", true), global("ws", false)];
975
976        assert_eq!(ids(&filter_for_runtime(bundles(), &manifest, RuntimeCaps::NATIVE)), ["op-all", "op-host", "ws"]);
977        assert_eq!(ids(&filter_for_runtime(bundles(), &manifest, RuntimeCaps::CONTAINER)), ["op-all", "ws"]);
978    }
979
980    #[test]
981    fn an_entry_audience_follows_its_agent_types() {
982        let with = |kinds: &[&str]| {
983            let mut e = entry("e", "E", "i");
984            e.agent_types = kinds.iter().map(|k| k.to_string()).collect();
985            e.audience()
986        };
987        assert_eq!(with(&[]), Some(Audience::Everyone));
988        assert_eq!(with(&["host", "container"]), Some(Audience::Everyone));
989        assert_eq!(with(&["host"]), Some(Audience::NativeOnly(HostCap::Write, HOST_ONLY_ENTRY)));
990        assert_eq!(with(&["container"]), Some(Audience::ContainerOnly));
991        // A list that names no kind this build knows reaches nobody, not everybody.
992        assert_eq!(with(&["standalone"]), None);
993    }
994
995    /// The step-5 move changes no delivery: for every entry the manifest ships, the audience picks the
996    /// same agents the `agent_types` list did.
997    #[test]
998    fn every_shipped_entry_reaches_the_same_agents_as_its_agent_types_did() {
999        let manifest: SeedManifest = serde_json::from_str(SEED_MANIFEST).expect("valid JSON");
1000        for e in &manifest.entries {
1001            for kind in ["host", "container"] {
1002                let before = e.agent_types.is_empty() || e.agent_types.iter().any(|t| t == kind);
1003                let caps = RuntimeCaps::of(RuntimeKind::parse(kind).expect("a kind").is_container());
1004                assert_eq!(e.audience().is_some_and(|a| a.permits(caps)), before, "{} for a {kind} agent", e.id);
1005            }
1006        }
1007    }
1008
1009    #[test]
1010    fn unknown_system_entries_and_workspace_entries_always_stay() {
1011        // A system row this build's manifest doesn't list (a newer build
1012        // seeded it on a shared store) is delivered, not silently dropped.
1013        let manifest = SeedManifest { version: 1, entries: vec![] };
1014        let kept = filter_for_runtime(vec![global("op-newer", true), global("ws", false)], &manifest, RuntimeCaps::CONTAINER);
1015        assert_eq!(ids(&kept), ["op-newer", "ws"]);
1016    }
1017
1018    #[test]
1019    fn workspace_entry_is_host_only_in_the_real_manifest() {
1020        let workspace = global("operator-config-workspace", true);
1021        let app_api = global("operator-config-app-api", true);
1022        let host = global_bundles_for_agent(vec![app_api.clone(), workspace.clone()], "standalone");
1023        assert_eq!(ids(&host), ["operator-config-app-api", "operator-config-workspace"]);
1024        let container = global_bundles_for_agent(vec![app_api, workspace], "container");
1025        assert_eq!(ids(&container), ["operator-config-app-api"]);
1026    }
1027}
1028
1029#[cfg(test)]
1030mod swarm_broadcast_entry_tests {
1031    use super::*;
1032
1033    fn shipped() -> SeedManifest {
1034        serde_json::from_str(SEED_MANIFEST).expect("valid JSON")
1035    }
1036
1037    #[test]
1038    fn the_swarm_broadcast_entry_ships_to_every_kind_of_agent() {
1039        let manifest = shipped();
1040        let entry = manifest.entries.iter().find(|e| e.id == "operator-config-swarm-broadcast").expect("entry present");
1041        assert!(entry.agent_types.is_empty(), "no kind filter: container agents receive broadcasts too");
1042    }
1043
1044    #[test]
1045    fn it_tells_an_agent_to_follow_a_broadcast_without_stopping_to_ask() {
1046        let manifest = shipped();
1047        let entry = manifest.entries.iter().find(|e| e.id == "operator-config-swarm-broadcast").unwrap();
1048        let text = &entry.instructions;
1049        assert!(text.contains("[BROADCAST:FROM=user VIA=swarm"), "names the exact header");
1050        assert!(text.contains("do not stop to ask for confirmation"));
1051        assert!(text.contains("It is not a jekt"));
1052        // The owner's decision does not extend to anything else: the text must not
1053        // claim the header proves anything or lifts what AgentMux enforces.
1054        assert!(text.contains("decided by AgentMux, not by this line"));
1055    }
1056
1057    #[test]
1058    fn the_header_the_entry_describes_is_the_one_srv_writes() {
1059        // Keep the prose and the producer from drifting apart.
1060        let header = crate::backend::reactive::broadcast_turn_message("agent1", 3, "m1", "x");
1061        let first = header.lines().next().unwrap();
1062        assert!(first.starts_with("[BROADCAST:FROM=user VIA=swarm TO=agent1 RECIPIENTS=3 MSGID=m1 TS="), "{first}");
1063        let manifest = shipped();
1064        let entry = manifest.entries.iter().find(|e| e.id == "operator-config-swarm-broadcast").unwrap();
1065        for field in ["FROM=user", "VIA=swarm", "TO=", "RECIPIENTS=", "MSGID=", "TS="] {
1066            assert!(entry.instructions.contains(field), "entry omits {field}");
1067        }
1068    }
1069
1070    #[test]
1071    fn the_manifest_version_moved_with_the_new_entry() {
1072        assert!(shipped().version >= 8);
1073    }
1074
1075    #[test]
1076    fn the_system_notes_it_describes_are_the_ones_srv_writes() {
1077        use crate::muxbus::delivery_status::notes;
1078        let manifest = shipped();
1079        let entry = manifest.entries.iter().find(|e| e.id == "operator-config-swarm-broadcast").unwrap();
1080        let text = &entry.instructions;
1081        assert!(text.contains(&format!("`{} ", notes::NOTE_MARKER)), "names the marker");
1082        assert!(text.contains("a jekt cannot carry one"));
1083        // The example notes keep the producer's wording (times aside).
1084        let pause = notes::pause_note(0, "MuxBus needs a sign-in");
1085        let after_time = &pause[pause.find(" (").unwrap()..];
1086        assert!(text.contains(after_time), "pause note drifted: {after_time}");
1087        assert!(text.contains("Cloud messages are paused since "));
1088        assert!(text.contains("Cloud messages resumed at "));
1089        let outage = notes::outage_note(0, 0, "MuxBus needs a sign-in", false);
1090        let after_times = &outage[outage.find(" (").unwrap()..];
1091        assert!(text.contains(after_times), "outage note drifted: {after_times}");
1092        assert!(text.contains("Cloud messages were paused 14:22\u{2013}16:31 "));
1093        assert!(text.contains("never starts a turn"), "says where a held note comes");
1094        assert!(notes::delayed_prefix(Some(0), notes::DELAYED_AFTER_MS + 1).starts_with("(sent "));
1095        assert!(text.contains("(sent 14:30, delivered 14:41)"));
1096        assert!(manifest.version >= 28);
1097    }
1098
1099    #[test]
1100    fn the_mark_on_the_persons_messages_is_the_one_srv_writes() {
1101        // Keep the prose and the producer from drifting apart.
1102        let marked = crate::backend::reactive::sanitize::user_turn_message("x");
1103        let first = marked.lines().next().unwrap();
1104        assert!(first.starts_with("[USER:FROM=user TS="), "{first}");
1105        let manifest = shipped();
1106        let entry = manifest.entries.iter().find(|e| e.id == "operator-config-swarm-broadcast").unwrap();
1107        let text = &entry.instructions;
1108        assert!(text.contains("`[USER:FROM=user TS=<unix seconds>]`"), "names the exact header");
1109        assert!(text.contains("The user sent a new message while you were working:"), "names the harness label");
1110        assert!(text.contains("prove nothing about who sent it"));
1111        assert!(text.contains("none of it is tool output"));
1112        assert!(text.contains("only as the first line of a delivered message"));
1113        assert!(text.contains("starts with none of these marks is not a message from the user"));
1114        assert!(manifest.version >= 39);
1115    }
1116
1117    #[test]
1118    fn the_kanban_mark_the_entry_describes_is_the_one_srv_writes() {
1119        let first = crate::backend::reactive::sanitize::kanban_agent_message("agent1", "x");
1120        assert_eq!(first.lines().next(), Some("[KANBAN:FROM=agent1 BY=agent]"));
1121        let manifest = shipped();
1122        let entry = manifest.entries.iter().find(|e| e.id == "operator-config-swarm-broadcast").unwrap();
1123        assert!(entry.instructions.contains("`[KANBAN:FROM=<agent> BY=agent]`"));
1124        assert!(manifest.version >= 40);
1125    }
1126}