blob: 3d5dbf0c764eab59b0bf1c807672720fd2aa8c83 [file]
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
use super::*;
use crate::recall::{number, unsigned};
use crate::session_history::HistoryCut;
use maka_sandbox::workspace::PermissionBasis;
use serde::{Deserialize, de::IgnoredAny};
use crate::queue::QueueEntry;
use maka_agent_facts::durable::{BackendSpec, RunOrigin, RunSpec, Trigger};
fn eligible_input(
spec: &RunSpec,
kind: &str,
original: bool,
queue: Option<&QueueEntry>,
digest: &str,
indexed: Option<&str>,
basis: Option<PermissionBasis>,
) -> bool {
use maka_agent_facts::memory::MemoryAdmission::{Disabled, Enabled};
let admitted = kind == "run_admitted";
let steering = kind == "step_prepared";
if !matches!(spec.origin, RunOrigin::Local)
|| !matches!(spec.backend, BackendSpec::Model { .. })
|| (!steering && !matches!(spec.trigger, Trigger::Message { .. }))
{
return false;
}
let Some(entry) = queue else {
return original && admitted && spec.input.digest == digest;
};
let queued = &entry.request.spec;
let bound = basis == Some(spec.permission_basis)
&& spec.permission_basis == queued.permission_basis
&& spec.workspace == queued.workspace
&& spec.allowed_tools.is_none()
&& queued.allowed_tools.is_none();
matches!(queued.memory_admission, Enabled | Disabled)
&& (original || steering && bound)
&& (indexed == Some(digest) || admitted && indexed == Some(spec.input.digest.as_str()))
}
// Ignore attachments, quotes and preparation receipts when reading the original text.
#[derive(Deserialize)]
struct MessageBody {
text: String,
#[serde(default)]
preparation: Vec<IgnoredAny>,
}
#[derive(Deserialize)]
struct SourceMessage {
message_id: String,
origin: Option<IgnoredAny>,
unprepared_content: MessageBody,
}
#[derive(Deserialize)]
struct InputEnvelope {
kind: Option<String>,
content: Option<MessageBody>,
#[serde(default)]
source_messages: Vec<SourceMessage>,
message_id: Option<String>,
origin: Option<IgnoredAny>,
unprepared_content: Option<MessageBody>,
}
impl InputEnvelope {
fn user_text(self, queued: bool, message: &str, ordinal: u64) -> Option<String> {
if queued {
return (self.message_id.as_deref() == Some(message) && self.origin.is_none())
.then_some(self.unprepared_content?.text);
}
if self.kind.as_deref() != Some("message") {
return None;
}
if self.source_messages.is_empty() {
let body = self.content?;
return body.preparation.is_empty().then_some(body.text);
}
let source = self
.source_messages
.into_iter()
.nth(usize::try_from(ordinal).ok()?)?;
(source.message_id == message && source.origin.is_none())
.then_some(source.unprepared_content.text)
}
}
#[derive(Clone)]
pub struct Guard {
pub cut: HistoryCut,
pub after: u64,
pub background_steering_basis: Option<maka_sandbox::workspace::PermissionBasis>,
}
impl Guard {
pub fn check(&self, c: &Connection) -> Result<(), StoreError> {
crate::recall::checked_source_range(c, &self.cut.owner, &self.cut, self.after)?;
let backend: Option<Option<String>> = c.query_row(
"SELECT s.configuration->>'$.backend.kind' FROM session_control s JOIN session_creations r ON r.session_id=s.id
WHERE s.id=?1 AND r.ready=1 AND r.visible=1 AND s.archived=0
AND coalesce(s.configuration->>'incognito',0)=0
AND s.configuration->>'parentSessionId' IS NULL AND s.configuration->>'tools' IS NULL
AND NOT EXISTS(SELECT 1 FROM agent_rooms r WHERE r.owner=?2 AND r.session=s.id)
AND NOT EXISTS(SELECT 1 FROM session_retirements WHERE session_id=s.id AND remove_session=1)",
params![self.cut.session, serde_json::to_string(&self.cut.owner)?], |r| r.get(0)).optional()?;
let model = match backend {
None => false,
Some(Some(kind)) => kind == "model",
Some(None) => matches!(
crate::store::latest_message_backend(c, &self.cut.owner, &self.cut.session)?,
None | Some((_, maka_agent_facts::durable::BackendSpec::Model { .. }))
),
};
if !model || self.after > self.cut.through_sequence {
return Err(invalid("memory extraction source changed"));
}
Ok(())
}
pub fn contains(&self, r: &MemoryEvidenceReference) -> bool {
r.session_id == self.cut.session
&& self.after < r.sequence
&& r.sequence <= self.cut.through_sequence
}
// The commit has already checked the range and its permissions in this transaction.
pub(super) fn verify_evidence(
&self,
c: &Connection,
r: &MemoryEvidenceReference,
) -> Result<i64, StoreError> {
if self.contains(r)
&& let Some(source) = self
.sources(c, &[(r.sequence, r.item_index)], None, usize::MAX)?
.sources
.pop()
&& source.reference(&self.cut.session, &r.quote).as_ref() == Some(r)
{
return evidence_time(c, &r.session_id, source.request.as_deref(), source.at);
}
Err(invalid(
"memory extraction evidence does not match the authorized user text",
))
}
fn sources(
&self,
c: &Connection,
positions: &[(u64, u64)],
next: Option<(u64, u64)>,
max_text_bytes: usize,
) -> Result<SourcePage, StoreError> {
let mut page = SourcePage {
sources: Vec::with_capacity(positions.len()),
excluded_by_window: false,
next,
};
if positions.is_empty() {
return Ok(page);
}
// Recall addresses either a consumed RootSourceMessage or the admitted RunInput.
// Only the unprepared user text is evidence. The Recall body can append attachment
// names or contain a plugin-prepared display string; it only supplies span coordinates.
let mut stmt = c.prepare_cached(
"SELECT d.body,h.fact_id,d.at,d.fields_json->>'$[0].end',d.sequence,d.ordinal,
d.message,q.request,d.body_ref_sequence,d.body_ref_start,d.body_ref_end,
h.kind,run.original_user_run,maka_content_bytes(spec.payload,spec.encoding),
q.entry_json,d.references_json->>'$[0].digest'
FROM json_each(?3) k CROSS JOIN agent_recall_messages d
JOIN agent_session_history h ON h.sequence=d.sequence AND h.namespace_id=d.namespace_id AND h.run=d.run
JOIN agent_run_specs run ON run.run=h.run JOIN contents spec ON spec.id=run.spec_content_id
LEFT JOIN agent_queue_items q ON q.session=?2 AND q.message=d.message
WHERE d.namespace_id=?1 AND d.sequence=k.value->>0 AND d.ordinal=k.value->>1
AND h.historical=0 AND h.kind IN ('run_admitted','step_prepared','external_task_prepared')
AND d.role='\"user\"' AND d.origin_json IS NULL AND d.internal=0
AND (q.request IS NULL OR q.state='delivered' AND q.owner=run.owner AND q.accepted_run=h.run)")?;
let ns_id = crate::namespace::find_owner_id(c, &self.cut.owner, &self.cut.session)?
.ok_or_else(|| invalid("memory extraction namespace missing"))?;
let mut rows = stmt.query(params![
ns_id,
self.cut.session,
serde_json::to_string(positions)?
])?;
let mut content = c.prepare_cached(
"SELECT maka_content_bytes(payload,encoding) FROM contents WHERE content_sha256=?",
)?;
while let Some(row) = rows.next()? {
let kind: String = row.get(11)?;
let spec: RunSpec =
serde_json::from_slice(row.get_ref(13)?.as_blob().map_err(rusqlite::Error::from)?)?;
let queue: Option<QueueEntry> = row
.get_ref(14)?
.as_str_or_null()
.map_err(rusqlite::Error::from)?
.map(serde_json::from_str)
.transpose()?;
let indexed_digest = row
.get_ref(15)?
.as_str_or_null()
.map_err(rusqlite::Error::from)?;
let Some(digest) = queue
.as_ref()
.map(|entry| entry.request.source.digest.as_str())
.or(indexed_digest)
else {
continue;
};
if !eligible_input(
&spec,
&kind,
row.get(12)?,
queue.as_ref(),
digest,
indexed_digest,
self.background_steering_basis,
) {
continue;
}
let end = usize::try_from(row.get::<_, i64>(3)?)
.map_err(|_| invalid("invalid memory display span"))?;
if end > max_text_bytes {
page.excluded_by_window = true;
continue;
}
let ordinal = unsigned(row.get(5)?)?;
let mut payload = content.query([digest])?;
let row_content = payload
.next()?
.ok_or_else(|| invalid("memory extraction evidence content missing"))?;
let envelope: InputEnvelope = serde_json::from_slice(
row_content
.get_ref(0)?
.as_blob()
.map_err(rusqlite::Error::from)?,
)?;
let Some(original) = envelope.user_text(
queue.is_some(),
row.get_ref(6)?.as_str().map_err(rusqlite::Error::from)?,
ordinal,
) else {
continue;
};
let sequence = unsigned(row.get(4)?)?;
let mut text: String = row.get(0)?;
if let Some(target) = row.get::<_, Option<i64>>(8)? {
text = crate::recall::index::resolve_body_ref(
c,
ns_id,
sequence,
target,
row.get(9)?,
row.get(10)?,
)?;
}
let body = text
.get(..end)
.ok_or_else(|| invalid("invalid memory display span"))?;
if body != original || body.trim().is_empty() {
continue;
}
let fingerprint = hex::encode(Sha256::digest(text.as_bytes()));
text.truncate(end);
let fact = uuid::Uuid::parse_str(&row.get::<_, String>(1)?)
.map_err(|e| invalid(e.to_string()))?;
let fact = maka_agent_facts::durable::FactId::try_from(fact).map_err(invalid)?;
page.sources.push(Source {
sequence,
ordinal,
at: row.get(2)?,
request: row.get(7)?,
text,
fact,
fingerprint,
});
}
drop(rows);
page.sources
.sort_unstable_by_key(|source| std::cmp::Reverse(source.position()));
Ok(page)
}
}
impl Query for Guard {
type Output = ();
fn execute(self, c: &Connection) -> Result<(), StoreError> {
self.check(c)
}
}
pub struct Source {
pub text: String,
sequence: u64,
ordinal: u64,
at: i64,
request: Option<String>,
fact: maka_agent_facts::durable::FactId,
fingerprint: String,
}
impl Source {
pub fn position(&self) -> (u64, u64) {
(self.sequence, self.ordinal)
}
pub fn reference(&self, session: &str, quote: &str) -> Option<MemoryEvidenceReference> {
if quote.trim().is_empty() {
return None;
}
let start = self.text.find(quote)?;
let following = start + quote.chars().next()?.len_utf8();
if self.text[following..].contains(quote) {
return None;
}
Some(MemoryEvidenceReference {
session_id: session.into(),
sequence: self.sequence,
item_index: self.ordinal,
fact_id: self.fact.as_uuid(),
fingerprint: self.fingerprint.clone(),
start: start.try_into().ok()?,
end: (start + quote.len()).try_into().ok()?,
quote: quote.into(),
})
}
}
pub const PAGE_SIZE: usize = 16;
pub struct Page {
pub guard: Guard,
pub max_text_bytes: usize,
pub before: Option<(u64, u64)>,
}
pub struct SourcePage {
pub excluded_by_window: bool,
pub sources: Vec<Source>,
pub next: Option<(u64, u64)>,
}
impl Query for Page {
type Output = SourcePage;
fn execute(self, c: &Connection) -> Result<SourcePage, StoreError> {
self.guard.check(c)?;
let cut = &self.guard.cut;
let upper = (cut.through_sequence, i64::MAX as u64);
let before = self.before.map_or(upper, |cursor| cursor.min(upper));
// Seek the existing visible-message index and cap inspected rows as well as
// accepted sources. A long stretch of tool output cannot cause a full history scan.
const SCAN: i64 = 256;
let mut stmt = c.prepare_cached(
"SELECT sequence,ordinal,role='\"user\"' AND origin_json IS NULL
FROM agent_recall_messages INDEXED BY agent_recall_visible_order
WHERE namespace_id=? AND internal=0 AND sequence>?
AND (sequence,ordinal)<(?,?) ORDER BY sequence DESC,ordinal DESC LIMIT ?",
)?;
let mut rows = stmt.query(params![
crate::namespace::find_owner_id(c, &cut.owner, &cut.session)?,
number(self.guard.after)?,
number(before.0)?,
number(before.1)?,
SCAN + 1
])?;
let mut positions = Vec::new();
let mut last = None;
let mut next = None;
let mut inspected = 0;
while let Some(row) = rows.next()? {
if inspected == SCAN || positions.len() == PAGE_SIZE {
next = last;
break;
}
let pos = (unsigned(row.get(0)?)?, unsigned(row.get(1)?)?);
last = Some(pos);
inspected += 1;
if row.get::<_, bool>(2)? {
positions.push(pos);
}
}
drop(rows);
self.guard.sources(c, &positions, next, self.max_text_bytes)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn frozen_range_rechecks_the_effective_message_backend() {
use maka_agent_facts::durable::{BackendSpec, RunId, Trigger};
let db = Connection::open_in_memory().unwrap();
let migrations: Vec<_> = maka_event_log::ROOT_MIGRATIONS
.iter()
.chain(crate::MIGRATIONS)
.copied()
.collect();
maka_event_log::migration::run(&db, &migrations).unwrap();
db.execute_batch("INSERT INTO session_control(id,fingerprint,revision,created_at,updated_at,archived,configuration)
VALUES('chat','k',1,0,0,0,'{}');
INSERT INTO session_creations(session_id,creation_id,fingerprint,ready,visible) VALUES('chat','initial','k',1,1)").unwrap();
let (mut spec, blobs) = crate::store::stop_tests::spec();
spec.session_id = "chat".into();
let owner = spec.owner.clone();
let model = spec.backend.clone();
let executor = BackendSpec::Executor {
selection: maka_agent_facts::executor::Selection {
executor: "external".into(),
settings: Default::default(),
},
descriptor: spec.input.clone(),
};
let message = |name: &str| Trigger::Message {
message_id: name.into(),
};
let mut admit = |at, backend, trigger| {
let id = RunId::new();
spec.turn_id = id.to_string();
spec.trigger = trigger;
spec.backend = backend;
crate::sql::admit(
&db,
crate::store::Admission::with_identity(
id,
spec.clone(),
maka_agent_facts::durable::UnixMillis(at),
blobs.clone(),
),
)
.unwrap();
};
admit(1, executor.clone(), message("first"));
let schedule = Trigger::Schedule {
schedule_id: "daily".into(),
};
admit(2, model.clone(), schedule.clone());
let guard = Guard {
cut: crate::session_history::capture_at(&db, &owner, "chat", Some(0)).unwrap(),
after: 0,
background_steering_basis: None,
};
assert!(guard.check(&db).is_err());
admit(3, model.clone(), message("second"));
assert!(guard.check(&db).is_ok());
admit(4, executor, message("third"));
assert!(guard.check(&db).is_err());
admit(5, model.clone(), schedule);
assert!(guard.check(&db).is_err());
admit(6, model, message("fourth"));
assert!(guard.check(&db).is_ok());
}
#[test]
fn original_text_in_a_large_envelope_is_verified_against_the_admitted_run() {
use maka_agent_facts::{
durable::UnixMillis,
input::{MessageInput, RunInput},
memory::MemoryAdmission,
};
let db = Connection::open_in_memory().unwrap();
let migrations = maka_event_log::ROOT_MIGRATIONS
.iter()
.chain(crate::MIGRATIONS)
.copied()
.collect::<Vec<_>>();
maka_event_log::migration::run(&db, &migrations).unwrap();
db.execute_batch("INSERT INTO session_control(id,fingerprint,revision,created_at,updated_at,archived,configuration)
VALUES('chat','k',1,0,0,0,'{}');
INSERT INTO session_creations(session_id,creation_id,fingerprint,ready,visible) VALUES('chat','initial','k',1,1)").unwrap();
let (mut spec, mut blobs) = crate::store::stop_tests::spec();
let owner = spec.owner.clone();
spec.session_id = "chat".into();
spec.memory_admission = MemoryAdmission::Enabled;
let text = "Remember: use pnpm; max token: 8192";
let mut content = MessageInput::from(text);
content.quotes = Some(vec![maka_agent_facts::input::QuoteRef {
source_message_id: None,
source_turn_id: None,
label: None,
text: "quoted material".repeat(6000),
source: None,
note: None,
}]);
let blob = crate::store::ContentBlob::json(&RunInput::Message {
content,
request_fingerprint: None,
source_messages: vec![],
})
.unwrap();
spec.input = blob.reference().clone();
blobs.push(blob);
crate::sql::admit(
&db,
crate::store::Admission::new(spec, UnixMillis(25), blobs),
)
.unwrap();
crate::recall::index::catch_up_session(
&db,
&owner,
&serde_json::to_string(&owner).unwrap(),
"chat",
)
.unwrap();
let guard = Guard {
cut: crate::session_history::capture_at(&db, &owner, "chat", None).unwrap(),
after: 0,
background_steering_basis: None,
};
let page = Page {
max_text_bytes: 1024,
guard: guard.clone(),
before: None,
}
.execute(&db)
.unwrap();
assert_eq!(page.sources.len(), 1);
let source = &page.sources[0];
assert_eq!(source.text, text);
assert!(source.reference("chat", "quoted material").is_none());
let mut reference = source.reference("chat", "use pnpm").unwrap();
assert_eq!(guard.verify_evidence(&db, &reference).unwrap(), 25);
reference.start += 1;
assert!(guard.verify_evidence(&db, &reference).is_err());
}
#[test]
fn utf8_coordinates_and_overlapping_quotes_are_validated() {
let original = "隐私 私人 偏好简短。 ababa";
let source = Source {
text: original.into(),
sequence: 5,
ordinal: 1,
at: 17,
request: None,
fact: maka_agent_facts::durable::FactId::new(),
fingerprint: hex::encode(Sha256::digest(original.as_bytes())),
};
let valid = source.reference("s", "偏好简短").unwrap();
assert_eq!(
&original[valid.start as usize..valid.end as usize],
"偏好简短"
);
for forbidden in ["aba", ""] {
assert!(source.reference("s", forbidden).is_none(), "{forbidden}");
}
}
}