1use rusqlite::params;
26use sha2::{Digest, Sha256};
27
28use super::error::StoreError;
29use super::store::Store;
30
31#[derive(Debug, Clone, PartialEq)]
35pub struct BundleVersion {
36 pub id: String,
37 pub bundle_id: String,
38 pub name: String,
39 pub instructions: String,
40 pub content_hash: String,
41 pub parent_version_id: Option<String>,
42 pub source: String,
43 pub source_detail: String,
44 pub written_by: String,
54 pub written_by_uid: String,
60 pub created_at: i64,
61}
62
63#[derive(Debug, Clone, PartialEq)]
66pub struct BundleVersionSummary {
67 pub id: String,
68 pub content_hash: String,
69 pub parent_version_id: Option<String>,
70 pub source: String,
71 pub source_detail: String,
72 pub written_by: String,
73 pub written_by_uid: String,
75 pub created_at: i64,
76 pub size_bytes: u64,
79 pub tokens_est: u64,
80}
81
82use agentmux_common::time::now_ms;
83
84pub fn content_hash(name: &str, instructions: &str) -> String {
90 let mut hasher = Sha256::new();
91 hasher.update(name.as_bytes());
92 hasher.update(b"\0");
93 hasher.update(instructions.as_bytes());
94 hex::encode(hasher.finalize())
95}
96
97#[allow(clippy::too_many_arguments)]
107pub(crate) fn bundle_version_insert_tx(
108 tx: &rusqlite::Transaction,
109 bundle_id: &str,
110 name: &str,
111 instructions: &str,
112 source: &str,
113 source_detail: &str,
114 written_by: &str,
115 written_by_uid: &str,
116) -> Result<BundleVersion, StoreError> {
117 let id = uuid::Uuid::new_v4().to_string();
118 let hash = content_hash(name, instructions);
119 let created_at = now_ms();
120 let parent_version_id: Option<String> = {
121 let mut stmt = tx.prepare(
122 "SELECT id FROM db_bundle_versions
123 WHERE bundle_id = ?1
124 ORDER BY created_at DESC, rowid DESC
125 LIMIT 1",
126 )?;
127 match stmt.query_row(params![bundle_id], |row| row.get::<_, String>(0)) {
128 Ok(id) => Some(id),
129 Err(rusqlite::Error::QueryReturnedNoRows) => None,
130 Err(e) => return Err(e.into()),
131 }
132 };
133 tx.execute(
134 "INSERT INTO db_bundle_versions
135 (id, bundle_id, name, instructions, content_hash, parent_version_id, source, source_detail, written_by, created_at, written_by_uid)
136 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
137 params![
138 id,
139 bundle_id,
140 name,
141 instructions,
142 hash,
143 parent_version_id,
144 source,
145 source_detail,
146 written_by,
147 created_at,
148 written_by_uid,
149 ],
150 )?;
151
152 Ok(BundleVersion {
153 id,
154 bundle_id: bundle_id.to_string(),
155 name: name.to_string(),
156 instructions: instructions.to_string(),
157 content_hash: hash,
158 parent_version_id,
159 source: source.to_string(),
160 source_detail: source_detail.to_string(),
161 written_by: written_by.to_string(),
162 written_by_uid: written_by_uid.to_string(),
163 created_at,
164 })
165}
166
167impl Store {
168 #[cfg(any(test, feature = "test-support"))]
182 pub fn bundle_version_insert(
183 &self,
184 bundle_id: &str,
185 name: &str,
186 instructions: &str,
187 source: &str,
188 source_detail: &str,
189 written_by: &str,
190 ) -> Result<BundleVersion, StoreError> {
191 let mut conn = self.conn.lock().unwrap();
192 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
193 let version = bundle_version_insert_tx(&tx, bundle_id, name, instructions, source, source_detail, written_by, "")?;
195 tx.commit()?;
196 Ok(version)
197 }
198
199 pub fn bundle_version_list(&self, bundle_id: &str) -> Result<Vec<BundleVersionSummary>, StoreError> {
211 self.bundle_versions_newest_first(bundle_id, -1)
212 }
213
214 pub fn bundle_version_latest(&self, bundle_id: &str) -> Result<Option<BundleVersionSummary>, StoreError> {
217 Ok(self.bundle_versions_newest_first(bundle_id, 1)?.into_iter().next())
218 }
219
220 fn bundle_versions_newest_first(&self, bundle_id: &str, limit: i64) -> Result<Vec<BundleVersionSummary>, StoreError> {
222 let conn = self.conn.lock().unwrap();
223 let mut stmt = conn.prepare(
224 "SELECT id, content_hash, parent_version_id, source, source_detail, written_by, created_at, written_by_uid, instructions
225 FROM db_bundle_versions
226 WHERE bundle_id = ?1
227 ORDER BY created_at DESC, rowid DESC
228 LIMIT ?2",
229 )?;
230 let rows = stmt
231 .query_map(params![bundle_id, limit], |row| {
232 Ok(BundleVersionSummary {
233 id: row.get(0)?,
234 content_hash: row.get(1)?,
235 parent_version_id: row.get(2)?,
236 source: row.get(3)?,
237 source_detail: row.get(4)?,
238 written_by: row.get(5)?,
239 created_at: row.get(6)?,
240 written_by_uid: row.get(7)?,
241 size_bytes: row.get_ref(8)?.as_str().map_or(0, |c| c.len() as u64),
242 tokens_est: row.get_ref(8)?.as_str().map_or(0, agentmux_common::tokens::estimate_tokens),
243 })
244 })?
245 .collect::<Result<Vec<_>, _>>()?;
246 Ok(rows)
247 }
248
249 pub fn bundle_version_get(&self, version_id: &str) -> Result<Option<BundleVersion>, StoreError> {
255 let conn = self.conn.lock().unwrap();
256 let mut stmt = conn.prepare(
257 "SELECT id, bundle_id, name, instructions, content_hash, parent_version_id, source, source_detail, written_by, created_at, written_by_uid
258 FROM db_bundle_versions
259 WHERE id = ?1",
260 )?;
261 match stmt.query_row(params![version_id], |row| {
262 Ok(BundleVersion {
263 id: row.get(0)?,
264 bundle_id: row.get(1)?,
265 name: row.get(2)?,
266 instructions: row.get(3)?,
267 content_hash: row.get(4)?,
268 parent_version_id: row.get(5)?,
269 source: row.get(6)?,
270 source_detail: row.get(7)?,
271 written_by: row.get(8)?,
272 created_at: row.get(9)?,
273 written_by_uid: row.get(10)?,
274 })
275 }) {
276 Ok(v) => Ok(Some(v)),
277 Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
278 Err(e) => Err(e.into()),
279 }
280 }
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 fn test_store() -> Store {
288 Store::open_shared(std::path::Path::new(":memory:")).unwrap()
289 }
290
291 #[test]
292 fn insert_chains_parent_version_id() {
293 let store = test_store();
294 let v1 = store
295 .bundle_version_insert("bundle-1", "Coding Standards", "use tabs", "agent_inferred", "{}", "agent-1")
296 .unwrap();
297 assert!(v1.parent_version_id.is_none());
298
299 let v2 = store
300 .bundle_version_insert("bundle-1", "Coding Standards", "use spaces", "agent_inferred", "{}", "agent-1")
301 .unwrap();
302 assert_eq!(v2.parent_version_id, Some(v1.id.clone()));
303 assert_ne!(v1.content_hash, v2.content_hash);
304 }
305
306 #[test]
307 fn list_is_newest_first_and_scoped_to_one_bundle() {
308 let store = test_store();
309 store
310 .bundle_version_insert("bundle-a", "A", "content 1", "agent_inferred", "{}", "agent-1")
311 .unwrap();
312 let a2 = store
313 .bundle_version_insert("bundle-a", "A", "content 2", "agent_inferred", "{}", "agent-1")
314 .unwrap();
315 store
316 .bundle_version_insert("bundle-b", "B", "unrelated", "agent_inferred", "{}", "agent-1")
317 .unwrap();
318
319 let history = store.bundle_version_list("bundle-a").unwrap();
320 assert_eq!(history.len(), 2);
321 assert_eq!(history[0].id, a2.id, "newest first");
322 }
323
324 #[test]
325 fn get_returns_full_content_by_id() {
326 let store = test_store();
327 let v = store
328 .bundle_version_insert("bundle-1", "Name", "the body", "human", "{}", "armory-ui")
329 .unwrap();
330 let fetched = store.bundle_version_get(&v.id).unwrap().expect("version exists");
331 assert_eq!(fetched.instructions, "the body");
332 assert_eq!(fetched.bundle_id, "bundle-1");
333 assert_eq!(fetched.written_by, "armory-ui");
334 }
335
336 #[test]
337 fn get_returns_none_for_unknown_id() {
338 let store = test_store();
339 assert!(store.bundle_version_get("does-not-exist").unwrap().is_none());
340 }
341
342 #[test]
343 fn renaming_without_changing_instructions_still_changes_the_hash() {
344 let store = test_store();
345 let v1 = store
346 .bundle_version_insert("bundle-1", "Old Name", "same body", "agent_inferred", "{}", "agent-1")
347 .unwrap();
348 let v2 = store
349 .bundle_version_insert("bundle-1", "New Name", "same body", "agent_inferred", "{}", "agent-1")
350 .unwrap();
351 assert_ne!(v1.content_hash, v2.content_hash, "renaming is a real edit, not a no-op");
352 }
353
354 #[test]
359 fn written_by_is_independent_of_the_caller_supplied_source() {
360 let store = test_store();
361 let v = store
362 .bundle_version_insert("bundle-1", "Name", "body", "human", "{}", "agent-should-not-be-trusted-as-human")
363 .unwrap();
364 assert_eq!(v.source, "human", "source is caller-supplied annotation, kept as-is");
365 assert_eq!(v.written_by, "agent-should-not-be-trusted-as-human", "written_by is the real, separate identity field");
366 }
367}