Skip to main content

lean_ctx_ext/core/
subagent_contract.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Sub-agent context contracts (GL#450).
3//!
4//! A briefing pack is the *contract* between a parent agent and a sub-agent:
5//! task, token budget, the facts the sub-agent needs, and the return format
6//! it must produce. Packs are deterministic — same input, byte-identical
7//! output — so they can be diffed, cached, and replayed. The return channel
8//! is the inverse: a sub-agent reports `category/key: value` lines, which the
9//! parent distills into recallable knowledge facts instead of raw transcript.
10
11use serde::{Deserialize, Serialize};
12
13use crate::core::knowledge::ProjectKnowledge;
14use crate::core::tokens::count_tokens;
15
16/// Versioned briefing pack. Field order is fixed by this struct; serialization
17/// uses `serde_json::to_string_pretty` which preserves struct order, keeping
18/// the bytes stable across runs.
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct SubAgentContractV1 {
21    pub contract_version: u32,
22    pub task: String,
23    pub budget_tokens: usize,
24    pub used_tokens: usize,
25    pub project_hash: String,
26    pub facts: Vec<ContractFact>,
27    pub return_format: String,
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
31pub struct ContractFact {
32    pub category: String,
33    pub key: String,
34    pub value: String,
35}
36
37/// Instruction embedded in every pack telling the sub-agent how to report.
38pub(crate) const RETURN_FORMAT_V1: &str = "Report results as lines of 'category/key: value'. \
39     Each line becomes a recallable fact in the parent's knowledge store. \
40     Keep values self-contained; no transcript dumps.";
41
42/// Build a deterministic briefing pack: task + the most relevant current
43/// facts, greedily filled (in stable relevance order) until `budget_tokens`
44/// is reached. The task itself is always included; the budget governs facts.
45pub fn build_briefing_pack(
46    knowledge: &ProjectKnowledge,
47    task: &str,
48    budget_tokens: usize,
49) -> SubAgentContractV1 {
50    let mut used = count_tokens(task);
51
52    // Deterministic relevance: term-coverage on the lexical index over the
53    // task's content words only (#1832), quality tie-break, then stable
54    // (category, key) ordering. recall_for_task() already filters to current
55    // facts and sorts deterministically.
56    let ranked = knowledge.recall_for_task(task);
57    // The pack carries fact values to a sub-agent: only facts that may be
58    // delivered now enter it (`ProjectKnowledge::delivery_filter`).
59    let deliverable = knowledge.delivery_filter();
60
61    let mut facts: Vec<ContractFact> = Vec::new();
62    for f in ranked.into_iter().filter(|&f| deliverable(f)) {
63        let line_tokens = count_tokens(&format!("{}/{}: {}", f.category, f.key, f.value));
64        if used + line_tokens > budget_tokens {
65            continue;
66        }
67        used += line_tokens;
68        facts.push(ContractFact {
69            category: f.category.clone(),
70            key: f.key.clone(),
71            value: f.value.clone(),
72        });
73    }
74
75    SubAgentContractV1 {
76        contract_version: 1,
77        task: task.to_string(),
78        budget_tokens,
79        used_tokens: used,
80        project_hash: knowledge.project_hash.clone(),
81        facts,
82        return_format: RETURN_FORMAT_V1.to_string(),
83    }
84}
85
86/// Serialize a pack with stable formatting (struct field order, pretty JSON).
87pub fn serialize_pack(pack: &SubAgentContractV1) -> Result<String, String> {
88    serde_json::to_string_pretty(pack).map_err(|e| format!("contract serialization failed: {e}"))
89}
90
91/// Parse sub-agent return lines (`category/key: value`) into structured
92/// facts. Lines that don't match the contract format are reported back as
93/// rejects instead of being silently dropped.
94pub fn parse_return_lines(input: &str) -> (Vec<ContractFact>, Vec<String>) {
95    let mut facts = Vec::new();
96    let mut rejected = Vec::new();
97
98    for line in input.lines() {
99        let line = line.trim();
100        if line.is_empty() {
101            continue;
102        }
103        let parsed = line.split_once(": ").and_then(|(head, value)| {
104            let (category, key) = head.split_once('/')?;
105            let category = category.trim();
106            let key = key.trim();
107            let value = value.trim();
108            if category.is_empty() || key.is_empty() || value.is_empty() {
109                return None;
110            }
111            Some(ContractFact {
112                category: category.to_string(),
113                key: key.to_string(),
114                value: value.to_string(),
115            })
116        });
117        match parsed {
118            Some(f) => facts.push(f),
119            None => rejected.push(line.to_string()),
120        }
121    }
122
123    (facts, rejected)
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use crate::core::memory_policy::MemoryPolicy;
130
131    fn knowledge_with_facts() -> (tempfile::TempDir, ProjectKnowledge) {
132        let policy = MemoryPolicy::default();
133        let k_root = tempfile::tempdir().unwrap();
134        let mut k = ProjectKnowledge::new(k_root.path().to_str().unwrap());
135        k.remember(
136            "architecture",
137            "auth",
138            "JWT RS256 authentication",
139            "s1",
140            0.9,
141            &policy,
142        );
143        k.remember(
144            "architecture",
145            "db",
146            "PostgreSQL 16 with pgvector",
147            "s1",
148            0.85,
149            &policy,
150        );
151        k.remember("deploy", "host", "AWS eu-central-1", "s1", 0.8, &policy);
152        (k_root, k)
153    }
154
155    #[test]
156    fn briefing_pack_is_deterministic() {
157        let (_root, k) = knowledge_with_facts();
158        let a = serialize_pack(&build_briefing_pack(&k, "fix authentication bug", 500)).unwrap();
159        let b = serialize_pack(&build_briefing_pack(&k, "fix authentication bug", 500)).unwrap();
160        assert_eq!(a, b, "same input must produce byte-identical packs");
161    }
162
163    #[test]
164    fn briefing_pack_respects_budget() {
165        let (_root, k) = knowledge_with_facts();
166        let tight = build_briefing_pack(&k, "authentication database deployment", 30);
167        assert!(
168            tight.used_tokens <= 30,
169            "used {} > budget 30",
170            tight.used_tokens
171        );
172        let roomy = build_briefing_pack(&k, "authentication database deployment", 5000);
173        assert!(roomy.facts.len() >= tight.facts.len());
174    }
175
176    #[test]
177    fn briefing_pack_includes_relevant_fact() {
178        let (_root, k) = knowledge_with_facts();
179        let pack = build_briefing_pack(&k, "fix authentication bug", 500);
180        assert!(
181            pack.facts.iter().any(|f| f.key == "auth"),
182            "auth fact must be selected for an authentication task: {:?}",
183            pack.facts
184        );
185        assert_eq!(pack.contract_version, 1);
186        assert_eq!(pack.return_format, RETURN_FORMAT_V1);
187    }
188
189    #[test]
190    fn briefing_pack_ignores_a_shared_generic_verb() {
191        // #1832: "fix" alone must not pull the deploy fact into the briefing.
192        let policy = MemoryPolicy::default();
193        let (_root, mut k) = knowledge_with_facts();
194        k.remember(
195            "deploy",
196            "rollout",
197            "Fix the rollout order",
198            "s1",
199            0.8,
200            &policy,
201        );
202        let pack = build_briefing_pack(&k, "fix authentication bug", 500);
203        assert!(
204            pack.facts.iter().all(|f| f.key != "rollout"),
205            "{:?}",
206            pack.facts
207        );
208    }
209
210    /// The pack carries fact values to a sub-agent: a fact bound to a file
211    /// that is gone is not ranked into it; a fact without a binding is.
212    #[test]
213    fn briefing_pack_leaves_out_a_fact_that_is_not_served() {
214        use crate::core::archive::bindings::{self, Item};
215        use crate::core::context_admission::stored::lineage_support::{governed, project, scoped};
216        let _data = governed();
217        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
218        let (_directory, root) = project();
219        std::fs::write(format!("{root}/auth.rs"), "pub fn verify_rs256() {}\n").expect("source");
220        let policy = MemoryPolicy::default();
221        let mut k = ProjectKnowledge::new(&root);
222        let bound = "JWT RS256 authentication";
223        let typed = "authentication rows live in PostgreSQL";
224        scoped(&root, || {
225            k.remember("architecture", "auth", bound, "s1", 0.9, &policy);
226            k.remember("architecture", "db", typed, "s1", 0.8, &policy);
227        });
228        let item = Item::KnowledgeFact {
229            project: &root,
230            category: "architecture",
231            key: "auth",
232        };
233        let sources =
234            bindings::sources_at(&root, &["auth.rs"], "ctx_knowledge").expect("readable source");
235        assert!(bindings::bind(&item, bound, &root, sources));
236        let keys = || {
237            scoped(&root, || {
238                build_briefing_pack(&k, "fix authentication bug", 500)
239            })
240            .facts
241            .into_iter()
242            .map(|fact| fact.key)
243            .collect::<Vec<_>>()
244        };
245
246        assert!(keys().contains(&"auth".to_owned()), "{:?}", keys());
247        assert!(keys().contains(&"db".to_owned()), "{:?}", keys());
248        std::fs::remove_file(format!("{root}/auth.rs")).expect("delete");
249        assert_eq!(keys(), ["db".to_owned()]);
250    }
251
252    #[test]
253    fn parse_return_accepts_contract_lines() {
254        let (facts, rejected) = parse_return_lines(
255            "finding/root-cause: race in session save\n\
256             decision/fix: serialize via mutate_locked\n\
257             \n\
258             this line is not contract formatted",
259        );
260        assert_eq!(facts.len(), 2);
261        assert_eq!(facts[0].category, "finding");
262        assert_eq!(facts[0].key, "root-cause");
263        assert_eq!(rejected.len(), 1);
264    }
265
266    #[test]
267    fn parse_return_rejects_empty_parts() {
268        let (facts, rejected) = parse_return_lines("/key: value\ncat/: value\ncat/key:    ");
269        assert!(facts.is_empty(), "{facts:?}");
270        assert_eq!(rejected.len(), 3);
271    }
272}