Skip to main content

rinne_loop/
assembler.rs

1//! The context assembler (`CONTEXT.md` §12).
2//!
3//! Builds each node's context packet from the blackboard. This is the hardest
4//! component because no two workers share a context window. For a **harness**
5//! worker it writes a thin packet and *pins file paths* — the worker reads the
6//! repo itself. For an **API** worker it *inlines file contents* — the model
7//! sees only what is sent. Get this right or workers talk past each other.
8
9use std::path::{Path, PathBuf};
10
11use crate::dag::{Node, Plan};
12use crate::worker::{ContextPacket, InlinedFile, WorkerFamily};
13use crate::{Result, BLACKBOARD_DIR};
14use rinne_types::Blackboard;
15
16/// Builds context packets against a plan and its blackboard.
17pub struct ContextAssembler<'a> {
18    blackboard: &'a dyn Blackboard,
19    plan: &'a Plan,
20}
21
22impl<'a> ContextAssembler<'a> {
23    pub fn new(blackboard: &'a dyn Blackboard, plan: &'a Plan) -> Self {
24        Self { blackboard, plan }
25    }
26
27    /// Assemble the packet for `node`, shaped for the target worker `family`.
28    ///
29    /// `critique` carries an evaluator's feedback on loop-back (P5); pass `None`
30    /// on the first attempt.
31    pub fn build(
32        &self,
33        node: &Node,
34        family: WorkerFamily,
35        critique: Option<String>,
36    ) -> Result<ContextPacket> {
37        // The context sources are the same regardless of family: the plan's
38        // pinned `@`-mentions plus this node's named input artifacts. Only the
39        // *shaping* (paths vs. contents) differs.
40        let mentioned = &self.plan.mentioned;
41        let input_artifacts: Vec<String> = node
42            .inputs
43            .iter()
44            .filter(|i| i.as_str() != "diff") // `diff` is a special pseudo-input
45            .cloned()
46            .collect();
47
48        let mut packet = ContextPacket {
49            critique,
50            ..Default::default()
51        };
52
53        match family {
54            WorkerFamily::Harness => {
55                // Pin repo-relative mention paths, and the on-disk paths of input
56                // artifacts (under .rinne/artifacts/) for the worker to read.
57                for m in mentioned {
58                    packet.pinned_paths.push(m.clone());
59                }
60                for name in &input_artifacts {
61                    if self.blackboard.artifact_exists(name) {
62                        packet
63                            .pinned_paths
64                            .push(artifact_rel_path(name));
65                    }
66                }
67            }
68            WorkerFamily::Api => {
69                // Inline contents: the model sees only what we send.
70                let workspace = self.blackboard.workspace();
71                for m in mentioned {
72                    if let Some(file) = read_inlined(workspace, m) {
73                        packet.inlined_files.push(file);
74                    }
75                }
76                for name in &input_artifacts {
77                    if let Ok(contents) = self.blackboard.read_artifact(name) {
78                        packet.inlined_files.push(InlinedFile {
79                            path: artifact_rel_path(name),
80                            contents,
81                        });
82                    }
83                }
84            }
85        }
86
87        Ok(packet)
88    }
89}
90
91/// The workspace-relative path of a named artifact (e.g.
92/// `.rinne/artifacts/design.md`), usable by a harness worker from the repo root.
93fn artifact_rel_path(name: &str) -> PathBuf {
94    Path::new(BLACKBOARD_DIR).join("artifacts").join(name)
95}
96
97/// Cap on a single inlined file's size, so `@`-mentioning a huge (or binary)
98/// file can't blow up the API request's tokens/cost/memory. Content past the cap
99/// is truncated with a visible marker rather than sent whole.
100const MAX_INLINE_BYTES: usize = 256 * 1024;
101
102/// Read a mentioned file's contents for inlining, resolving it against the
103/// workspace. Returns `None` if it cannot be read (e.g. a directory or missing);
104/// oversized files are truncated with a marker rather than dropped.
105fn read_inlined(workspace: &Path, rel: &Path) -> Option<InlinedFile> {
106    let abs = if rel.is_absolute() {
107        rel.to_path_buf()
108    } else {
109        workspace.join(rel)
110    };
111    let mut contents = std::fs::read_to_string(&abs).ok()?;
112    if contents.len() > MAX_INLINE_BYTES {
113        // Truncate on a char boundary at or below the cap.
114        let mut cut = MAX_INLINE_BYTES;
115        while cut > 0 && !contents.is_char_boundary(cut) {
116            cut -= 1;
117        }
118        contents.truncate(cut);
119        contents.push_str("\n…[file truncated: exceeded inline size limit]\n");
120    }
121    Some(InlinedFile {
122        path: rel.to_path_buf(),
123        contents,
124    })
125}