1use crate::store::read_versioned;
5use kernel::store::DocumentStore;
6use serde_json::{Map, Value, json};
7use std::sync::{Arc, Mutex};
8
9pub const HINT_TAGS: &[&str] = &[
10 "stuck-loop",
11 "job-detached",
12 "blocked-on-job",
13 "poll-loop",
14 "repeated-failure",
15 "repeated-cell",
16 "large-read",
17 "output-truncated",
18];
19
20pub struct HintsModule {
21 store: Arc<dyn DocumentStore>,
22 lanes: Mutex<Option<Map<String, Value>>>,
24}
25
26fn tags(value: Option<&Value>) -> Result<Vec<String>, String> {
27 let items = value
28 .and_then(Value::as_array)
29 .filter(|items| !items.is_empty())
30 .ok_or("hint tags must be one or more strings")?;
31 items
32 .iter()
33 .map(|tag| match tag.as_str() {
34 Some(tag) if HINT_TAGS.contains(&tag) => Ok(tag.to_string()),
35 _ => Err(format!(
36 "Unknown hint tag {}; tags: {}",
37 jsrt::json::stringify(tag),
38 HINT_TAGS.join(", ")
39 )),
40 })
41 .collect()
42}
43
44impl HintsModule {
45 pub fn new(store: Arc<dyn DocumentStore>) -> Self {
46 Self {
47 store,
48 lanes: Mutex::new(None),
49 }
50 }
51
52 fn load(&self, lanes: &mut Option<Map<String, Value>>) -> Result<(), String> {
53 if lanes.is_some() {
54 return Ok(());
55 }
56 let saved = read_versioned("ultron.module/hints", self.store.read()?, "version")?;
57 let mut loaded = Map::new();
58 if let Some(Value::Object(saved)) = saved.as_ref().and_then(|saved| saved.get("lanes")) {
59 for (lane, entry) in saved {
60 let muted: Vec<Value> = entry["muted"]
61 .as_array()
62 .map(|items| items.iter().filter(|tag| tag.is_string()).cloned().collect())
63 .unwrap_or_default();
64 let fired = entry
65 .get("fired")
66 .filter(|fired| fired.is_object())
67 .cloned()
68 .unwrap_or(json!({}));
69 loaded.insert(lane.clone(), json!({"muted": muted, "fired": fired}));
70 }
71 }
72 *lanes = Some(loaded);
73 Ok(())
74 }
75
76 pub fn start(&self) -> Result<(), String> {
77 self.load(&mut jsrt::sync::lock(&self.lanes))
78 }
79
80 pub fn muted(&self, lane: &str) -> Vec<String> {
81 let mut lanes = jsrt::sync::lock(&self.lanes);
82 if self.load(&mut lanes).is_err() {
83 return Vec::new();
84 }
85 lanes
86 .as_ref()
87 .and_then(|lanes| lanes.get(lane))
88 .and_then(|entry| entry["muted"].as_array())
89 .map(|items| {
90 items
91 .iter()
92 .filter_map(|tag| tag.as_str().map(str::to_string))
93 .collect()
94 })
95 .unwrap_or_default()
96 }
97
98 pub fn handle(&self, kind: &str, payload: &Map<String, Value>, lane: &str) -> Result<Value, String> {
99 let mut guard = jsrt::sync::lock(&self.lanes);
100 self.load(&mut guard)?;
101 let lanes = guard.as_mut().expect("loaded");
102 let requested = if kind == "hints.muted" {
103 Vec::new()
104 } else {
105 tags(payload.get("tags"))?
106 };
107 let entry = lanes
108 .entry(lane.to_string())
109 .or_insert_with(|| json!({"muted": [], "fired": {}}));
110 let mut muted: Vec<String> = entry["muted"]
111 .as_array()
112 .map(|items| {
113 items
114 .iter()
115 .filter_map(|tag| tag.as_str().map(str::to_string))
116 .collect()
117 })
118 .unwrap_or_default();
119 match kind {
120 "hints.mute" => {
121 muted.extend(requested);
122 muted.sort();
123 muted.dedup();
124 }
125 "hints.unmute" => muted.retain(|tag| !requested.contains(tag)),
126 "hints.muted" => {}
127 _ => return Err(kernel::ops::not_wired(kind)),
128 }
129 entry["muted"] = json!(muted);
130 if kind != "hints.muted" {
131 let document = json!({"version": 1, "lanes": lanes});
132 let _ = self.store.write(&document);
134 }
135 Ok(json!({"muted": muted}))
136 }
137}
138
139impl HintsModule {
140 pub fn fire(&self, lane: &str, candidates: &[(&'static str, String)], max: u64, stuck: bool) -> Option<String> {
144 let mut guard = jsrt::sync::lock(&self.lanes);
145 self.load(&mut guard).ok()?;
146 let lanes = guard.as_mut().expect("loaded");
147 let entry = lanes
148 .entry(lane.to_string())
149 .or_insert_with(|| json!({"muted": [], "fired": {}}));
150 let usable = |entry: &Value, tag: &str| {
151 let muted = entry["muted"].as_array().is_some_and(|m| m.iter().any(|t| t == tag));
152 !muted && entry["fired"][tag].as_u64().unwrap_or(0) < max
153 };
154 let stuck = stuck && usable(entry, "stuck-loop");
155 for (tag, text) in candidates {
156 if !usable(entry, tag) || (stuck && *tag == "repeated-failure") {
157 continue;
158 }
159 let fired = entry["fired"][*tag].as_u64().unwrap_or(0) + 1;
160 entry["fired"][*tag] = fired.into();
161 let document = json!({"version": 1, "lanes": lanes});
162 let _ = self.store.write(&document);
163 return Some(format!(
164 "[hint:{tag}] {text} (Mute this hint: `await hints.mute(\"{tag}\")`.)"
165 ));
166 }
167 None
168 }
169}
170
171impl crate::ApiModule for HintsModule {
172 fn prefixes(&self) -> &[&str] {
173 &["hints."]
174 }
175
176 fn start(&self, _host: &dyn crate::TaskHost) -> Result<(), String> {
177 HintsModule::start(self)
178 }
179
180 fn handle(&self, request: &crate::Request<'_>) -> Result<Value, String> {
181 HintsModule::handle(self, request.kind, request.payload, request.lane)
182 }
183}