aKode 0.5.0: riepilogo della memoria a inizio sessione, sollecito alle azioni annunciate, daemon allineato al CLI

- ext/memoria: legge una volta per sessione la risorsa memoria://briefing
  (file di git status, budget di token, timeout breve), accetta solo un
  blocco <memoria_briefing> chiuso e limitato, lo inserisce dopo le istruzioni
  del plugin e lo tiene in cache per il thread (prefisso del prompt stabile).
  Impostazioni [memoria] briefing, briefing_timeout_ms, briefing_max_tokens.
- Turno: se il modello chiude con un messaggio che annuncia un'azione senza
  chiamare strumenti, un solo sollecito per turno ([agent] announce_nudges,
  predefinito 1, 0 lo disattiva), con avviso visibile e test sui messaggi
  osservati con Qwen.
- Daemon: sync_with_cli confronta l'eseguibile del CLI con il pacchetto del
  daemon e, se diverso, lo seleziona e riavvia solo quando non ci sono
  sessioni caricate; altrimenti avviso. Usato all'avvio della TUI, da
  `akode update`, da install.sh e da `akode app-server daemon update
  --from-cli --if-idle`. Prima un daemon preparato una volta restava alla
  versione vecchia (CLI 0.4.0 con app server 0.3.1).
- Test: snapshot del doctor indipendenti dalla versione; snapshot della TUI
  aggiornati alla 0.5.0 e allo schema dei tool appiattiti della 0.4.0.
- Versione 0.5.0 e sezione Novità nel README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-14 21:49:51 +01:00
parent 546bd1da18
commit 95f4ddcd72
52 changed files with 1267 additions and 224 deletions

View File

@@ -695,6 +695,27 @@ pub enum ThreadStoreConfig {
/// Default for `[agent] max_repeated_failures`.
pub const DEFAULT_MAX_REPEATED_FAILURES: u32 = 3;
/// Default for `[agent] announce_nudges`.
pub const DEFAULT_ANNOUNCE_NUDGES: u32 = 1;
/// Session-start briefing of the `memoria` plugin (`[memoria]`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MemoriaBriefingConfig {
pub enabled: bool,
pub timeout_ms: u64,
pub max_tokens: u32,
}
impl Default for MemoriaBriefingConfig {
fn default() -> Self {
Self {
enabled: true,
timeout_ms: 3000,
max_tokens: 1500,
}
}
}
/// Application configuration loaded from disk and merged with overrides.
#[derive(Debug, Clone, PartialEq)]
pub struct Config {
@@ -1225,6 +1246,13 @@ pub struct Config {
/// (`[agent] max_repeated_failures`). `0` disables the check.
pub max_repeated_failures: u32,
/// One-shot reminder when a turn ends with an announced but not executed action
/// (`[agent] announce_nudges`). `0` disables it.
pub announce_nudges: u32,
/// Session-start briefing of the `memoria` plugin (`[memoria]`).
pub memoria_briefing: MemoriaBriefingConfig,
/// Idle timeout for unsubscribed app-server threads.
pub thread_unload_delay: Duration,
@@ -4225,6 +4253,26 @@ impl Config {
.as_ref()
.and_then(|agent| agent.max_repeated_failures)
.unwrap_or(DEFAULT_MAX_REPEATED_FAILURES);
let announce_nudges = cfg
.agent
.as_ref()
.and_then(|agent| agent.announce_nudges)
.unwrap_or(DEFAULT_ANNOUNCE_NUDGES);
let memoria_briefing = {
let defaults = MemoriaBriefingConfig::default();
let toml = cfg.memoria.clone().unwrap_or_default();
MemoriaBriefingConfig {
enabled: toml.briefing.unwrap_or(defaults.enabled),
timeout_ms: toml
.briefing_timeout_ms
.unwrap_or(defaults.timeout_ms)
.clamp(100, 30_000),
max_tokens: toml
.briefing_max_tokens
.unwrap_or(defaults.max_tokens)
.clamp(300, 3000),
}
};
let background_terminal_max_timeout = cfg
.background_terminal_max_timeout
.unwrap_or(DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS)
@@ -4827,6 +4875,8 @@ impl Config {
code_mode,
background_terminal_max_timeout,
max_repeated_failures,
announce_nudges,
memoria_briefing,
thread_unload_delay,
ghost_snapshot,
multi_agent_v2,

View File

@@ -0,0 +1,138 @@
//! One-shot reminder for models that announce an action and end the turn without calling a tool
//! ("Correggo il file." / "Now I'll run the tests:"). Observed with Qwen on imeAI in about one
//! session out of four. The check is a conservative heuristic on the final message only; the
//! caller limits it to `[agent] announce_nudges` reminders per turn, so it cannot loop.
/// Hook id shown in the transcript for the reminder.
pub(crate) const NUDGE_ID: &str = "akode-announce-nudge";
/// Text sent back to the model as a hook prompt.
pub(crate) const NUDGE_TEXT: &str = "aKode: your last message announces an action, but you did not call any tool, so nothing happened. \
If the action is still needed, call the tool now. If you are done, reply with a short final summary of what you did.";
/// Longest final message that can still be a bare announcement (characters).
const MAX_LEN: usize = 600;
/// Openers that announce an imminent action (lowercase, accents kept).
const ANNOUNCE: &[&str] = &[
// italiano
"ora ",
"adesso ",
"procedo",
"passo a",
"passo ora",
"vado a",
"lo faccio",
"lo correggo",
"la correggo",
"eseguo",
"lancio",
"avvio",
"correggo",
"modifico",
"aggiungo",
"creo",
"scrivo",
"aggiorno",
"verifico",
"controllo",
"faccio il commit",
"faccio ora",
"committo",
"applico",
"sistemo",
"rimuovo",
"cerco",
"leggo",
"apro",
"salvo",
"inizio",
"comincio",
"proviamo",
"provo",
"riprovo",
"prima ",
"per prima cosa",
"quindi ",
"a questo punto",
// english
"let me",
"i'll ",
"i will ",
"i'm going to",
"i am going to",
"now i",
"next, i",
"next i",
"first, i",
"first i",
"let's ",
"going to ",
];
/// Phrases that close a turn properly (done, question, report).
const FINISHED: &[&str] = &[
"fatto",
"completato",
"completata",
"ho aggiunto",
"ho corretto",
"ho creato",
"ho modificato",
"ho eseguito",
"ho lanciato",
"ho fatto",
"ho aggiornato",
"ho verificato",
"è stato",
"sono stati",
"passano",
"riepilogo",
"in sintesi",
"done",
"completed",
"i added",
"i fixed",
"i created",
"i updated",
"i ran",
"all tests pass",
"summary",
];
/// True when `message` looks like an announcement of a next step that was never executed.
pub(crate) fn looks_like_unexecuted_announcement(message: &str) -> bool {
let text = message.trim();
if text.is_empty() || text.chars().count() > MAX_LEN || text.contains("```") {
return false;
}
// A question to the user is a legitimate way to end a turn.
if text.ends_with('?') {
return false;
}
let lower = text.to_lowercase();
if FINISHED.iter().any(|f| lower.contains(f)) {
return false;
}
// The last sentence (or the last line) must announce an action. Sentences end with
// punctuation followed by whitespace, so file names like `saluti.py` do not split them.
let body = lower.trim_end_matches(['.', ':', '…', '!', ' ', '\n']);
let start = [". ", ".\n", "! ", "!\n", "\n", ": "]
.iter()
.filter_map(|sep| body.rfind(sep).map(|i| i + sep.len()))
.max()
.unwrap_or(0);
let last = body[start..]
.trim_start_matches(|c: char| !c.is_alphanumeric())
.to_string();
let announces = |s: &str| ANNOUNCE.iter().any(|a| s.starts_with(a));
if announces(&last) {
return true;
}
// "…, poi faccio il commit:" or a final colon that introduces a step.
text.ends_with(':') && ANNOUNCE.iter().any(|a| lower.contains(a.trim()))
}
#[cfg(test)]
#[path = "announce_nudge_tests.rs"]
mod tests;

View File

@@ -0,0 +1,41 @@
use super::looks_like_unexecuted_announcement as announces;
#[test]
fn bare_announcements_are_detected() {
// Messages observed with Qwen on imeAI (v0.4.0 end-to-end test and phase 2 A/B).
for m in [
"Ho trovato: \"funzoni\" → \"funzioni\". Correggo il file.",
"Let me start by recalling any relevant memories and then examining the README to find the typo.",
"Ora lancio i test.",
"Perfetto, procedo con il commit:",
"Adesso aggiungo la funzione saluta_sera a saluti.py e poi faccio il commit.",
"Now I'll run the tests:",
"I'll update the changelog next.",
"Bene. Passo a scrivere il test.",
"Il file usa Unix line endings e l'encoding è normale UTF-8. La linea è esattamente ` Contiene funzoni per salutare.\\n`. Proviamo con un approccio diverso:",
"Ho le convenzioni: messaggio `saluti: ...`, funzione pura (restituisce stringa), test `unittest`, e `py_compile` prima del commit. Aggiungo la funzione, il test, verifico la sintassi e commit.",
"Perfetto: c'è già un test per `congeda`, manca quello per `saluta`. Creo il test seguendo la convenzione esistente.",
] {
assert!(announces(m), "should nudge: {m}");
}
}
#[test]
fn finished_turns_and_questions_are_left_alone() {
for m in [
"",
"Fatto: ho aggiunto saluta_sera e i test passano.",
"I test passano (3 test, OK).",
"Ho corretto il README e creato il commit «saluti: correggi refuso».",
"Vuoi che faccia anche il commit?",
"Il comando per i test è `python3 -m unittest -q`.",
"Done. All tests pass.",
"Ecco il codice:\n```python\nprint(1)\n```\nOra lo provo.",
"Per lanciare i test usa python3 -m unittest -q dalla radice del repository.",
] {
assert!(!announces(m), "should not nudge: {m}");
}
// Long reports are never treated as announcements.
let long = format!("{} Ora lancio i test.", "Analisi del codice. ".repeat(40));
assert!(!announces(&long));
}

View File

@@ -254,6 +254,7 @@ mod submission;
pub(crate) use reasoning_effort::RequestEffortUsage;
pub(crate) use submission::Submission;
mod input_queue;
mod announce_nudge;
mod loop_guard;
mod mcp;
mod mcp_prewarm;

View File

@@ -499,6 +499,8 @@ pub(crate) async fn run_turn(
let mut last_agent_message: Option<String> = None;
let mut stop_hook_active = false;
// Reminders sent this turn for announced-but-not-executed actions (`[agent] announce_nudges`).
let mut announce_nudges_sent: u32 = 0;
// Although from the perspective of codex.rs, TurnDiffTracker has the lifecycle of a Task which contains
// many turns, from the perspective of the user, it is a single turn.
let turn_diff_tracker = Arc::new(tokio::sync::Mutex::new(
@@ -792,6 +794,48 @@ pub(crate) async fn run_turn(
}
}
if !needs_follow_up
&& announce_nudges_sent < turn_context.config.announce_nudges
&& sampling_request_last_agent_message
.as_deref()
.is_some_and(super::announce_nudge::looks_like_unexecuted_announcement)
&& let Some(nudge) = build_hook_prompt_message(
&[akode_protocol::items::HookPromptFragment {
text: super::announce_nudge::NUDGE_TEXT.to_string(),
hook_run_id: super::announce_nudge::NUDGE_ID.to_string(),
metadata: akode_protocol::models::ContentItemMetadata::harness(),
}],
&sess.item_id_generator,
)
{
announce_nudges_sent += 1;
tracing::info!(
turn_id = %turn_context.sub_id,
nudges = announce_nudges_sent,
"akode: turn ended on an announced action without a tool call; nudging the model"
);
sess.send_event(
&turn_context,
EventMsg::Warning(WarningEvent {
message: "Il modello ha annunciato un'azione senza eseguirla: aKode lo sollecita una volta.".to_string(),
}),
)
.await;
sess.record_response_item_and_emit_turn_item(
&turn_context,
&step_context.settings.model_info,
nudge,
)
.await;
sess.input_queue
.accept_mailbox_delivery_for_current_turn(
&sess.active_turn,
&turn_context.sub_id,
)
.await;
continue;
}
if !needs_follow_up {
last_agent_message = sampling_request_last_agent_message;
let stop_outcome = run_turn_stop_hooks(