1use std::io::{Read, Write};
11use std::path::PathBuf;
12
13use borg_trace::fingerprint::bash_read_paths;
14use serde_json::{Value, json};
15
16use crate::harness::{self, Harness};
17use crate::learn::learning;
18use crate::{collective, conscience, learn, live, outcome, predict, prefilter};
19
20pub(crate) fn state_file(session: &str) -> PathBuf {
21 let dir = std::env::var_os("BORG_STATE").map_or_else(|| PathBuf::from("/tmp/borg"), PathBuf::from);
22 let _ = std::fs::create_dir_all(&dir);
23 let safe: String = session.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
24 dir.join(format!("{safe}.ctx"))
25}
26
27pub(crate) fn append(session: &str, text: &str) {
30 if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(state_file(session)) {
31 let _ = f.write_all(format!("{text}\n").as_bytes());
32 }
33}
34
35pub(crate) fn touched(input: &Value, tool: &str) -> String {
37 let s = |k: &str| input.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
38 match tool {
39 "Bash" => {
40 let cmd = s("command");
41 let paths = bash_read_paths(&cmd);
42 if paths.is_empty() { cmd.chars().take(COMMAND_CHARS).collect() } else { paths.join(" ") }
43 }
44 "Grep" => format!("{} {}", s("pattern"), s("path")),
45 "Glob" => s("pattern"),
46 _ => {
47 let mut t = [s("file_path"), s("notebook_path"), s("path")].join(" ").trim().to_string();
48 for p in further_files(input) {
50 if !t.is_empty() {
51 t.push(' ');
52 }
53 t.push_str(p);
54 }
55 t
56 }
57 }
58}
59
60const COMMAND_CHARS: usize = borg_trace::dialogue::TOUCH_CHARS;
64
65pub(crate) fn further_files(input: &Value) -> impl Iterator<Item = &str> {
69 input.get("edits").and_then(Value::as_array).into_iter().flatten().filter_map(|e| e.get("file_path").and_then(Value::as_str)).filter(|p| !p.is_empty())
70}
71
72pub(crate) fn repo_of(cwd: &str) -> String {
73 borg_trace::repo_key(cwd).rsplit('/').next().unwrap_or_default().to_string()
74}
75
76fn stat(session: &str, input: &Value, kind: &str, fill: impl FnOnce(&mut crate::stats::Event)) {
78 let home = learn::home();
79 let mut ev = crate::stats::Event::new(kind, learn::now_ms());
80 ev.session = session.into();
81 ev.repo = repo_of(input.get("cwd").and_then(Value::as_str).unwrap_or_default());
82 ev.engineer = crate::presence::read(&home, session).map(|p| p.engineer).unwrap_or_default();
84 fill(&mut ev);
85 crate::stats::record(&home, &ev);
86}
87
88fn prompts_file(session: &str) -> PathBuf {
90 state_file(session).with_extension("prompts")
91}
92
93fn turn_id(session: &str) -> u64 {
96 std::fs::metadata(prompts_file(session)).map_or(0, |m| m.len())
97}
98
99fn where_file(session: &str) -> PathBuf {
103 state_file(session).with_extension("where")
104}
105
106fn where_now(session: &str) -> String {
109 let paths = std::fs::read_to_string(where_file(session)).unwrap_or_default();
110 let latest = std::fs::read_to_string(state_file(session).with_extension("lastprompt")).unwrap_or_default();
111 format!("{paths}\n{latest}")
112}
113
114fn note_where(session: &str, text: &str) {
115 if text.trim().is_empty() {
116 return;
117 }
118 if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(where_file(session)) {
119 let _ = writeln!(f, "{text}");
120 }
121}
122
123fn task_file(session: &str) -> PathBuf {
124 state_file(session).with_extension("task")
125}
126
127fn denied_file(session: &str) -> PathBuf {
131 state_file(session).with_extension("denied")
132}
133
134fn capture_prompt(h: &dyn Harness, session: &str, input: &Value, prompt: &str) {
137 if !learning() {
138 return;
139 }
140 let task = std::fs::read_to_string(task_file(session)).unwrap_or_default();
141 if let Ok(tool) = std::fs::read_to_string(denied_file(session)) {
142 let _ = std::fs::remove_file(denied_file(session));
143 let said = prompt.trim();
144 if said.len() > 3 && !said.starts_with('<') {
145 record(session, input, task, proposal(h, input), Some(tool), said.chars().take(learn::EXCERPT_CHARS).collect());
146 return;
147 }
148 }
149 if !learn::is_correction(prompt) || task.is_empty() {
150 let task: String = prompt.chars().take(learn::TASK_CHARS).collect();
151 let _ = std::fs::write(task_file(session), task);
152 return;
153 }
154 record(session, input, task, proposal(h, input), None, prompt.chars().take(learn::EXCERPT_CHARS).collect());
155}
156
157fn veto(h: &dyn Harness, session: &str, input: &Value, reason: &str) {
160 let _ = std::fs::remove_file(denied_file(session));
161 let cwd = input.get("cwd").and_then(Value::as_str).unwrap_or_default();
162 let task = std::fs::read_to_string(task_file(session)).unwrap_or_default();
163 let said = crate::veto::Said {
164 session,
165 repo: &repo_of(cwd),
166 engineer: &learn::engineer(cwd),
167 task: &task,
168 agent: &proposal(h, input),
169 reason,
170 ms: learn::now_ms(),
171 via: "prompt",
172 };
173 if let Ok(v) = crate::veto::record(&learn::home(), &said) {
174 append(session, &format!("#borg-episode {}", v.episode));
175 }
176}
177
178fn capture_rejection(h: &dyn Harness, session: &str, input: &Value) {
181 if !learning() {
182 return;
183 }
184 let error = input.get("error").and_then(Value::as_str).unwrap_or_default();
185 let tool = format!(
186 "{} {}",
187 input.get("tool_name").and_then(Value::as_str).unwrap_or_default(),
188 input.get("tool_input").map(|v| v.to_string()).unwrap_or_default().chars().take(learn::EXCERPT_CHARS).collect::<String>()
189 );
190 let Some(said) = learn::rejection(error) else {
191 if learn::denied(error) {
192 let _ = std::fs::write(denied_file(session), tool);
193 }
194 return;
195 };
196 let task = std::fs::read_to_string(task_file(session)).unwrap_or_default();
197 record(session, input, task, proposal(h, input), Some(tool), said);
198}
199
200fn proposal(h: &dyn Harness, input: &Value) -> String {
203 let t = full_proposal(h, input);
204 t.chars().rev().take(learn::PROPOSAL_CHARS).collect::<Vec<_>>().into_iter().rev().collect()
205}
206
207fn full_proposal(h: &dyn Harness, input: &Value) -> String {
210 harness::last_message(h.caps(), input)
211}
212
213fn record(session: &str, input: &Value, task: String, agent: String, rejected_tool: Option<String>, correction: String) {
214 let ms = learn::now_ms();
215 let cwd = input.get("cwd").and_then(Value::as_str).unwrap_or_default();
216 let e = learn::Episode {
217 id: format!("{}-{ms}", session.chars().take(8).collect::<String>()),
218 ms,
219 repo: repo_of(cwd),
220 session: session.into(),
221 task,
222 agent,
223 rejected_tool,
224 correction,
225 engineer: learn::engineer(cwd),
226 ..learn::Episode::default()
227 };
228 let _ = learn::record_episode(&e);
229 append(session, &format!("#borg-episode {}", e.id));
230}
231
232fn lessons(session: &str) -> Vec<conscience::Challenge> {
237 loaded(session).0
238}
239
240fn judged(all: &[conscience::Challenge], withheld: Vec<conscience::Challenge>) -> std::borrow::Cow<'_, [conscience::Challenge]> {
244 if withheld.is_empty() { all.into() } else { all.iter().cloned().chain(withheld).collect::<Vec<_>>().into() }
245}
246
247fn loaded(session: &str) -> (Vec<conscience::Challenge>, Vec<conscience::Challenge>) {
249 let before = std::env::var("BORG_BEFORE").ok().and_then(|v| v.parse().ok());
250 let mut all = conscience::load_for(&lessons_path(), before, Some(session));
251 let where_text = std::fs::read_to_string(where_file(session)).unwrap_or_default();
254 let repos = crate::systems::work_repos(&where_text);
255 if crate::systems::on() {
256 crate::systems::gate(&mut all, &repos);
257 }
258 all.retain(|c| crate::reach::deliverable(c, &repos));
260 let withheld = crate::absorb::withhold_beside(&lessons_path(), &mut all, before);
262 if crate::concepts::on() {
265 let where_text = std::fs::read_to_string(where_file(session)).unwrap_or_default();
266 let edits = std::fs::read_to_string(edits_file(session)).unwrap_or_default();
267 let latest = std::fs::read_to_string(state_file(session).with_extension("lastprompt")).unwrap_or_default();
268 crate::concepts::apply(&mut all, &crate::concepts::of_work(&edits, &where_text, &latest), crate::concepts::beta());
269 }
270 (all, withheld)
271}
272
273fn lessons_path() -> PathBuf {
275 std::env::var_os("BORG_CONSCIENCE").map(PathBuf::from).unwrap_or_else(|| learn::home().join("lessons.jsonl"))
276}
277
278fn edits_file(session: &str) -> PathBuf {
283 state_file(session).with_extension("edits")
284}
285
286fn cost_file(session: &str) -> PathBuf {
290 state_file(session).with_extension("cost")
291}
292
293fn changes_file(session: &str) -> PathBuf {
296 state_file(session).with_extension("changes")
297}
298
299fn log_cost(session: &str, line: &str) {
300 if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(cost_file(session)) {
301 let _ = writeln!(f, "{line}");
302 }
303}
304
305fn early_acted(session: &str, all: &[conscience::Challenge], final_msg: &str) -> std::collections::HashSet<String> {
312 let edits = std::fs::read_to_string(edits_file(session)).unwrap_or_default();
313 let state = std::fs::read_to_string(state_file(session)).unwrap_or_default();
314 let lines: Vec<&str> = edits.lines().filter(|l| !l.starts_with(WORK)).collect();
315 let mut out = std::collections::HashSet::new();
316 for (p, l) in lines.iter().enumerate() {
317 let Some(list) = l.strip_prefix("#borg-early ").or_else(|| l.strip_prefix("#borg-queued ")) else { continue };
318 let ids: std::collections::HashSet<&str> = ids_in(list).collect();
319 let asked: Vec<&conscience::Challenge> = all.iter().filter(|c| ids.contains(c.id.as_str())).collect();
320 let after: Vec<&str> = lines[p + 1..].iter().copied().filter(|l| !l.starts_with("#borg-")).collect();
321 let upto = state.find(&format!("{l}\n")).map_or(state.as_str(), |i| &state[..i]);
322 let before = format!("{upto}\n{}", lines[..p].join("\n"));
323 out.extend(crate::memory::resolve(&asked, all, &before, &after.join("\n"), final_msg, crate::memory::NOVEL_WORDS).0);
324 }
325 out
326}
327
328fn done_in<'a>(state: &'a str, acted: &std::collections::HashSet<String>) -> std::collections::HashSet<&'a str> {
333 let mut done = listed(state, "#borg-asked ");
334 done.extend(listed(state, "#borg-early ").into_iter().chain(listed(state, "#borg-queued ")).filter(|i| acted.contains(*i)));
335 done
336}
337
338fn had_in(state: &str) -> std::collections::HashSet<&str> {
341 let mut had = listed(state, "#borg-asked ");
342 had.extend(listed(state, "#borg-early "));
343 had.extend(listed(state, "#borg-queued "));
344 had
345}
346
347const WORK: &str = "#borg-work ";
352
353pub(crate) fn edit_text(tool: &str, input: &Value) -> Option<String> {
356 if !["edit", "write", "multiedit", "notebookedit"].contains(&tool.to_ascii_lowercase().as_str()) {
357 return None;
358 }
359 let s = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
360 let mut text = [s(input, "file_path"), s(input, "notebook_path")].join(" ");
361 for p in further_files(input) {
362 text.push(' ');
363 text.push_str(p);
364 }
365 for k in ["new_string", "content", "new_source"] {
366 text.push(' ');
367 text.push_str(&s(input, k));
368 }
369 for e in input.get("edits").and_then(Value::as_array).into_iter().flatten() {
370 text.push(' ');
371 text.push_str(&s(e, "new_string"));
372 }
373 Some(text.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(EDIT_CHARS).collect())
374}
375
376const EDIT_CHARS: usize = 600;
379
380const EVIDENCE_CHARS: usize = 4000;
386const _: () = assert!(EVIDENCE_CHARS >= 3 * predict::JUDGE_PART);
387
388pub(crate) fn one_line(text: &str, n: usize) -> String {
390 text.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(n).collect()
391}
392
393fn note_answer(h: &dyn Harness, session: &str, input: &Value) {
397 let edits = std::fs::read_to_string(edits_file(session)).unwrap_or_default();
398 let lines: Vec<&str> = edits.lines().collect();
399 let Some(i) = lines.iter().rposition(|l| l.starts_with("#borg-asked ")) else { return };
400 if lines[i + 1..].iter().any(|l| l.starts_with("#borg-answer ")) {
401 return;
402 }
403 if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(edits_file(session)) {
404 let _ = writeln!(f, "#borg-answer {}", one_line(&full_proposal(h, input), EVIDENCE_CHARS));
405 }
406}
407
408const MAX_PENDING: usize = conscience::CAP;
413const MAX_JUDGE_TRIES: usize = 2;
418
419const DELIVERED: [&str; 4] = ["#borg-asked ", "#borg-early ", "#borg-queued ", "#borg-placebo "];
424
425const ROUTED: &str = "#borg-routed ";
429
430fn is_marker(line: &str) -> bool {
433 DELIVERED.iter().any(|m| line.starts_with(m)) || line.starts_with("#borg-live ") || line.starts_with(ROUTED)
434}
435
436#[must_use]
441pub fn stripped(check: &str, lesson: &str) -> bool {
442 let mut h = blake3::Hasher::new();
443 h.update(b"borg-strip-v1\0");
444 h.update(format!("{check}\0{lesson}").as_bytes());
445 h.finalize().as_bytes()[0] & 1 == 1
446}
447
448struct Judging<'a> {
451 pending: Vec<predict::Pending<'a>>,
452 question: bool,
453 crowded: Vec<String>,
454}
455
456fn pending<'a>(session: &str, state: &str, all: &'a [conscience::Challenge], final_msg: &str, answered_only: bool, judging: &str) -> Judging<'a> {
473 let mut tries: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
474 let mut settled = std::collections::HashSet::new();
475 for l in state.lines() {
476 if let Some(l) = l.strip_prefix("#borg-judged ") {
477 let (id, label) = l.split_once('=').unwrap_or((l, ""));
478 *tries.entry(id).or_default() += 1;
479 if label.trim() != "pending" {
480 settled.insert(id);
481 }
482 } else if let Some(list) = DELIVERED.iter().find_map(|m| l.strip_prefix(m)) {
483 for id in ids_in(list) {
484 tries.remove(id);
485 settled.remove(id);
486 }
487 }
488 }
489 let edits = std::fs::read_to_string(edits_file(session)).unwrap_or_default();
490 let lines: Vec<&str> = edits.lines().collect();
491 let part = predict::JUDGE_PART;
492 struct Delivery<'l> {
494 channel: &'static str,
495 question: bool,
497 before: &'l str,
498 answers: Vec<&'l str>,
499 work: Vec<&'l str>,
500 fresh: Vec<(&'l str, &'l str, bool)>,
501 }
502 let mut deliveries: Vec<Delivery> = Vec::new();
503 for (p, l) in lines.iter().enumerate() {
504 let Some((marker, list)) = DELIVERED.iter().find_map(|m| l.strip_prefix(m).map(|rest| (*m, rest))) else { continue };
505 let question = marker == "#borg-asked ";
506 let later = &lines[p + 1..];
507 let channel = match marker {
508 "#borg-asked " if later.first().is_some_and(|n| n.starts_with("#borg-live ")) => "live",
509 "#borg-asked " => "stop",
510 "#borg-early " => "early",
511 "#borg-queued " => "queued",
512 _ => outcome::PLACEBO,
513 };
514 let answers: Vec<&str> = if question { later.iter().filter_map(|l| l.strip_prefix("#borg-answer ")).collect() } else { Vec::new() };
515 if answered_only && question && answers.is_empty() {
516 continue;
517 }
518 let before = match lines[..p].iter().rev().find(|b| !is_marker(b)) {
521 Some(b) if b.starts_with(WORK) => &b[WORK.len()..],
522 Some(b) if !b.starts_with("#borg-") => b,
523 _ => "",
524 };
525 let work: Vec<&str> = later.iter().copied().filter(|l| !l.starts_with("#borg-")).collect();
526 let (list, tag) = tagged(list);
527 let routed: std::collections::HashMap<&str, &str> =
528 later.first().and_then(|n| n.strip_prefix(ROUTED)).into_iter().flat_map(|r| r.split(',')).filter_map(|it| it.split_once('=')).collect();
529 let fresh: Vec<&str> = list
530 .split(',')
531 .map(str::trim)
532 .filter(|i| !i.is_empty() && !settled.contains(i) && tries.get(i).copied().unwrap_or(0) < MAX_JUDGE_TRIES)
533 .filter(|i| all.iter().any(|c| c.id == *i))
534 .collect();
535 let check_of = |id: &str| routed.get(id).copied().or(tag).unwrap_or_default();
536 let fresh =
537 fresh.into_iter().map(|id| (id, check_of(id), question && stripped(if check_of(id).is_empty() { judging } else { check_of(id) }, id))).collect();
538 deliveries.push(Delivery { channel, question, before, answers, work, fresh });
539 }
540 let strip: Vec<&str> = deliveries.iter().flat_map(|d| &d.fresh).filter(|f| f.2).map(|f| f.0).collect();
543 let blind = |text: &str| strip.iter().fold(text.to_string(), |t, id| crate::memory::strip_declaration(&t, id));
544 let turn = predict::clip(&one_line(&blind(final_msg), part + 1), part);
545 let mut out: Vec<(predict::Pending, bool)> = Vec::new();
547 for d in deliveries {
548 let answer = blind(&d.answers.join(" "));
550 let said = answer.to_lowercase();
551 let since: Vec<&str> = std::iter::once(answer.as_str()).filter(|a| !a.is_empty()).chain(d.work.iter().copied()).collect();
552 let after = format!("work since: {}\nthis turn: {turn}", predict::clip(&blind(&since.join(" | ")), 2 * part));
553 let before = blind(d.before);
554 for (id, check, stripped) in d.fresh {
555 let Some(c) = all.iter().find(|c| c.id == id) else { continue };
556 out.retain(|x| x.0.lesson.id != id);
558 let declared = if stripped { None } else { crate::memory::declared(&said, &id.to_lowercase()) };
559 let pending =
560 predict::Pending { lesson: c, before: before.clone(), after: after.clone(), declared, check: check.to_string(), channel: d.channel, stripped };
561 out.push((pending, d.question));
562 }
563 }
564 let questions = out.iter().filter(|x| x.1).count().min(MAX_PENDING);
565 let mut room = [MAX_PENDING - questions, questions];
566 let (mut kept, mut crowded): (Vec<(predict::Pending, bool)>, Vec<String>) = (Vec::new(), Vec::new());
567 for x in out.into_iter().rev() {
568 let r = &mut room[usize::from(x.1)];
569 if *r > 0 {
570 *r -= 1;
571 kept.push(x);
572 } else {
573 crowded.push(x.0.lesson.id.clone());
574 }
575 }
576 kept.reverse();
577 crowded.sort();
578 Judging { pending: kept.into_iter().map(|x| x.0).collect(), question: questions > 0, crowded }
579}
580
581fn without_declarations<'t>(text: &'t str, pending: &[predict::Pending]) -> std::borrow::Cow<'t, str> {
584 pending.iter().filter(|p| p.stripped).fold(std::borrow::Cow::Borrowed(text), |t, p| crate::memory::strip_declaration(&t, &p.lesson.id).into())
585}
586
587fn note_unjudged(session: &str, ids: &[String], why: &str) {
591 if !ids.is_empty() {
592 append(session, &format!("#borg-unjudged {} why={why}", ids.join(",")));
593 }
594}
595
596pub(crate) fn unjudged(state: &str) -> std::collections::HashMap<String, &'static str> {
601 let mut why: std::collections::HashMap<String, &'static str> = std::collections::HashMap::new();
602 let mut tries: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
603 for l in state.lines() {
604 if let Some(list) = DELIVERED.iter().find_map(|m| l.strip_prefix(m)) {
605 for id in ids_in(list) {
606 tries.remove(id);
607 why.insert(id.to_string(), outcome::UNJUDGED_NO_CALL);
608 }
609 } else if let Some(l) = l.strip_prefix("#borg-judged ") {
610 let (id, label) = l.split_once('=').unwrap_or((l, ""));
611 if label.trim() == "pending" {
612 let n = tries.entry(id).or_default();
613 *n += 1;
614 if *n >= MAX_JUDGE_TRIES {
615 why.insert(id.to_string(), outcome::UNJUDGED_TRIES);
616 }
617 }
618 } else if let Some(rest) = l.strip_prefix("#borg-unjudged ") {
619 let (list, reason) = rest.rsplit_once(" why=").unwrap_or((rest, ""));
620 let reason = match reason.trim() {
621 "slots" => outcome::UNJUDGED_SLOTS,
622 "failed" => outcome::UNJUDGED_FAILED,
623 _ => continue,
624 };
625 for id in list.split(',').map(str::trim).filter(|i| !i.is_empty()) {
626 if tries.get(id).copied().unwrap_or(0) < MAX_JUDGE_TRIES {
627 why.insert(id.to_string(), reason);
628 }
629 }
630 }
631 }
632 why
633}
634
635fn record_verdicts(session: &str, input: &Value, pending: &[predict::Pending], resolved: &[predict::Judged], chars: usize, call: usize) {
644 let mut records: std::collections::BTreeMap<(&str, &str, &str, bool), Vec<String>> = std::collections::BTreeMap::new();
647 let mut settled = 0;
648 for p in pending {
649 let judged = resolved.iter().find(|j| j.id == p.lesson.id);
650 let label = judged.and_then(predict::Judged::label);
651 let word = match label {
652 Some(outcome::CHANGED) => "changed",
653 Some(_) => "ignored",
654 None => "pending",
655 };
656 append(session, &format!("#borg-judged {}={word}", p.lesson.id));
657 let kind = match (label, judged) {
658 (Some(kind), _) => kind,
659 (None, Some(_)) => outcome::UNCLEAR,
660 (None, None) => continue,
661 };
662 settled += usize::from(label.is_some());
663 records.entry((kind, p.channel, p.check.as_str(), p.stripped)).or_default().push(p.lesson.id.clone());
664 }
665 log_cost(session, &format!("judge call={call} pending={} resolved={settled} chars={chars}", pending.len()));
666 if learning() {
667 let cwd = input.get("cwd").and_then(Value::as_str).unwrap_or_default();
668 let (home, ms) = (learn::home(), learn::now_ms());
669 let mut counted: std::collections::BTreeMap<(&str, &str), Vec<String>> = std::collections::BTreeMap::new();
671 for ((kind, channel, check, stripped), lessons) in records {
672 counted.entry((kind, channel)).or_default().extend(lessons.iter().cloned());
673 let o = outcome::Outcome {
674 kind: kind.into(),
675 session: session.into(),
676 lessons,
677 ms,
678 repo: repo_of(cwd),
679 channel: channel.into(),
680 check: check.into(),
681 judge: predict::JUDGE_VERSION,
682 stripped,
683 ..Default::default()
684 };
685 let _ = learn::append_jsonl(&home.join("outcomes.jsonl"), &o);
686 }
687 for ((kind, channel), lessons) in counted {
688 outcome::count_result(
689 &home,
690 &outcome::Outcome {
691 kind: kind.into(),
692 session: session.into(),
693 lessons,
694 ms,
695 repo: repo_of(cwd),
696 channel: channel.into(),
697 ..Default::default()
698 },
699 );
700 }
701 }
702}
703
704pub(crate) fn listed<'a>(context: &'a str, marker: &str) -> std::collections::HashSet<&'a str> {
706 context.lines().filter_map(|l| l.strip_prefix(marker)).flat_map(ids_in).collect()
707}
708
709fn ids_in(list: &str) -> impl Iterator<Item = &str> {
711 tagged(list).0.split(',').map(str::trim).filter(|i| !i.is_empty())
712}
713
714fn tag(check: &str) -> String {
716 if check.is_empty() { String::new() } else { format!(" @{check}") }
717}
718
719const MAX_EARLY_DELIVERIES: usize = 3;
736
737fn early(h: &dyn Harness, so_far: &SoFar, hook_event: &str, session: &str, input: &Value, text: &str) -> Option<String> {
738 if text.trim().is_empty()
739 || std::env::var("BORG_EARLY").is_ok_and(|v| v.trim().eq_ignore_ascii_case("off"))
740 || std::env::var_os("BORG_ONLY").is_some()
741 || std::env::var_os("BORG_CRITIC").is_some()
742 {
743 return None;
744 }
745 let challenges = lessons(session);
746 let context = std::fs::read_to_string(state_file(session)).unwrap_or_default();
747 let plain = h.caps().early_delivery && context.lines().filter(|l| l.starts_with("#borg-early ")).count() < MAX_EARLY_DELIVERIES;
750 let standing = challenges.iter().any(conscience::Challenge::standing);
751 if !standing && (!plain || challenges.iter().all(|c| c.scope.is_empty() && !c.consolidated)) {
752 return None;
753 }
754 let settled = listed(&context, "#borg-topic ");
755 let named = conscience::named_scopes(&challenges, &where_now(session));
756 let mut topics: Vec<String> = if plain { named.iter().filter(|t| !settled.contains(t.as_str())).cloned().collect() } else { Vec::new() };
757 if plain
759 && topics.is_empty()
760 && hook_event == "UserPromptSubmit"
761 && !settled.contains(conscience::ANY)
762 && challenges.iter().any(|c| c.consolidated && !c.standing())
763 {
764 topics.push(conscience::ANY.into());
765 }
766 let mut standing_topics = named;
768 if hook_event == "UserPromptSubmit" {
769 standing_topics.push(conscience::ANY.into());
770 }
771 let done = had_in(&context);
772 let mut pool = if standing { conscience::standing_pool(&challenges, &standing_topics, &done) } else { Vec::new() };
773 if !topics.is_empty() {
774 pool.extend(conscience::early_pool(&challenges, &conscience::work_text(&context), &topics, &done));
775 }
776 let mut shown_topics = topics.clone();
778 for t in standing_topics.into_iter().filter(|t| pool.iter().any(|(_, c)| c.standing() && c.scope.contains(t))) {
779 if !shown_topics.contains(&t) {
780 shown_topics.push(t);
781 }
782 }
783 let selected: Vec<&conscience::Challenge> = conscience::explored(pool.iter().copied()).into_iter().take(conscience::EARLY_CAP).collect();
786 let shown = conscience::render_early(&selected, &shown_topics);
787 let delivered = &selected[..shown.as_ref().map_or(0, |(_, n)| *n)];
788 let now_settled: Vec<&str> = topics
791 .iter()
792 .filter(|t| {
793 !delivered.is_empty()
795 || !challenges.iter().any(|c| {
796 !c.standing()
797 && (c.scope.contains(t) || (t.as_str() == conscience::ANY && c.consolidated))
798 && !done.contains(c.id.as_str())
799 && !delivered.iter().any(|d| d.id == c.id)
800 })
801 })
802 .map(String::as_str)
803 .collect();
804 if !now_settled.is_empty() {
805 append(session, &format!("#borg-topic {}", now_settled.join(",")));
806 }
807 let (text, _) = shown?;
808 let ids = delivered.iter().map(|c| c.id.as_str()).collect::<Vec<_>>().join(",");
809 let check = crate::select::check_id(session, "early", learn::now_ms(), std::process::id());
811 let line = format!("#borg-early {ids} @{check}");
812 append(session, &line);
813 note_work(session, so_far, &line);
814 let p = conscience::early_propensity(&pool, session, &shown_topics);
815 let p: Vec<f64> = delivered.iter().map(|c| p.get(&c.id).copied().unwrap_or(0.0)).collect();
816 record_delivery(session, input, delivered, "early", &check, p, early_rel(&challenges, &conscience::work_text(&context), &topics, delivered));
817 log_cost(session, &format!("free event={hook_event} lessons={} chars={}", delivered.len(), text.len()));
818 crate::stats::count(&learn::home(), crate::stats::EARLY, session, |e| {
819 e.n = delivered.len() as u64;
820 e.lessons = delivered.iter().map(|c| c.id.clone()).collect();
821 e.channel = "early".into();
822 });
823 Some(text)
824}
825
826fn early_rel(challenges: &[conscience::Challenge], work: &str, topics: &[String], delivered: &[&conscience::Challenge]) -> Vec<f64> {
832 let Some(&(top, _)) = conscience::early_pool(challenges, work, topics, &std::collections::HashSet::new()).first() else { return Vec::new() };
833 let ranked = conscience::rank(challenges, work);
834 delivered.iter().map(|c| outcome::round_p(ranked.iter().find(|(_, x)| x.id == c.id).map_or(0.0, |(s, _)| *s) / top)).collect()
835}
836
837fn note_work(session: &str, so_far: &SoFar, lines: &str) {
841 if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(edits_file(session)) {
842 let _ = writeln!(f, "{WORK}{}\n{lines}", one_line(so_far.get(), EVIDENCE_CHARS));
843 }
844}
845
846fn record_delivery(session: &str, input: &Value, delivered: &[&conscience::Challenge], channel: &str, check: &str, p: Vec<f64>, rel: Vec<f64>) {
852 if !learning() || delivered.is_empty() {
853 return;
854 }
855 let lessons: Vec<String> = delivered.iter().map(|c| c.id.clone()).collect();
856 let (grades, ranks, applied) = graded_of(session, &lessons);
857 let asked = outcome::Outcome {
858 kind: outcome::ASKED.into(),
859 session: session.into(),
860 lessons,
861 ms: learn::now_ms(),
862 repo: repo_of(input.get("cwd").and_then(Value::as_str).unwrap_or_default()),
863 groups: conscience::disagreement_ids(delivered),
864 channel: channel.into(),
865 grades,
866 ranks,
867 applied,
868 p: p.into_iter().map(outcome::round_p).collect(),
869 check: check.into(),
870 rel,
871 ..Default::default()
872 };
873 let _ = outcome::append(&learn::home().join("outcomes.jsonl"), &asked);
874}
875
876fn record_route(session: &str, input: &Value, check: &str, lessons: Vec<String>, channel: &str, route: &str, reason: &str) {
879 if !learning() || lessons.is_empty() {
880 return;
881 }
882 let o = outcome::Outcome {
883 kind: outcome::DELIVERY.into(),
884 session: session.into(),
885 lessons,
886 ms: learn::now_ms(),
887 repo: repo_of(input.get("cwd").and_then(Value::as_str).unwrap_or_default()),
888 channel: channel.into(),
889 check: check.into(),
890 route: route.into(),
891 reason: reason.into(),
892 ..Default::default()
893 };
894 let _ = outcome::append(&learn::home().join("outcomes.jsonl"), &o);
895}
896
897fn record_routes(session: &str, input: &Value, routed: &[(&conscience::Challenge, &str)], channel: &str, route: &str, reason: &str) {
899 for (check, ids) in by_check(routed) {
900 record_route(session, input, check, ids.into_iter().map(String::from).collect(), channel, route, reason);
901 }
902}
903
904fn by_check<'a>(routed: &[(&'a conscience::Challenge, &'a str)]) -> Vec<(&'a str, Vec<&'a str>)> {
906 let mut out: Vec<(&str, Vec<&str>)> = Vec::new();
907 for (c, check) in routed {
908 match out.iter_mut().find(|(k, _)| k == check) {
909 Some((_, ids)) => ids.push(c.id.as_str()),
910 None => out.push((check, vec![c.id.as_str()])),
911 }
912 }
913 out
914}
915
916fn queued_file(session: &str) -> PathBuf {
924 state_file(session).with_extension("queued")
925}
926
927#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
929enum Queued {
930 Ask,
931 Instead,
933 Free,
934 Placebo,
935}
936
937const INSTEAD: &str = "instead ";
944
945const INSTEAD_NEXT: &str = "instead-next ";
950
951const LIVE_NEXT: &str = "live-next ";
954
955const ASKED_INSTEAD: &str = "in place of a hand-over";
959
960fn queue_line(line: &str) -> (Queued, Vec<&str>, &str) {
962 let ask = line.strip_prefix("live ").or_else(|| line.strip_prefix(LIVE_NEXT));
963 let instead = line.strip_prefix(INSTEAD).or_else(|| line.strip_prefix(INSTEAD_NEXT));
964 let (route, list) = match (ask, line.strip_prefix("placebo "), instead) {
965 (Some(l), _, _) => (Queued::Ask, l),
966 (_, Some(l), _) => (Queued::Placebo, l),
967 (_, _, Some(l)) => (Queued::Instead, l),
968 _ => (Queued::Free, line),
969 };
970 (route, ids_in(list).collect(), tagged(list).1.unwrap_or_default())
971}
972
973fn enqueue(session: &str, line: &str) {
976 let q = queued_file(session);
977 live::locked(&q, || {
978 let _ = std::fs::OpenOptions::new().create(true).append(true).open(&q).and_then(|mut f| f.write_all(format!("{line}\n").as_bytes()));
979 });
980}
981
982fn take_queue(session: &str) -> Option<String> {
985 let q = queued_file(session);
986 let taken = state_file(session).with_extension(format!("queued.{}", std::process::id()));
987 live::locked(&q, || std::fs::rename(&q, &taken)).ok()?;
988 let text = std::fs::read_to_string(&taken).unwrap_or_default();
989 let _ = std::fs::remove_file(&taken);
990 Some(text)
991}
992
993fn take_live(session: &str) -> Taken {
1000 let Some(text) = take_queue(session) else { return Taken::default() };
1001 let mut taken = Taken::default();
1002 for line in text.lines() {
1003 let to = match (line.starts_with("live "), line.starts_with(INSTEAD)) {
1004 (true, _) => &mut taken.asks,
1005 (_, true) => &mut taken.instead,
1006 _ => {
1007 enqueue(session, line);
1008 continue;
1009 }
1010 };
1011 let (_, ids, check) = queue_line(line);
1012 to.extend(ids.into_iter().map(|i| (i.to_string(), check.to_string())));
1013 }
1014 taken
1015}
1016
1017#[derive(Default)]
1019struct Taken {
1020 asks: Vec<(String, String)>,
1022 instead: Vec<(String, String)>,
1024}
1025
1026fn waiting_in(text: &str) -> impl Iterator<Item = &str> {
1030 text.lines().map(queue_line).filter(|(route, _, _)| *route != Queued::Placebo).flat_map(|(_, ids, _)| ids)
1031}
1032
1033fn note_never_delivered(session: &str, input: &Value) {
1037 let text = std::fs::read_to_string(queued_file(session)).unwrap_or_default();
1038 for line in text.lines() {
1039 let (route, ids, check) = queue_line(line);
1040 let channel = match route {
1041 Queued::Ask => "live",
1042 Queued::Instead | Queued::Free => "queued",
1043 Queued::Placebo => outcome::PLACEBO,
1044 };
1045 record_route(session, input, check, ids.into_iter().map(String::from).collect(), channel, outcome::ROUTE_NEVER, "session ended");
1046 }
1047}
1048
1049fn tagged_p(state: &str, prefix: &str, check: &str, ids: &[&str]) -> Vec<f64> {
1052 let mut seen: std::collections::HashMap<&str, f64> = std::collections::HashMap::new();
1053 for line in state.lines().filter_map(|l| l.strip_prefix(prefix)) {
1054 let (items, at) = tagged(line);
1055 if at != Some(check) {
1056 continue;
1057 }
1058 for (id, p) in items.split(',').filter_map(|it| it.rsplit_once('=')) {
1059 if let Ok(p) = p.trim().parse::<f64>() {
1060 seen.insert(id.trim(), p);
1061 }
1062 }
1063 }
1064 ids.iter().map(|i| seen.get(i).copied()).collect::<Option<Vec<f64>>>().unwrap_or_default()
1065}
1066
1067type Pairs<'a> = Vec<(&'a conscience::Challenge, &'a str)>;
1069
1070type Drop<'a> = (&'a str, &'static str, &'static str, &'static str);
1073
1074fn queued(so_far: &SoFar, hook_event: &str, session: &str, input: &Value) -> Option<String> {
1088 let text = take_queue(session)?;
1089 let all = lessons(session);
1090 let state = std::fs::read_to_string(state_file(session)).unwrap_or_default();
1091 let had = had_in(&state);
1092 let mut done: Option<std::collections::HashSet<&str>> = None;
1093 let mut lines: Vec<(Queued, Vec<&str>, &str)> = text.lines().map(queue_line).collect();
1094 lines.sort_by_key(|l| l.0);
1097 let placebos = lines.iter().position(|l| l.0 == Queued::Placebo).unwrap_or(lines.len());
1098 let (mut firm, mut wanted, mut placebo): (Pairs, Pairs, Pairs) = (Vec::new(), Vec::new(), Vec::new());
1099 let mut dropped: Vec<(Drop, &str)> = Vec::new();
1100 let mut owed = 0;
1102 for (route, ids, check) in &lines[..placebos] {
1103 let channel = if *route == Queued::Ask { "live" } else { "queued" };
1104 for &id in ids {
1105 let Some(c) = all.iter().find(|c| c.id == id) else {
1106 dropped.push(((check, channel, outcome::ROUTE_DROPPED_DONE, "not deliverable"), id));
1107 continue;
1108 };
1109 let why = if firm.iter().chain(&wanted).any(|(c, _)| c.id == id) {
1110 Some("queued twice")
1111 } else if *route == Queued::Ask {
1112 done.get_or_insert_with(|| done_in(&state, &early_acted(session, &all, ""))).contains(id).then_some("done")
1113 } else {
1114 had.contains(id).then_some("given before")
1115 };
1116 match why {
1117 Some(why) => dropped.push(((check, channel, outcome::ROUTE_DROPPED_DONE, why), id)),
1118 None if *route == Queued::Ask => firm.push((c, check)),
1119 None => {
1120 owed += usize::from(*route == Queued::Instead);
1121 wanted.push((c, check));
1122 }
1123 }
1124 }
1125 }
1126 let free: Vec<&conscience::Challenge> = wanted.iter().map(|(c, _)| *c).collect();
1127 let shown = conscience::render_owing(&free, &[], owed);
1128 let n = shown.as_ref().map_or(0, |(_, n)| *n);
1129 dropped.extend(wanted[n..].iter().map(|(c, check)| ((*check, "queued", outcome::ROUTE_DROPPED_CHARS, "budget"), c.id.as_str())));
1130 for (_, ids, check) in &lines[placebos..] {
1133 for &id in ids {
1134 let Some(c) = all.iter().find(|c| c.id == id) else {
1135 dropped.push(((check, outcome::PLACEBO, outcome::ROUTE_DROPPED_DONE, "not deliverable"), id));
1136 continue;
1137 };
1138 let why = if placebo.iter().any(|(c, _)| c.id == id) {
1139 Some("queued twice")
1140 } else {
1141 (firm.iter().chain(&wanted[..n]).any(|(c, _)| c.id == id) || had.contains(id)).then_some("delivered")
1142 };
1143 match why {
1144 Some(why) => dropped.push(((check, outcome::PLACEBO, outcome::ROUTE_DROPPED_DONE, why), id)),
1145 None => placebo.push((c, check)),
1146 }
1147 }
1148 }
1149 let mut parts: Vec<String> = Vec::new();
1150 if !firm.is_empty() {
1151 parts.push(ask_live(so_far, hook_event, session, input, &mut firm));
1152 }
1153 let mut markers: Vec<String> = Vec::new();
1154 if let Some((text, n)) = shown {
1155 for (check, ids) in by_check(&wanted[..n]) {
1156 markers.push(format!("#borg-queued {}{}", ids.join(","), tag(check)));
1157 let delivered: Vec<&conscience::Challenge> = ids.iter().filter_map(|i| free.iter().find(|c| c.id == *i).copied()).collect();
1158 let p = if check.is_empty() { vec![1.0; ids.len()] } else { tagged_p(&state, "#borg-pf ", check, &ids) };
1161 record_delivery(session, input, &delivered, "queued", check, p, Vec::new());
1162 }
1163 record_routes(session, input, &wanted[..n], "queued", outcome::ROUTE_FREE, "");
1164 log_cost(session, &format!("free event={hook_event} lessons={n} chars={} graded dropped={}", text.len(), wanted.len() - n));
1165 crate::stats::count(&learn::home(), crate::stats::QUEUED_FREE, session, |e| {
1166 e.n = n as u64;
1167 e.lessons = wanted[..n].iter().map(|(c, _)| c.id.clone()).collect();
1168 e.channel = "queued".into();
1169 });
1170 parts.push(text);
1171 }
1172 for (check, ids) in by_check(&placebo) {
1174 markers.push(format!("#borg-placebo {}{}", ids.join(","), tag(check)));
1175 }
1176 record_routes(session, input, &placebo, outcome::PLACEBO, outcome::ROUTE_PLACEBO, "");
1177 if !markers.is_empty() {
1178 let markers = markers.join("\n");
1179 append(session, &markers);
1180 note_work(session, so_far, &markers);
1181 }
1182 let mut groups: Vec<(Drop, Vec<String>)> = Vec::new();
1183 for (key, id) in dropped {
1184 match groups.iter_mut().find(|(k, _)| *k == key) {
1185 Some((_, ids)) => ids.push(id.to_string()),
1186 None => groups.push((key, vec![id.to_string()])),
1187 }
1188 }
1189 for ((check, channel, route, why), ids) in groups {
1190 record_route(session, input, check, ids, channel, route, why);
1191 }
1192 (!parts.is_empty()).then(|| parts.join("\n\n"))
1193}
1194
1195fn ask_live(so_far: &SoFar, hook_event: &str, session: &str, input: &Value, firm: &mut [(&conscience::Challenge, &str)]) -> String {
1202 crate::memory::shuffle(firm, session);
1203 let groups = by_check(firm);
1204 let now = learn::now_ms();
1205 let lines: Vec<String> = groups
1207 .iter()
1208 .map(|(check, ids)| {
1209 let ids = ids.join(",");
1210 format!("#borg-asked {ids}{}\n#borg-live {ids} ms={now}", tag(check))
1211 })
1212 .collect();
1213 let lines = lines.join("\n");
1214 append(session, &lines);
1215 note_work(session, so_far, &lines);
1216 let cwd = input.get("cwd").and_then(Value::as_str).unwrap_or_default();
1217 let lessons: Vec<&conscience::Challenge> = firm.iter().map(|(c, _)| *c).collect();
1218 if learning() {
1219 let state = std::fs::read_to_string(state_file(session)).unwrap_or_default();
1220 for (check, ids) in &groups {
1221 let members: Vec<&conscience::Challenge> = lessons.iter().copied().filter(|c| ids.contains(&c.id.as_str())).collect();
1222 let ids: Vec<String> = members.iter().map(|c| c.id.clone()).collect();
1223 let (grades, ranks, applied) = graded_of(session, &ids);
1224 let p = if check.is_empty() {
1225 propensity_in(&state, &ids)
1226 } else {
1227 tagged_p(&state, "#borg-p ", check, &members.iter().map(|c| c.id.as_str()).collect::<Vec<_>>())
1228 };
1229 let (pool, base, scoped) = pool_in(&state, &ids);
1230 let asked = outcome::Outcome {
1231 kind: outcome::ASKED.into(),
1232 session: session.into(),
1233 lessons: ids,
1234 ms: now,
1235 repo: repo_of(cwd),
1236 groups: conscience::disagreement_ids(&members),
1237 channel: "live".into(),
1238 grades,
1239 ranks,
1240 applied,
1241 p,
1242 pool,
1243 base,
1244 scoped,
1245 check: check.to_string(),
1246 ..Default::default()
1247 };
1248 let _ = outcome::append(&learn::home().join("outcomes.jsonl"), &asked);
1249 }
1250 }
1251 record_routes(session, input, firm, "live", outcome::ROUTE_ASKED, "");
1252 let text = conscience::render_live(&lessons);
1253 log_cost(session, &format!("free event={hook_event} lessons={} chars={} live", lessons.len(), text.len()));
1254 stat(session, input, crate::stats::LIVE_ASK, |e| {
1255 e.n = lessons.len() as u64;
1256 e.lessons = lessons.iter().map(|c| c.id.clone()).collect();
1257 e.channel = "live".into();
1258 });
1259 text
1260}
1261
1262fn work_so_far(h: &dyn Harness, input: &Value) -> String {
1265 let session = input.get("session_id").and_then(Value::as_str).unwrap_or("unknown");
1266 harness::work_so_far(h.caps(), input, &turn_file(session), LIVE_WORK_CHARS)
1267}
1268
1269struct SoFar<'a> {
1273 h: &'a dyn Harness,
1274 input: &'a Value,
1275 text: std::cell::OnceCell<String>,
1276}
1277
1278impl<'a> SoFar<'a> {
1279 fn new(h: &'a dyn Harness, input: &'a Value) -> Self {
1280 SoFar { h, input, text: std::cell::OnceCell::new() }
1281 }
1282
1283 fn get(&self) -> &str {
1284 self.text.get_or_init(|| work_so_far(self.h, self.input))
1285 }
1286}
1287
1288fn turn_file(session: &str) -> PathBuf {
1291 state_file(session).with_extension("turn")
1292}
1293
1294const LIVE_WORK_CHARS: usize = EVIDENCE_CHARS;
1297
1298fn queen_ask(h: &dyn Harness, session: &str, cwd: &str) -> Option<String> {
1304 if !learning() || !crate::queen::ask_enabled() || std::env::var_os("BORG_ONLY").is_some() || std::env::var_os("BORG_CRITIC").is_some() {
1305 return None;
1306 }
1307 let repos = || {
1308 let mut repos = crate::systems::work_repos(&std::fs::read_to_string(where_file(session)).unwrap_or_default());
1309 let here = repo_of(cwd);
1310 if !here.is_empty() && !repos.contains(&here) {
1311 repos.insert(0, here);
1312 }
1313 repos
1314 };
1315 let scope = if cwd.is_empty() { String::new() } else { format!(" --dir {}", crate::queen::sh_quote(cwd)) };
1316 let mut q = crate::queen::deliver(&learn::home(), session, repos, &scope, learn::now_ms())?;
1317 if let Ok(exe) = std::env::current_exe() {
1318 q = q.run_by(&crate::queen::sh_quote(&exe.display().to_string()));
1319 }
1320 let text = crate::queen::render_delivery(&q, h.caps().question_dialog);
1321 log_cost(session, &format!("free event=UserPromptSubmit queen={} chars={}", q.id, text.len()));
1322 Some(text)
1323}
1324
1325fn free_context(h: &dyn Harness, hook_event: &str, session: &str, input: &Value, text: &str) -> Option<Value> {
1327 free_context_with(h, hook_event, session, input, text, None)
1328}
1329
1330fn free_context_with(h: &dyn Harness, hook_event: &str, session: &str, input: &Value, text: &str, extra: Option<String>) -> Option<Value> {
1332 let so_far = SoFar::new(h, input);
1333 let parts: Vec<String> =
1334 [queued(&so_far, hook_event, session, input), early(h, &so_far, hook_event, session, input, text), extra].into_iter().flatten().collect();
1335 (!parts.is_empty()).then(|| json!({"hookSpecificOutput": {"hookEventName": hook_event, "additionalContext": parts.join("\n\n")}}))
1336}
1337
1338enum Verdict {
1340 Skip(String),
1342 Failed,
1344 Ask(Vec<String>, bool),
1350}
1351
1352struct Work<'a> {
1354 all: &'a [conscience::Challenge],
1356 judged: &'a [conscience::Challenge],
1359 challenges: &'a [conscience::Challenge],
1362 done: &'a std::collections::HashSet<&'a str>,
1363 state: &'a str,
1365 context: &'a str,
1368 scope_text: &'a str,
1369 message: &'a str,
1371 changed: bool,
1373 judge: bool,
1376 budget: Option<std::time::Duration>,
1379 started: std::time::Instant,
1380 check: &'a str,
1383 summary: &'a crate::select::summary::Summary,
1387}
1388
1389struct Call<'a> {
1391 eligible: usize,
1394 order: &'a [&'a conscience::Challenge],
1395 tail: &'a [(usize, &'a conscience::Challenge)],
1399 pt: f64,
1400 model: &'a str,
1401 prompt_hash: String,
1402 dur_ms: u64,
1403 usd: f64,
1405}
1406
1407fn check(session: &str, input: &Value, w: &Work, live: bool) -> Verdict {
1417 let skip = if live {
1422 None
1423 } else if prefilter::edits_gate() {
1424 (!w.changed).then(|| "noedit".to_string())
1425 } else {
1426 prefilter::skip(w.challenges, w.context).map(|score| format!("{score:.2}"))
1427 };
1428 if let Some(score) = skip {
1429 return Verdict::Skip(score);
1430 }
1431 let text = conscience::work_text(w.context);
1433 let text = text.as_ref();
1434 let started = std::time::Instant::now();
1438 let shortlist_now = || {
1439 let (list, added) = crate::vectors::shortlist(&lessons_path(), w.challenges, text, w.scope_text, crate::vectors::SHORTLIST);
1440 if crate::vectors::enabled() {
1441 log_cost(session, &format!("vectors added={added} ms={}", started.elapsed().as_millis()));
1442 }
1443 list
1444 };
1445 let whole = crate::whole::on();
1449 let (shortlist, eligible, order, tail, pt) = if whole {
1450 let ranked = conscience::rank_scoped(w.challenges, text, w.scope_text);
1451 let eligible = crate::whole::eligible(w.challenges, &ranked, w.scope_text);
1452 let n = eligible.len();
1453 let tokens = match std::env::var_os("BORG_STOP_POOL_TOKENS") {
1457 Some(_) => crate::whole::tokens(),
1458 None => {
1459 let limit = live::call_limit(w.budget, w.started.elapsed());
1460 crate::select::pool_tokens(w.summary, Some(u64::try_from(limit.as_millis()).unwrap_or(u64::MAX)), session)
1461 }
1462 };
1463 let f = crate::whole::select_filled(eligible, shortlist_now, &ranked, tokens);
1464 let (drawn, pt) = if f.order.is_empty() { (Vec::new(), 0.0) } else { crate::whole::tail(&f.dropped, tail_seed(session, w.check, live, w.summary)) };
1469 let tail: Vec<(usize, &conscience::Challenge)> = drawn.into_iter().map(|(i, c)| (f.order.len() + i, c)).collect();
1470 let sampled = if tail.is_empty() { String::new() } else { format!(" tail={}", tail.len()) };
1471 log_cost(session, &format!("pool mode=all eligible={n} shown={} budget={}{sampled}", f.shown.len(), if f.fell { "full" } else { "fits" }));
1472 let mut shown = f.shown;
1473 shown.extend(tail.iter().map(|(_, c)| *c));
1474 (shown, n, f.order, tail, pt)
1475 } else {
1476 let list = shortlist_now();
1477 (list.clone(), list.len(), list, Vec::new(), 0.0)
1478 };
1479 let model = std::env::var("BORG_PREDICT_MODEL").unwrap_or_default();
1480 let judging = if w.judge {
1482 pending(session, w.state, w.judged, w.message, live, w.check)
1483 } else {
1484 Judging { pending: Vec::new(), question: false, crowded: Vec::new() }
1485 };
1486 let pend = &judging.pending;
1487 if shortlist.is_empty() && !judging.question {
1491 return Verdict::Skip("empty".into());
1492 }
1493 let extra = predict::judge_section(pend).len();
1494 let graded = crate::whole::graded();
1495 let compact = whole && !crate::whole::classic();
1496 let timeout = live::call_limit(w.budget, w.started.elapsed());
1497 let shown_work = without_declarations(text, pend);
1500 let called = std::time::Instant::now();
1501 let pred = if compact {
1502 predict::predict_whole(&shown_work, &shortlist, pend, &model, graded, timeout)
1503 } else {
1504 predict::predict(&shown_work, &shortlist, pend, &model, graded, timeout)
1505 };
1506 let dur_ms = called.elapsed().as_millis() as u64;
1507 stat(session, input, if live { crate::stats::LIVE_CHECK } else { crate::stats::CHECK }, |e| {
1508 e.n = shortlist.len() as u64;
1509 e.dur_ms = dur_ms;
1510 e.usd = pred.as_ref().map_or(0.0, |p| p.cost);
1511 if pred.is_none() {
1512 e.why = "failed".into();
1513 }
1514 });
1515 let usd = pred.as_ref().map_or(0.0, |p| p.cost);
1516 let call = Call { eligible, order: &order, tail: &tail, pt, model: &model, prompt_hash: predict::template_hash(compact, graded), dur_ms, usd };
1517 note_unjudged(session, &judging.crowded, "slots");
1518 let Some(pred) = pred else {
1519 if graded {
1521 record_graded(session, input, w, live, &[], None, &call);
1522 }
1523 note_unjudged(session, &pend.iter().map(|p| p.lesson.id.clone()).collect::<Vec<_>>(), "failed");
1524 return Verdict::Failed;
1525 };
1526 append(session, &format!("#borg-predict-cost {:.4}", pred.cost));
1528 if live {
1529 log_cost(session, &format!("live usd={:.4} lessons={}", pred.cost, shortlist.len()));
1530 }
1531 if !pend.is_empty() {
1532 let call = w.state.lines().filter(|l| l.starts_with("#borg-predict-cost")).count() + 1;
1533 record_verdicts(session, input, pend, &pred.resolved, extra, call);
1534 }
1535 let applied: Vec<(&conscience::Challenge, u8)> =
1536 pred.applies.iter().zip(&pred.grades).filter_map(|(i, g)| shortlist.iter().find(|c| &c.id == i).map(|c| (*c, *g))).collect();
1537 let ids = |cs: &[&conscience::Challenge]| cs.iter().map(|c| c.id.clone()).collect::<Vec<_>>();
1538 if graded {
1539 let lessons = lessons_path();
1543 let at = Decide {
1546 session,
1547 check: w.check,
1548 channel: if live { "live" } else { "stop" },
1549 lessons: &lessons,
1550 tokens: crate::select::shown_tokens(call.order),
1551 recorded: records_reach_gate(&lessons),
1552 };
1553 let r = decide(crate::select::policy(), &applied, &at, w.summary, DECIDE_WAIT, |r, basis| {
1554 record_graded(session, input, w, live, &applied, Some((r, basis)), &call)
1555 });
1556 let routed = |cs: &[&conscience::Challenge], p: &[f64]| -> Vec<(&str, f64)> {
1557 applied.iter().zip(p).filter(|((c, _), _)| cs.iter().any(|x| x.id == c.id)).map(|((c, _), p)| (c.id.as_str(), *p)).collect()
1558 };
1559 let mut lines = vec![graded_line(&applied), r.log.line(applied.len(), w.check)];
1560 lines.extend(r.log.attention.clone());
1561 lines.extend(p_line("#borg-p", routed(&r.ask, &r.p), Some(w.check)));
1562 lines.extend(p_line("#borg-pf", routed(&r.free, &r.pf), Some(w.check)));
1563 append(session, &lines.join("\n"));
1564 let queue = !r.free.is_empty();
1565 log_cost(session, &format!("graded applied={} ask={} free={} {}", applied.len(), r.ask.len(), r.free.len(), if queue { "queued" } else { "dropped" }));
1566 if queue {
1567 let asks = if r.log.policy == crate::select::Policy::Learned.name() { conscience::graded_without(&applied, None, &[]).0 } else { Vec::new() };
1572 let (owed, rest): (Vec<&conscience::Challenge>, Vec<&conscience::Challenge>) = r.free.iter().partition(|c| asks.iter().any(|a| a.id == c.id));
1573 if !owed.is_empty() {
1574 let prefix = if live && r.log.source == crate::select::policy::EXPERIMENT { INSTEAD } else { INSTEAD_NEXT };
1575 enqueue(session, &format!("{prefix}{}{}", ids(&owed).join(","), tag(w.check)));
1576 }
1577 if !rest.is_empty() {
1578 enqueue(session, &format!("{}{}", ids(&rest).join(","), tag(w.check)));
1579 }
1580 }
1581 if !r.placebo.is_empty() {
1582 enqueue(session, &format!("placebo {}{}", ids(&r.placebo).join(","), tag(w.check)));
1583 }
1584 Verdict::Ask(ids(&r.ask), applied.iter().any(|(_, g)| *g == 3))
1585 } else {
1586 let predicted: Vec<&conscience::Challenge> = applied.iter().map(|(c, _)| *c).collect();
1589 let pool = conscience::widen_pool(&conscience::rank_scoped(w.all, text, w.scope_text), &predicted, w.done);
1590 let widened: Vec<&conscience::Challenge> =
1591 conscience::in_scope_first(conscience::explored(pool.iter().copied())).into_iter().filter(|c| w.challenges.iter().any(|x| x.id == c.id)).collect();
1592 append_p_of(session, &pool, &widened, w.check);
1593 Verdict::Ask(ids(&widened), true)
1595 }
1596}
1597
1598struct Decide<'x> {
1600 session: &'x str,
1601 check: &'x str,
1602 channel: &'static str,
1603 lessons: &'x std::path::Path,
1604 tokens: u32,
1606 recorded: bool,
1609}
1610
1611struct Basis<'s> {
1616 summary: &'s crate::select::summary::Summary,
1617 had: &'s [String],
1618 why: &'static str,
1619}
1620
1621const DECIDE_WAIT: std::time::Duration = std::time::Duration::from_millis(live::AFTER_CALL.as_millis() as u64 / 3);
1628
1629const DECIDE_POLL: std::time::Duration = std::time::Duration::from_millis(5);
1631
1632fn decide_lock(lessons: &std::path::Path) -> PathBuf {
1634 crate::select::summary::cache_path(lessons).with_extension("json.lock")
1635}
1636
1637fn lock_within(file: &std::path::Path, wait: std::time::Duration) -> Result<std::fs::File, &'static str> {
1641 let lock = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(file).map_err(|_| outcome::DECIDED_NO_LOCK)?;
1642 let until = std::time::Instant::now() + wait;
1643 loop {
1644 match lock.try_lock() {
1645 Ok(()) => return Ok(lock),
1646 Err(std::fs::TryLockError::WouldBlock) if std::time::Instant::now() < until => std::thread::sleep(DECIDE_POLL),
1647 Err(std::fs::TryLockError::WouldBlock) => return Err(outcome::DECIDED_BUSY),
1648 Err(std::fs::TryLockError::Error(_)) => return Err(outcome::DECIDED_NO_LOCK),
1649 }
1650 }
1651}
1652
1653fn decide<'a>(
1670 policy: crate::select::Policy,
1671 applied: &[(&'a conscience::Challenge, u8)],
1672 at: &Decide,
1673 stale: &crate::select::summary::Summary,
1674 wait: std::time::Duration,
1675 mut record: impl FnMut(&crate::select::Routed<'a>, &Basis) -> bool,
1676) -> crate::select::Routed<'a> {
1677 use crate::select::Policy;
1678 let state = std::fs::read_to_string(state_file(at.session)).unwrap_or_default();
1679 let queue = std::fs::read_to_string(queued_file(at.session)).unwrap_or_default();
1680 let mut had: Vec<String> = had_in(&state).into_iter().chain(waiting_in(&queue)).map(str::to_string).collect();
1681 had.sort_unstable();
1682 had.dedup();
1683 let alpha = crate::select::alpha(at.lessons);
1685 let mut on = |summary: &crate::select::summary::Summary, policy: Policy, why: &'static str| {
1687 let ctx =
1688 crate::select::Ctx { session: at.session, check: at.check, channel: at.channel, lessons: at.lessons, summary, tokens: at.tokens, had: &had, alpha };
1689 let r = crate::select::graded_under(policy, applied, &ctx);
1690 let landed = record(&r, &Basis { summary, had: &had, why });
1691 (r, landed)
1692 };
1693 if policy != Policy::Learned {
1694 return on(stale, policy, "").0;
1695 }
1696 if !at.recorded {
1697 return on(stale, Policy::Fixed, outcome::DECIDED_NO_RECORD).0;
1698 }
1699 match lock_within(&decide_lock(at.lessons), wait) {
1700 Ok(_held) => {
1701 let summary = crate::select::summary::refresh(at.lessons);
1702 match on(&summary, policy, "") {
1703 (r, true) => r,
1704 (_, false) => on(&summary, Policy::Fixed, outcome::DECIDED_NO_RECORD).0,
1706 }
1707 }
1708 Err(why) => on(stale, Policy::Fixed, why).0,
1709 }
1710}
1711
1712fn records_reach_gate(lessons: &std::path::Path) -> bool {
1717 learning() && outcome::path_beside(lessons) == graded_log()
1718}
1719
1720fn graded_log() -> PathBuf {
1722 learn::home().join("outcomes.jsonl")
1723}
1724
1725fn tail_seed(session: &str, check: &str, live: bool, summary: &crate::select::summary::Summary) -> u64 {
1728 let channel = if live { "live" } else { "stop" };
1729 let ctx =
1730 crate::select::Ctx { session, check, channel, lessons: std::path::Path::new(""), summary, tokens: 0, had: &[], alpha: crate::select::policy::ALPHA };
1731 crate::select::seed(&ctx) ^ u64::from_be_bytes(*b"tailpool")
1732}
1733
1734fn record_graded(
1737 session: &str,
1738 input: &Value,
1739 w: &Work,
1740 live: bool,
1741 applied: &[(&conscience::Challenge, u8)],
1742 decided: Option<(&crate::select::Routed, &Basis)>,
1743 call: &Call,
1744) -> bool {
1745 if !learning() {
1746 return false;
1747 }
1748 let repo = repo_of(input.get("cwd").and_then(Value::as_str).unwrap_or_default());
1749 let o = graded_outcome(session, &repo, w.check, live, applied, decided, w.summary, call);
1750 outcome::append(&graded_log(), &o).is_ok()
1751}
1752
1753#[allow(clippy::too_many_arguments)] fn graded_outcome(
1765 session: &str,
1766 repo: &str,
1767 check: &str,
1768 live: bool,
1769 applied: &[(&conscience::Challenge, u8)],
1770 decided: Option<(&crate::select::Routed, &Basis)>,
1771 read: &crate::select::summary::Summary,
1772 call: &Call,
1773) -> outcome::Outcome {
1774 let ids = |cs: &[&conscience::Challenge]| cs.iter().map(|c| c.id.clone()).collect::<Vec<_>>();
1775 let rounded = |p: &[f64]| p.iter().map(|x| outcome::round_p(*x)).collect::<Vec<_>>();
1776 let (routed, basis) = (decided.map(|d| d.0), decided.map(|d| d.1));
1777 let shown: u32 = call.order.len().try_into().unwrap_or(u32::MAX);
1778 let place = |id: &str| call.order.iter().position(|x| x.id == id).or_else(|| call.tail.iter().find(|(_, x)| x.id == id).map(|(at, _)| *at));
1779 outcome::Outcome {
1780 kind: outcome::GRADED.into(),
1781 session: session.into(),
1782 lessons: applied.iter().map(|(c, _)| c.id.clone()).collect(),
1783 ms: learn::now_ms(),
1784 repo: repo.into(),
1785 channel: if live { "live" } else { "stop" }.into(),
1786 grades: applied.iter().map(|(_, g)| *g).collect(),
1787 ranks: (0..applied.len()).map(|r| u16::try_from(r).unwrap_or(u16::MAX)).collect(),
1788 applied: u16::try_from(applied.len()).unwrap_or(u16::MAX),
1789 chosen: routed.map(|r| ids(&r.ask)).unwrap_or_default(),
1790 explore: routed.is_some_and(|r| r.log.source == "explore"),
1791 p: routed.map(|r| rounded(&r.p)).unwrap_or_default(),
1792 check: check.into(),
1793 policy: routed.map_or_else(|| crate::select::policy().name(), |r| r.log.policy).into(),
1794 fit: routed.map_or_else(|| read.fit.key.clone(), |r| r.log.fit.clone()),
1795 seen: basis.map(|b| b.summary.key()).unwrap_or_default(),
1797 source: routed.map(|r| r.log.source).unwrap_or_default().into(),
1798 free: routed.map(|r| ids(&r.free)).unwrap_or_default(),
1799 pf: routed.map(|r| rounded(&r.pf)).unwrap_or_default(),
1800 placebo: routed.map(|r| ids(&r.placebo)).unwrap_or_default(),
1801 psi: routed.map_or(0.0, |r| r.log.psi),
1802 nofree: basis.map(|b| crate::select::nofree(applied, b.had)).unwrap_or_default(),
1803 xk: routed.and_then(|r| r.log.xk),
1805 xs: routed.and_then(|r| r.log.xs),
1806 alpha: routed.and_then(|r| r.log.alpha),
1808 tail: call.tail.iter().map(|(_, c)| c.id.clone()).collect(),
1809 pt: call.pt,
1810 reason: basis.map(|b| b.why).unwrap_or_default().into(),
1811 eligible: call.eligible.try_into().unwrap_or(u32::MAX),
1812 shown,
1813 tokens: crate::select::shown_tokens(call.order),
1814 fill: applied
1816 .iter()
1817 .map(|(c, _)| place(&c.id))
1818 .chain(call.tail.iter().map(|(at, _)| Some(*at)))
1819 .map(|i| i.map_or(u16::MAX, |i| u16::try_from(i).unwrap_or(u16::MAX)))
1820 .collect(),
1821 model: call.model.into(),
1822 prompt_hash: call.prompt_hash.clone(),
1823 harness: std::env::var("BORG_HARNESS").unwrap_or_default(),
1824 version: env!("CARGO_PKG_VERSION").into(),
1825 dur_ms: call.dur_ms,
1826 failed: routed.is_none(),
1827 usd: call.usd,
1828 ..Default::default()
1829 }
1830}
1831
1832fn live_trigger(session: &str, input: &Value, tool: &str, changed: bool) {
1836 let ctx = state_file(session);
1837 if let Some(why) = live::unsupported() {
1838 if std::fs::OpenOptions::new().write(true).create_new(true).open(ctx.with_extension("live.off")).is_ok() {
1840 eprintln!("borg: live mode needs the consequence model, which {why} replaces; this session stays in hook mode");
1841 }
1842 return;
1843 }
1844 if changed {
1845 live::bump(&ctx, tool);
1846 }
1847 let now = learn::now_ms();
1848 let home = learn::home();
1850 if crate::steer::active(&home) && crate::steer::paused(&home, session, crate::presence::read(&home, session).map(|p| p.started), now) {
1851 return;
1852 }
1853 let lock = live::lock_state(&ctx, now, live::stale_ms(), live::alive);
1854 if live::decide(live::Mode::Live, lock, live::count(&ctx), live::read_mark(&ctx), now, live::debounce_ms()).is_err() {
1855 return;
1856 }
1857 let s = |k: &str| input.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
1858 if let Ok(exe) = std::env::current_exe() {
1860 let _ = std::process::Command::new(exe)
1861 .args(["check", "--session", session, "--transcript", &s("transcript_path"), "--cwd", &s("cwd")])
1862 .stdin(std::process::Stdio::null())
1863 .stdout(std::process::Stdio::null())
1864 .stderr(std::process::Stdio::null())
1865 .spawn();
1866 }
1867}
1868
1869pub fn live_check(h: &dyn Harness, session: &str, input: &Value) {
1877 let ctx = state_file(session);
1878 let started = learn::now_ms();
1879 let Some(_lock) = live::acquire(&ctx, started) else { return };
1880 let n = live::count(&ctx);
1881 let mark = live::read_mark(&ctx);
1882 if live::unsupported().is_some() || live::decide(live::current(), live::Lock::Free, n, mark, started, live::debounce_ms()).is_err() {
1883 return;
1884 }
1885 let turn = turn_id(session);
1886 let (all, withheld) = loaded(session);
1887 let judged = judged(&all, withheld);
1888 let state = std::fs::read_to_string(&ctx).unwrap_or_default();
1889 let message = work_so_far(h, input);
1890 let acted = early_acted(session, &judged, &message);
1893 let mut done = done_in(&state, &acted);
1894 let waiting = std::fs::read_to_string(queued_file(session)).unwrap_or_default();
1895 done.extend(waiting_in(&waiting));
1896 let challenges: Vec<conscience::Challenge> = all.iter().filter(|c| !done.contains(c.id.as_str()) && !c.off_system).cloned().collect();
1897 let context = format!("{state}{message}");
1898 let scope_text = format!("{}\n{message}", where_now(session));
1899 let check_id = crate::select::check_id(session, "live", started, std::process::id());
1900 let summary = crate::select::summary::refresh(&lessons_path());
1902 let work = Work {
1903 all: &all,
1904 judged: &judged,
1905 challenges: &challenges,
1906 done: &done,
1907 state: &state,
1908 context: &context,
1909 scope_text: &scope_text,
1910 message: &message,
1911 changed: true,
1912 judge: true,
1913 budget: None,
1914 started: std::time::Instant::now(),
1915 check: &check_id,
1916 summary: &summary,
1917 };
1918 let before = mark.map_or(0, |m| m.covered);
1919 let covered = match check(session, input, &work, true) {
1920 Verdict::Skip(score) => {
1922 append(session, &format!("#borg-live-skip {score}"));
1923 before
1924 }
1925 Verdict::Failed => before,
1926 Verdict::Ask(ids, blocks) => {
1927 if !ids.is_empty() {
1928 let prefix = if blocks { "live " } else { LIVE_NEXT };
1929 enqueue(session, &format!("{prefix}{}{}", ids.join(","), tag(&check_id)));
1930 }
1931 n
1932 }
1933 };
1934 live::write_mark(&ctx, live::Mark { covered, started_ms: started, turn: Some(turn) });
1935}
1936
1937pub fn dispatch(h: &dyn Harness, event: &str, input: &Value) -> Option<Value> {
1940 let session = input.get("session_id").and_then(Value::as_str).unwrap_or("unknown");
1941 match event {
1942 "prompt" => on_prompt(h, session, input),
1943 "post_tool_failure" => {
1944 capture_test(session, input, true);
1945 if h.caps().deny_capture {
1946 capture_rejection(h, session, input);
1947 }
1948 None
1949 }
1950 "end" => {
1951 on_end(h, session, input);
1952 None
1953 }
1954 "post_tool" => {
1955 capture_test(session, input, false);
1956 on_post_tool(h, session, input)
1957 }
1958 "stop" => on_stop(h, session, input),
1959 _ => None,
1960 }
1961}
1962
1963fn on_prompt(h: &dyn Harness, session: &str, input: &Value) -> Option<Value> {
1964 let prompt = input.get("prompt").and_then(Value::as_str).unwrap_or_default();
1965 append(session, prompt);
1966 if learning() {
1967 crate::notes::remember_start(&crate::notes::state_dir(), session, input.get("cwd").and_then(Value::as_str).unwrap_or_default());
1969 crate::notes::mark(&crate::notes::state_dir(), session, "prompt");
1970 }
1971 if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(prompts_file(session)) {
1973 let _ = writeln!(f, "{prompt}");
1974 }
1975 let vetoed = (learning() && crate::veto::enabled()).then(|| crate::veto::reason_in(prompt)).flatten();
1977 match &vetoed {
1978 Some(reason) => veto(h, session, input, reason),
1979 None => capture_prompt(h, session, input, prompt),
1980 }
1981 note_where(session, &repo_of(input.get("cwd").and_then(Value::as_str).unwrap_or_default()));
1982 let _ = std::fs::write(state_file(session).with_extension("lastprompt"), prompt);
1983 let checked = crate::update::maybe_check(learn::now_ms());
1986 let out = (h.caps().prompt_context && input.get("context") != Some(&Value::Bool(false))).then(|| {
1989 let cwd = input.get("cwd").and_then(Value::as_str).unwrap_or_default();
1990 let ask = queen_ask(h, session, cwd);
1991 let update = crate::update::notice(checked.as_ref(), &learn::home(), &state_file(session).with_extension("update"));
1994 let extra: Vec<String> = [ask, vetoed.as_deref().map(crate::veto::render), update].into_iter().flatten().collect();
1995 free_context_with(h, "UserPromptSubmit", session, input, prompt, (!extra.is_empty()).then(|| extra.join("\n\n")))
1996 });
1997 if harness::transcript(h.caps(), input).is_none() {
1999 let _ = std::fs::write(turn_file(session), "");
2000 }
2001 out.flatten()
2002}
2003
2004fn capture_test(session: &str, input: &Value, failed: bool) {
2009 if !learning() || input.get("tool_name").and_then(Value::as_str) != Some("Bash") {
2010 return;
2011 }
2012 let command = input.pointer("/tool_input/command").and_then(Value::as_str).unwrap_or_default();
2013 if !crate::notes::regress_signals::runs_tests(command) {
2014 return;
2015 }
2016 let output = crate::notes::regress_signals::tool_output(input);
2017 if !failed && output.trim().is_empty() {
2018 return;
2019 }
2020 if let Some(what) = crate::notes::regress_signals::test_outcome(command, &output, failed)
2021 && let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(state_file(session).with_extension("tests"))
2022 {
2023 let _ = writeln!(f, "{what} {}", learn::now_ms());
2024 }
2025}
2026
2027fn on_end(h: &dyn Harness, session: &str, input: &Value) {
2028 let _ = std::fs::remove_file(denied_file(session));
2029 if !learning() {
2030 return;
2031 }
2032 crate::notes::remember_proposal(&crate::notes::state_dir(), session, &full_proposal(h, input));
2034 crate::notes::mark(&crate::notes::state_dir(), session, "stop");
2035 note_never_delivered(session, input);
2039 let end = outcome::Outcome {
2040 kind: outcome::ENDED.into(),
2041 session: session.into(),
2042 ms: learn::now_ms(),
2043 repo: repo_of(input.get("cwd").and_then(Value::as_str).unwrap_or_default()),
2044 ..Default::default()
2045 };
2046 let _ = outcome::append(&learn::home().join("outcomes.jsonl"), &end);
2047 if !crate::notes::on_end(session, input)
2050 && let Ok(exe) = std::env::current_exe()
2051 {
2052 let _ = std::process::Command::new(exe)
2053 .args(["learn", "--session", session])
2054 .stdin(std::process::Stdio::null())
2055 .stdout(std::process::Stdio::null())
2056 .stderr(std::process::Stdio::null())
2057 .spawn();
2058 }
2059}
2060
2061fn on_post_tool(h: &dyn Harness, session: &str, input: &Value) -> Option<Value> {
2062 let _ = std::fs::remove_file(denied_file(session));
2064 let tool = input.get("tool_name").and_then(Value::as_str).unwrap_or_default();
2065 let tool_input = input.get("tool_input").unwrap_or(&Value::Null);
2066 let touch = touched(tool_input, tool);
2067 append(session, &touch);
2068 note_where(
2070 session,
2071 &if tool == "Bash" { bash_read_paths(tool_input.get("command").and_then(Value::as_str).unwrap_or_default()).join(" ") } else { touch.clone() },
2072 );
2073 if prefilter::edits_gate() && prefilter::changes(tool, tool_input) {
2075 let _ = std::fs::OpenOptions::new().create(true).append(true).open(changes_file(session)).and_then(|mut f| writeln!(f, "{tool}"));
2076 }
2077 let edit = edit_text(tool, tool_input);
2078 if let Some(edit) = &edit
2079 && let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(edits_file(session))
2080 {
2081 let _ = writeln!(f, "{edit}");
2082 }
2083 if harness::transcript(h.caps(), input).is_none()
2085 && let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(turn_file(session))
2086 {
2087 let _ = writeln!(f, "[{tool}] {touch}");
2088 if let Some(edit) = &edit {
2089 let _ = writeln!(f, "{edit}");
2090 }
2091 }
2092 if live::current() == live::Mode::Live {
2096 live_trigger(session, input, tool, prefilter::changes(tool, tool_input));
2097 }
2098 (h.caps().tool_context && !subagent(input)).then(|| free_context(h, "PostToolUse", session, input, &touch)).flatten()
2102}
2103
2104fn subagent(input: &Value) -> bool {
2107 input.get("agent_id").and_then(Value::as_str).is_some_and(|a| !a.is_empty())
2108}
2109
2110struct StopLive {
2115 on: bool,
2116 budget: Option<std::time::Duration>,
2117 lock: live::Lock,
2118 guard: Option<live::Guard>,
2119 waiting: Vec<(String, String)>,
2123 instead: Vec<(String, String)>,
2126}
2127
2128impl StopLive {
2129 fn take(h: &dyn Harness, session: &str) -> StopLive {
2130 let on = live::current() == live::Mode::Live;
2131 let budget = crate::expert_route::stop_budget(h);
2132 let lock = if on { live::wait_free(&state_file(session), live::stop_wait(budget).as_millis() as u64) } else { live::Lock::Free };
2133 let guard = if on && lock != live::Lock::Held { live::acquire(&state_file(session), learn::now_ms()) } else { None };
2134 let lock = if on && guard.is_none() { live::Lock::Held } else { lock };
2135 let Taken { asks: waiting, instead } = if on { take_live(session) } else { Taken::default() };
2136 StopLive { on, budget, lock, guard, waiting, instead }
2137 }
2138}
2139
2140fn on_stop(h: &dyn Harness, session: &str, input: &Value) -> Option<Value> {
2141 let started = std::time::Instant::now();
2142 let started_ms = learn::now_ms();
2143 if learning() {
2144 crate::notes::remember_proposal(&crate::notes::state_dir(), session, &full_proposal(h, input));
2146 crate::notes::mark(&crate::notes::state_dir(), session, "stop");
2147 crate::sweep::turn_end(h, session, input);
2149 }
2150 let second_round = input.get("stop_hook_active").and_then(Value::as_bool) == Some(true);
2151 if std::env::var("BORG_CRITIC").as_deref() == Ok("generic") {
2152 return (!second_round).then(|| json!({"decision": "block", "reason": conscience::GENERIC}));
2153 }
2154 let (all, withheld) = loaded(session);
2155 let judged = judged(&all, withheld);
2156 note_answer(h, session, input);
2159 let changed = std::fs::remove_file(changes_file(session)).is_ok();
2162 if second_round {
2164 return None;
2165 }
2166 stat(session, input, crate::stats::TURN_END, |_| {});
2167 let live = StopLive::take(h, session);
2168 let state = std::fs::read_to_string(state_file(session)).unwrap_or_default();
2169 let proposal = full_proposal(h, input);
2174 let acted = early_acted(session, &judged, &proposal);
2175 let only = std::env::var_os("BORG_ONLY").is_some();
2176 let done = if only { std::collections::HashSet::new() } else { done_in(&state, &acted) };
2177 let queue = if only { String::new() } else { std::fs::read_to_string(queued_file(session)).unwrap_or_default() };
2183 let waiting: std::collections::HashSet<&str> =
2184 if only { Default::default() } else { live.waiting.iter().chain(&live.instead).map(|(id, _)| id.as_str()).chain(waiting_in(&queue)).collect() };
2185 let challenges: Vec<conscience::Challenge> =
2187 all.iter().filter(|c| !done.contains(c.id.as_str()) && !waiting.contains(c.id.as_str()) && !c.off_system).cloned().collect();
2188 let message = input.get("last_assistant_message").and_then(Value::as_str).unwrap_or_default();
2189 let context = format!("{state}{message}");
2190 let scope_text = format!("{}\n{message}", where_now(session));
2192 let check_id = crate::select::check_id(session, "stop", started_ms, std::process::id());
2193 let summary = crate::select::summary::refresh(&lessons_path());
2195 let work = Work {
2196 all: &all,
2197 judged: &judged,
2198 challenges: &challenges,
2199 done: &done,
2200 state: &state,
2201 context: &context,
2202 scope_text: &scope_text,
2203 message: &proposal,
2204 changed,
2205 judge: !live.on || live.guard.is_some(),
2206 budget: live.budget,
2207 started,
2208 check: &check_id,
2209 summary: &summary,
2210 };
2211 match stop_select(h, session, input, &work, &live) {
2212 Ok(selected) => stop_ask(h, session, input, selected, &check_id, &live.instead),
2213 Err(out) => out,
2214 }
2215}
2216
2217type Asks<'a> = Vec<(&'a conscience::Challenge, String)>;
2220
2221fn stop_select<'a>(h: &dyn Harness, session: &str, input: &Value, w: &Work<'a>, live: &StopLive) -> Result<Asks<'a>, Option<Value>> {
2224 let own = |cs: Vec<&'a conscience::Challenge>| cs.into_iter().map(|c| (c, w.check.to_string())).collect();
2225 match std::env::var("BORG_ONLY") {
2226 Ok(ids) => Ok(own(w.challenges.iter().filter(|c| ids.split(',').any(|i| i == c.id)).collect())),
2228 Err(_) if std::env::var("BORG_MATCH").as_deref() != Ok("bm25") => stop_check(h, session, input, w, live),
2231 Err(_) => {
2234 let pool = conscience::budget_pool(&conscience::rank_scoped(w.all, &conscience::work_text(w.context), w.scope_text), w.done);
2235 let asked: Vec<&conscience::Challenge> = conscience::in_scope_first(conscience::explored(pool.iter().copied()))
2236 .into_iter()
2237 .filter_map(|c| w.challenges.iter().find(|x| x.id == c.id))
2238 .collect();
2239 append_p_of(session, &pool, &asked, w.check);
2240 Ok(own(asked))
2241 }
2242 }
2243}
2244
2245fn stop_check<'a>(h: &dyn Harness, session: &str, input: &Value, w: &Work<'a>, live: &StopLive) -> Result<Asks<'a>, Option<Value>> {
2251 let skip = |why: &str| {
2252 append(session, &format!("#borg-skip {why}"));
2253 stat(session, input, crate::stats::GATE_SKIP, |e| e.why = why.to_string());
2254 let prompts = std::fs::read_to_string(prompts_file(session)).unwrap_or_default();
2255 Err(crate::queen::stop(session, input, &|| harness::plan(h.caps(), input), &prompts, &[]))
2256 };
2257 let mut waiting: Vec<(&conscience::Challenge, String)> = Vec::new();
2258 let instead = live.instead.iter().map(|(id, check)| (id, check, "queued"));
2261 for (id, check, channel) in live.waiting.iter().map(|(id, check)| (id, check, "live")).chain(instead) {
2262 let why = match w.all.iter().find(|c| &c.id == id).filter(|c| !c.off_system) {
2263 Some(_) if waiting.iter().any(|(c, _)| &c.id == id) => "queued twice",
2264 Some(_) if w.done.contains(id.as_str()) => "done at the stop",
2265 Some(c) => {
2266 waiting.push((c, check.clone()));
2267 continue;
2268 }
2269 None => "not deliverable",
2270 };
2271 record_route(session, input, check, vec![id.clone()], channel, outcome::ROUTE_DROPPED_DONE, why);
2272 }
2273 let ctx = state_file(session);
2276 if live.on && live::covered(live.lock, live::count(&ctx), live::read_mark(&ctx), turn_id(session)) {
2277 return if waiting.is_empty() { skip("live_covered") } else { Ok(waiting) };
2278 }
2279 let mut asked: Asks = match check(session, input, w, false) {
2280 Verdict::Skip(_) | Verdict::Failed if !waiting.is_empty() => Vec::new(),
2281 Verdict::Skip(score) => return skip(&score),
2282 Verdict::Failed => return Err(None),
2283 Verdict::Ask(ids, _) => ids.iter().filter_map(|i| w.challenges.iter().find(|c| &c.id == i)).map(|c| (c, w.check.to_string())).collect(),
2284 };
2285 asked.extend(waiting);
2287 Ok(asked)
2288}
2289
2290fn graded_line(applied: &[(&conscience::Challenge, u8)]) -> String {
2293 let items: Vec<String> = applied.iter().enumerate().map(|(r, (c, g))| format!("{}:{g}:{r}", c.id)).collect();
2294 format!("#borg-graded n={} {}", applied.len(), items.join(","))
2295}
2296
2297fn p_line<'a>(prefix: &str, chosen: impl IntoIterator<Item = (&'a str, f64)>, check: Option<&str>) -> Option<String> {
2303 let items: Vec<String> = chosen.into_iter().map(|(id, p)| format!("{id}={}", outcome::round_p(p))).collect();
2304 (!items.is_empty()).then(|| format!("{prefix} {}{}", items.join(","), tag(check.unwrap_or_default())))
2305}
2306
2307fn append_p_of(session: &str, pool: &[(f64, &conscience::Challenge)], asked: &[&conscience::Challenge], check: &str) {
2314 if asked.is_empty() {
2315 return;
2316 }
2317 let p = conscience::propensity(pool, session);
2318 let chosen: Vec<(&str, f64)> = asked.iter().filter_map(|c| p.get(&c.id).map(|p| (c.id.as_str(), *p))).collect();
2319 let items: Vec<String> =
2320 pool.iter().map(|(s, c)| format!("{}={}{}", c.id, conscience::pool_base(*s, c), if c.scope.is_empty() { "" } else { ":s" })).collect();
2321 let pool = format!("#borg-pool {}{}", items.join(","), tag(check));
2322 append(session, &p_line("#borg-p", chosen, Some(check)).map_or(pool.clone(), |p| format!("{p}\n{pool}")));
2323}
2324
2325fn tagged(line: &str) -> (&str, Option<&str>) {
2327 match line.rsplit_once(" @") {
2328 Some((items, check)) if !check.is_empty() && check.bytes().all(|b| b.is_ascii_hexdigit()) => (items, Some(check)),
2329 _ => (line, None),
2330 }
2331}
2332
2333fn pool_in(state: &str, ids: &[String]) -> (Vec<String>, Vec<f64>, Vec<bool>) {
2338 let parse = |line: &str| -> Option<(Vec<String>, Vec<f64>, Vec<bool>)> {
2339 let mut out = (Vec::new(), Vec::new(), Vec::new());
2340 for item in line.split(',') {
2341 let (id, rest) = item.rsplit_once('=')?;
2342 let (base, scoped) = match rest.strip_suffix(":s") {
2343 Some(b) => (b, true),
2344 None => (rest, false),
2345 };
2346 out.0.push(id.trim().to_string());
2347 out.1.push(base.trim().parse::<f64>().ok()?);
2348 out.2.push(scoped);
2349 }
2350 Some(out)
2351 };
2352 let mut check: std::collections::HashMap<&str, Option<&str>> = std::collections::HashMap::new();
2354 for line in state.lines().filter_map(|l| l.strip_prefix("#borg-p ")) {
2355 let (items, tag) = tagged(line);
2356 for (id, _) in items.split(',').filter_map(|it| it.rsplit_once('=')) {
2357 check.insert(id.trim(), tag);
2358 }
2359 }
2360 let Some(Some(tag)) = ids.first().and_then(|i| check.get(i.as_str())).copied() else { return Default::default() };
2361 if !ids.iter().all(|i| check.get(i.as_str()).copied().flatten() == Some(tag)) {
2362 return Default::default();
2363 }
2364 state
2365 .lines()
2366 .rev()
2367 .filter_map(|l| l.strip_prefix("#borg-pool "))
2368 .map(tagged)
2369 .filter(|(_, t)| *t == Some(tag))
2370 .find_map(|(items, _)| parse(items).filter(|(pool, _, _)| ids.iter().all(|i| pool.contains(i))))
2371 .unwrap_or_default()
2372}
2373
2374fn propensity_in(state: &str, ids: &[String]) -> Vec<f64> {
2378 let mut seen: std::collections::HashMap<&str, f64> = std::collections::HashMap::new();
2379 for line in state.lines().filter_map(|l| l.strip_prefix("#borg-p ")) {
2380 for (id, p) in tagged(line).0.split(',').filter_map(|it| it.rsplit_once('=')) {
2381 if let Ok(p) = p.trim().parse::<f64>() {
2382 seen.insert(id.trim(), p);
2383 }
2384 }
2385 }
2386 ids.iter().map(|i| seen.get(i.as_str()).copied()).collect::<Option<Vec<f64>>>().unwrap_or_default()
2387}
2388
2389fn graded_of(session: &str, ids: &[String]) -> (Vec<u8>, Vec<u16>, u16) {
2392 let state = std::fs::read_to_string(state_file(session)).unwrap_or_default();
2393 let mut seen: std::collections::HashMap<String, (u8, u16, u16)> = std::collections::HashMap::new();
2394 for line in state.lines().filter_map(|l| l.strip_prefix("#borg-graded n=")) {
2395 let Some((n, items)) = line.split_once(' ') else { continue };
2396 let n: u16 = n.parse().unwrap_or(0);
2397 for it in items.split(',') {
2398 let mut p = it.rsplitn(3, ':');
2399 let (Some(r), Some(g), Some(id)) = (p.next(), p.next(), p.next()) else { continue };
2400 seen.insert(id.to_string(), (g.parse().unwrap_or(0), r.parse().unwrap_or(0), n));
2401 }
2402 }
2403 let got: Vec<(u8, u16, u16)> = ids.iter().map(|i| seen.get(i).copied().unwrap_or((0, 0, 0))).collect();
2404 (got.iter().map(|g| g.0).collect(), got.iter().map(|g| g.1).collect(), got.iter().map(|g| g.2).max().unwrap_or(0))
2405}
2406
2407fn stop_ask(h: &dyn Harness, session: &str, input: &Value, mut selected: Asks, check: &str, instead: &[(String, String)]) -> Option<Value> {
2414 crate::memory::shuffle(&mut selected, session);
2417 let lessons: Vec<&conscience::Challenge> = selected.iter().map(|(c, _)| *c).collect();
2418 let log = lessons.iter().map(|c| c.id.as_str()).collect::<Vec<_>>().join(",");
2419 let others: Vec<String> = selected.iter().filter(|(_, k)| k != check).map(|(c, k)| format!("{}={k}", c.id)).collect();
2420 let mut marker = if lessons.is_empty() { "#borg-asked ".to_string() } else { format!("#borg-asked {log}{}", tag(check)) };
2422 if !others.is_empty() {
2423 marker.push_str(&format!("\n{ROUTED}{}", others.join(",")));
2424 }
2425 append(session, &marker);
2426 if !lessons.is_empty()
2427 && let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(edits_file(session))
2428 {
2429 let _ = writeln!(f, "{}\n{marker}", one_line(&full_proposal(h, input), EVIDENCE_CHARS));
2431 }
2432 let prompts = std::fs::read_to_string(prompts_file(session)).unwrap_or_default();
2435 let queen = crate::queen::stop(session, input, &|| harness::plan(h.caps(), input), &prompts, &lessons);
2436 if lessons.is_empty() {
2437 return queen;
2438 }
2439 if learning() {
2440 let cwd = input.get("cwd").and_then(Value::as_str).unwrap_or_default();
2444 let state = std::fs::read_to_string(state_file(session)).unwrap_or_default();
2445 let ms = learn::now_ms();
2446 let disagree = conscience::disagreement_ids(&lessons);
2449 let (handed, routed): (Vec<(&conscience::Challenge, &str)>, Vec<_>) =
2450 selected.iter().map(|(c, k)| (*c, k.as_str())).partition(|(c, k)| instead.iter().any(|(id, at)| *id == c.id && at == k));
2451 let groups = by_check(&routed).into_iter().map(|g| (g, false)).chain(by_check(&handed).into_iter().map(|g| (g, true)));
2452 for ((k, members), handed) in groups {
2453 let ids: Vec<String> = members.iter().map(|i| (*i).to_string()).collect();
2454 let (grades, ranks, applied) = graded_of(session, &ids);
2455 let p = match handed {
2456 true => Vec::new(),
2457 false if k.is_empty() => propensity_in(&state, &ids),
2458 false => tagged_p(&state, "#borg-p ", k, &members),
2459 };
2460 let (pool, base, scoped) = if handed { Default::default() } else { pool_in(&state, &ids) };
2461 let asked = outcome::Outcome {
2462 kind: outcome::ASKED.into(),
2463 session: session.into(),
2464 lessons: ids.clone(),
2465 ms,
2466 repo: repo_of(cwd),
2467 groups: disagree.iter().filter(|g| g.iter().any(|x| ids.contains(x))).cloned().collect(),
2468 channel: "stop".into(),
2469 grades,
2470 ranks,
2471 applied,
2472 p,
2473 pool,
2474 base,
2475 scoped,
2476 check: k.into(),
2477 ..Default::default()
2478 };
2479 let _ = outcome::append(&learn::home().join("outcomes.jsonl"), &asked);
2480 let reason = match (handed, k == check) {
2481 (true, _) => ASKED_INSTEAD,
2482 (false, true) => "",
2483 (false, false) => "at the stop",
2484 };
2485 record_route(session, input, k, ids, "stop", outcome::ROUTE_ASKED, reason);
2486 }
2487 }
2488 let out = queen.or_else(|| Some(json!({"decision": "block", "reason": conscience::render(&lessons)})));
2489 let chars = out.as_ref().and_then(|o| o["reason"].as_str()).map_or(0, str::len);
2490 log_cost(session, &format!("block questions={} chars={chars}", lessons.len()));
2491 stat(session, input, crate::stats::BLOCK, |e| {
2492 e.n = lessons.len() as u64;
2493 e.lessons = lessons.iter().map(|c| c.id.clone()).collect();
2494 e.channel = "stop".into();
2495 });
2496 out
2497}
2498
2499pub fn main(name: &str, event: &str) {
2504 let Some(h) = harness::by_name(name) else { return };
2505 let mut raw = String::new();
2506 let _ = std::io::stdin().read_to_string(&mut raw);
2507 let mut input = h.normalise(serde_json::from_str(&raw).unwrap_or(Value::Null));
2508 if !h.caps().sends_pid
2510 && let Some(m) = input.as_object_mut()
2511 {
2512 m.shift_remove("pid");
2513 }
2514 let cwd = input.get("cwd").and_then(Value::as_str).unwrap_or_default();
2517 let cfg = collective::load();
2518 let route = match &cfg {
2519 Ok(cfg) => collective::route(cfg.as_ref(), cwd, &learn::home()),
2520 Err(_) => collective::Route::Off,
2521 };
2522 let collective::Route::Collective { home, name, .. } = route else { return };
2523 let mode = live::of(cfg.as_ref().ok().and_then(Option::as_ref), &name).mode;
2526 unsafe {
2529 std::env::set_var("BORG_HOME", &home);
2530 std::env::set_var("BORG_MODE", mode.name());
2531 std::env::set_var("BORG_HARNESS", h.name());
2533 if std::env::var_os("BORG_STATE").is_none() {
2534 std::env::set_var("BORG_STATE", home.join("state"));
2535 }
2536 }
2537 let now = learn::now_ms();
2539 let session = input.get("session_id").and_then(Value::as_str).unwrap_or("unknown");
2540 crate::listen::touch(&home, event, session, now);
2544 if matches!(event, "start" | "halted") {
2546 return;
2547 }
2548 let me = match event {
2551 "pre_tool" => {
2552 if !crate::steer::active(&home) {
2553 return;
2554 }
2555 crate::presence::read(&home, session)
2556 }
2557 _ => crate::presence::touch(&home, &name, h.name(), event, &input, now),
2558 };
2559 let started = me.map(|p| p.started);
2562 let stopping = crate::listen::stopping(&home, event, session, now);
2564 let out = crate::steer::around(&home, event, &input, started, now, || crate::expert_route::checkpoint(h, event, &input, || dispatch(h, event, &input)));
2565 let out = crate::listen::after_stop(&home, h, stopping.as_ref(), &input, out);
2567 let out = harness::with_budgets(h, &input, out);
2569 if let Some(out) = crate::msg::deliver(&home, h.caps(), event, &input, started, now, out) {
2571 println!("{}", for_harness(h, out));
2572 }
2573}
2574
2575fn for_harness(h: &dyn Harness, mut out: Value) -> Value {
2579 if matches!(h.wiring(), harness::Wiring::CommandHooks { .. })
2580 && let Some(o) = out.as_object_mut()
2581 {
2582 o.shift_remove("shown_ids");
2583 }
2584 out
2585}
2586
2587#[cfg(test)]
2588mod tests {
2589 use super::*;
2590
2591 #[test]
2592 fn every_file_of_an_edit_survives_the_cut_of_its_text() {
2593 let long = "x".repeat(700);
2594 let input = json!({"file_path": "/w/a.rs", "new_string": long, "edits": [{"file_path": "/w/b.rs", "new_string": "more"}]});
2595 let text = edit_text("Edit", &input).unwrap();
2596 assert!(text.starts_with("/w/a.rs /w/b.rs x"), "{}", &text[..40]);
2597 assert_eq!(text.chars().count(), 600);
2598 let multi = json!({"file_path": "/w/a.rs", "edits": [{"old_string": "a", "new_string": "b"}, {"old_string": "c", "new_string": "d"}]});
2599 assert_eq!(edit_text("MultiEdit", &multi).as_deref(), Some("/w/a.rs b d"), "Claude's MultiEdit reads as before");
2600 assert_eq!(touched(&input, "Edit"), "/w/a.rs /w/b.rs");
2601 }
2602
2603 #[test]
2604 fn propensity_in_takes_the_latest_entry_and_nothing_when_one_is_missing() {
2605 let state = "#borg-p A=1,B=0.25\n#borg-asked A,B\n#borg-p B=0.5,C=0.1\n";
2606 let ids = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2607 assert_eq!(propensity_in(state, &ids(&["B", "A"])), [0.5, 1.0]);
2608 assert_eq!(propensity_in(state, &ids(&["C"])), [0.1]);
2609 assert!(propensity_in(state, &ids(&["A", "D"])).is_empty(), "D unknown: no guess");
2610 assert!(propensity_in("", &ids(&["A"])).is_empty());
2611 }
2612
2613 #[test]
2614 fn pool_in_takes_the_pool_of_the_check_that_logged_each_p() {
2615 let state = "#borg-p A=0.6,B=0.4 @c1\n#borg-pool A=1.5:s,B=0.25,C=2 @c1\n#borg-asked A,B\n#borg-p B=0.5 @c2\n#borg-pool B=0.5,D=0.125:s @c2\n";
2616 let ids = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2617 assert_eq!(pool_in(state, &ids(&["B"])), (ids(&["B", "D"]), vec![0.5, 0.125], vec![false, true]), "B's latest p is check 2's");
2618 assert_eq!(pool_in(state, &ids(&["A"])), (ids(&["A", "B", "C"]), vec![1.5, 0.25, 2.0], vec![true, false, false]));
2619 assert_eq!(pool_in(state, &ids(&["A", "B"])), Default::default(), "A's p from check 1, B's from check 2: no pairing");
2620 assert_eq!(pool_in("", &ids(&["A"])), Default::default());
2621 assert_eq!(pool_in(state, &[]), Default::default());
2622 let graded = "#borg-p A=1\n#borg-p B=0.5 @c3\n#borg-pool A=1,B=1 @c3\n";
2624 assert_eq!(pool_in(graded, &ids(&["A"])), Default::default());
2625 assert_eq!(pool_in(graded, &ids(&["B"])).0, ids(&["A", "B"]));
2626 assert_eq!(pool_in("#borg-p A=1\n#borg-pool A=1,B=2\n", &ids(&["A"])), Default::default());
2628 }
2629
2630 #[test]
2631 fn a_queue_line_names_its_route_its_ids_and_its_check() {
2632 let c = "0123456789ab";
2633 assert_eq!(queue_line(&format!("A,B @{c}")), (Queued::Free, vec!["A", "B"], c));
2634 assert_eq!(queue_line(&format!("live A @{c}")), (Queued::Ask, vec!["A"], c));
2635 assert_eq!(queue_line(&format!("placebo X,Y @{c}")), (Queued::Placebo, vec!["X", "Y"], c));
2636 assert_eq!(queue_line(&format!("instead G0,G1 @{c}")), (Queued::Instead, vec!["G0", "G1"], c));
2637 assert_eq!(queue_line(&format!("instead-next G2 @{c}")), (Queued::Instead, vec!["G2"], c));
2638 assert_eq!(queue_line("A,B"), (Queued::Free, vec!["A", "B"], ""));
2640 assert_eq!(queue_line("live A"), (Queued::Ask, vec!["A"], ""));
2641 assert_eq!(queue_line(&format!("live-next A,B @{c}")), (Queued::Ask, vec!["A", "B"], c));
2642 assert_eq!(listed(&format!("#borg-asked A,B @{c}\n#borg-asked C\n"), "#borg-asked "), ["A", "B", "C"].into_iter().collect());
2643 }
2644
2645 #[test]
2646 fn a_tagged_propensity_is_its_checks_never_another_checks() {
2647 let state = "#borg-pf A=1,B=0.5 @c1\n#borg-pf A=0.25 @c2\n#borg-p A=0.75 @c1\n#borg-pf B=0.9\n";
2648 assert_eq!(tagged_p(state, "#borg-pf ", "c1", &["A", "B"]), [1.0, 0.5]);
2649 assert_eq!(tagged_p(state, "#borg-pf ", "c2", &["A"]), [0.25]);
2650 assert!(tagged_p(state, "#borg-pf ", "c2", &["A", "B"]).is_empty(), "B has none at c2: no guess");
2651 assert_eq!(tagged_p(state, "#borg-p ", "c1", &["A"]), [0.75], "#borg-p and #borg-pf are separate lines");
2652 assert_eq!(p_line("#borg-pf", [("A", 1.0), ("B", 0.33333)], Some("c1")).as_deref(), Some("#borg-pf A=1,B=0.3333 @c1"));
2653 assert_eq!(p_line("#borg-p", [], Some("c1")), None);
2654 }
2655
2656 #[test]
2657 fn unjudged_says_why_each_delivered_lesson_has_no_verdict() {
2658 let c = "0123456789ab";
2659 let state = format!(
2660 "#borg-asked A,B,C,D @{c}\n#borg-judged A=pending\n#borg-unjudged B why=slots\n#borg-judged A=pending\n#borg-unjudged D why=failed\n\
2661 #borg-queued E @{c}\n#borg-judged B=pending\n#borg-asked D\n"
2662 );
2663 let why = unjudged(&state);
2664 assert_eq!(why["A"], outcome::UNJUDGED_TRIES, "two unclear tries");
2665 assert_eq!(why["B"], outcome::UNJUDGED_SLOTS, "one try is not all of them; the last call left it out");
2666 assert_eq!(why["C"], outcome::UNJUDGED_NO_CALL);
2667 assert_eq!(why["D"], outcome::UNJUDGED_NO_CALL, "delivered again after its failed call");
2668 assert_eq!(why["E"], outcome::UNJUDGED_NO_CALL);
2669 }
2670
2671 #[test]
2672 fn the_declaration_coin_is_fixed_per_check_and_lesson_and_fair() {
2673 assert_eq!(stripped("0123456789ab", "L1"), stripped("0123456789ab", "L1"));
2674 let heads = (0..1000).filter(|i| stripped("0123456789ab", &format!("L{i}"))).count();
2675 assert!((400..600).contains(&heads), "{heads} of 1000");
2676 let checks = (0..1000).filter(|i| stripped(&format!("{i:012x}"), "L1")).count();
2677 assert!((400..600).contains(&checks), "{checks} of 1000");
2678 }
2679
2680 #[test]
2684 fn pending_gives_every_route_the_same_evidence_and_its_own_check() {
2685 let session = format!("pending-v2-{}", std::process::id());
2686 let c = |id: &str| conscience::Challenge { id: id.into(), ..Default::default() };
2687 let all = [c("A"), c("B"), c("C"), c("D"), c("E")];
2688 let edits = "Plan: the blocked message\n#borg-asked A,B @0000000000c1\n#borg-routed B=0000000000c2\n#borg-answer A: applies. B: skip.\n\
2689 edit one\n#borg-work the work so far\n#borg-queued C @0000000000c3\n#borg-placebo D @0000000000c4\nedit two\n\
2690 #borg-work later work\n#borg-asked E @0000000000c5\n";
2691 let _ = std::fs::write(edits_file(&session), edits);
2692 let state: String = edits.lines().filter(|l| DELIVERED.iter().any(|m| l.starts_with(m))).map(|l| format!("{l}\n")).collect();
2693 let j = pending(&session, &state, &all, "the final message", false, "00000000cafe");
2694 let got: Vec<(&str, &str, &str)> = j.pending.iter().map(|p| (p.lesson.id.as_str(), p.channel, p.check.as_str())).collect();
2695 assert_eq!(
2696 got,
2697 [
2698 ("A", "stop", "0000000000c1"),
2699 ("B", "stop", "0000000000c2"),
2700 ("C", "queued", "0000000000c3"),
2701 ("D", outcome::PLACEBO, "0000000000c4"),
2702 ("E", "stop", "0000000000c5")
2703 ]
2704 );
2705 let p = |id: &str| j.pending.iter().find(|p| p.lesson.id == id).unwrap();
2706 assert_eq!(
2707 (p("A").before.as_str(), p("C").before.as_str(), p("D").before.as_str()),
2708 ("Plan: the blocked message", "the work so far", "the work so far")
2709 );
2710 assert_eq!(p("C").after, "work since: edit two\nthis turn: the final message");
2711 assert_eq!(p("D").after, p("C").after, "a placebo is judged as a free delivery");
2712 assert!(p("A").after.starts_with("work since: ") && p("A").after.contains("edit one | edit two"), "{}", p("A").after);
2713 assert_eq!(p("A").after, p("B").after, "delivered together, one shared evidence");
2714 for (id, word) in [("A", "applies"), ("B", "skip")] {
2715 let x = p(id);
2716 assert_eq!(x.stripped, stripped(&x.check, id));
2717 match x.stripped {
2718 true => assert!(x.declared.is_none() && !x.after.contains(&format!("{id}: {word}")), "{x:?}"),
2719 false => assert!(x.declared.is_some() && x.after.contains(&format!("{id}: {word}")), "{x:?}"),
2720 }
2721 }
2722 assert!(!p("C").stripped && !p("D").stripped, "only questions are stripped");
2723 let live = pending(&session, &state, &all, "", true, "00000000cafe");
2725 let ids: Vec<&str> = live.pending.iter().map(|p| p.lesson.id.as_str()).collect();
2726 assert_eq!(ids, ["A", "B", "C", "D"], "E is not answered yet");
2727 assert!(j.question && j.crowded.is_empty());
2728 let _ = std::fs::remove_file(edits_file(&session));
2729 }
2730
2731 #[test]
2736 fn a_stripped_declaration_leaves_every_evidence_of_the_call() {
2737 let session = format!("pending-strip-{}", std::process::id());
2738 let c = |id: &str| conscience::Challenge { id: id.into(), ..Default::default() };
2739 let all = [c("A"), c("F"), c("G")];
2740 let check = |lesson: &str, strip: bool| (0u64..).map(|i| format!("{i:012x}")).find(|k| stripped(k, lesson) == strip).unwrap();
2741 let (ca, cf, cg) = (check("A", false), check("F", true), check("G", false));
2742 let answer = "Fixed the arc. F: applies";
2743 let edits = format!(
2744 "Plan: the blocked message\n#borg-asked A @{ca}\n#borg-answer A: applies\nedit one\n#borg-work the work so far\n\
2745 #borg-asked F @{cf}\n#borg-live F ms=1\n#borg-answer {answer}\n{answer}\n#borg-asked G @{cg}\n"
2746 );
2747 let _ = std::fs::write(edits_file(&session), &edits);
2748 let state: String = edits.lines().filter(|l| DELIVERED.iter().any(|m| l.starts_with(m))).map(|l| format!("{l}\n")).collect();
2749 let j = pending(&session, &state, &all, answer, false, "00000000cafe");
2750 let p = |id: &str| j.pending.iter().find(|p| p.lesson.id == id).unwrap();
2751 assert!(p("F").stripped && p("F").declared.is_none(), "{:?}", p("F"));
2752 for x in &j.pending {
2753 assert!(!format!("{} {}", x.before, x.after).to_lowercase().contains("f: applies"), "{x:?}");
2754 }
2755 assert!(p("F").after.contains("this turn: Fixed the arc."), "the rest of the message stays: {}", p("F").after);
2756 assert!(!p("A").stripped && p("A").declared == Some(true) && p("A").after.contains("A: applies"), "{:?}", p("A"));
2757 assert_eq!(without_declarations(&format!("work\n{answer}"), &j.pending), "work\nFixed the arc. ");
2759 assert_eq!(without_declarations("A: applies", &j.pending), "A: applies");
2760 let _ = std::fs::remove_file(edits_file(&session));
2761 }
2762
2763 #[test]
2768 fn a_merged_ask_of_two_draws_carries_no_pool() {
2769 let session = format!("pool-merge-{}", std::process::id());
2770 let _ = std::fs::remove_file(state_file(&session));
2771 let c = |id: &str| conscience::Challenge { id: id.into(), ..Default::default() };
2772 let (a, b, cc, d, e, f) = (c("A"), c("B"), c("C"), c("D"), c("E"), c("F"));
2773 let live: Vec<(f64, &conscience::Challenge)> = vec![(1.0, &a), (0.9, &b), (0.8, &cc), (0.7, &d)];
2774 append_p_of(&session, &live, &[&a, &b], "c1");
2775 let stop: Vec<(f64, &conscience::Challenge)> = vec![(1.0, &a), (0.9, &e), (0.8, &f)];
2776 append_p_of(&session, &stop, &[&a], "c2");
2777 let state = std::fs::read_to_string(state_file(&session)).unwrap_or_default();
2778 let merged = vec!["A".to_string(), "B".to_string()];
2779 assert_eq!(propensity_in(&state, &merged).len(), 2, "each id has its latest p");
2780 assert_eq!(pool_in(&state, &merged), Default::default());
2781 assert_eq!(pool_in(&state, &["A".to_string()]).0, ["A", "E", "F"], "A alone: the stop check's pool");
2782 assert_eq!(pool_in(&state, &["B".to_string()]).0, ["A", "B", "C", "D"], "B alone: the live check's");
2783 assert_eq!(tagged_p(&state, "#borg-p ", "c1", &["B"]).len(), 1, "B's record carries its own check's p");
2784 let _ = std::fs::remove_file(state_file(&session));
2785 }
2786
2787 #[test]
2791 fn an_early_lessons_relative_score_is_its_share_of_the_best_on_topic_match() {
2792 let c = |id: &str, q: &str| conscience::Challenge { id: id.into(), question: q.into(), scope: vec!["Orion".into()], ..Default::default() };
2793 let standing = conscience::Challenge { source: conscience::CONSTRAINT.into(), ..c("S", "harpsichord tuning") };
2794 let all = vec![c("A", "orion budget place reset arc drain"), c("B", "orion budget place"), c("C", "telescope glaciers"), standing];
2795 let work = "drain the orion budget place, never with a reset arc";
2796 let topics = vec!["Orion".to_string()];
2797 let ranked = conscience::rank(&all, work);
2798 let score = |id: &str| ranked.iter().find(|(_, x)| x.id == id).map_or(0.0, |(s, _)| *s);
2799 assert!(score("A") > score("B") && score("B") > 0.0, "{ranked:?}");
2800 let rel = early_rel(&all, work, &topics, &[&all[1], &all[3]]);
2802 assert_eq!(rel, [outcome::round_p(score("B") / score("A")), 0.0]);
2803 assert!(rel[0] < 1.0);
2804 assert_eq!(early_rel(&all, work, &topics, &[&all[0]]), [1.0]);
2805 assert!(early_rel(&all, work, &["Beacon".to_string()], &[&all[3]]).is_empty());
2807 }
2808
2809 fn decide_store(name: &str) -> std::path::PathBuf {
2813 decide_store_with(name, true)
2814 }
2815
2816 fn decide_store_with(name: &str, sure: bool) -> std::path::PathBuf {
2820 use crate::select::{policy, summary};
2821 let d = std::env::temp_dir().join(format!("borg-decide-{name}-{}", std::process::id()));
2822 let _ = std::fs::remove_dir_all(&d);
2823 std::fs::create_dir_all(&d).unwrap();
2824 let lessons = d.join("lessons.jsonl");
2825 std::fs::write(&lessons, "").unwrap();
2826 std::fs::write(outcome::path_beside(&lessons), "").unwrap();
2827 let at = |name: &str| policy::NAMES.iter().position(|n| *n == name).unwrap();
2828 let mut beta = vec![0.0; policy::P];
2829 beta[at("intercept")] = -0.5;
2830 if sure {
2831 beta[at("ask")] = -3.0;
2832 beta[at("not")] = -1.0;
2833 }
2834 let mut chol = vec![0.0; policy::P * policy::P];
2835 for k in 0..policy::P {
2836 chol[k * policy::P + k] = 0.05;
2837 }
2838 let model = policy::Model { beta, chol, sd: vec![1.0; policy::P], spread: [0.1; 3], ..policy::Model::default() };
2839 let rates = policy::Rates { free_stop: 1.0, free_live: 1.0, later: 0.0, wait: 0.0, ask_live: 1.0 };
2840 let fit = policy::Fit { key: "9-abcdef01".into(), model: Some(model), rates, ..policy::Fit::default() };
2841 let gate = summary::Gate { gain: vec![0.0; policy::DRAWS], allowance: 5.0, ..summary::Gate::default() };
2842 summary::save(&lessons, &summary::Summary { fit, gate, ..summary::Summary::default() }).unwrap();
2843 lessons
2844 }
2845
2846 fn record_beside(lessons: &std::path::Path, applied: &[(&conscience::Challenge, u8)], check: &str, r: &crate::select::Routed, basis: &Basis) -> bool {
2849 let order: Vec<&conscience::Challenge> = applied.iter().map(|(c, _)| *c).collect();
2850 let call = Call { eligible: order.len(), order: &order, tail: &[], pt: 0.0, model: "", prompt_hash: String::new(), dur_ms: 1, usd: 0.0 };
2851 let o = graded_outcome("decide-s", "r", check, true, applied, Some((r, basis)), basis.summary, &call);
2852 outcome::append(&outcome::path_beside(lessons), &o).is_ok()
2853 }
2854
2855 #[test]
2858 fn the_graded_record_carries_the_question_count_tests_draw() {
2859 use crate::select::{Log, Routed, policy, summary};
2860 let c = |id: &str| conscience::Challenge { id: id.into(), ..Default::default() };
2861 let ls = [c("A"), c("B")];
2862 let applied: Vec<(&conscience::Challenge, u8)> = ls.iter().zip([2, 1]).collect();
2863 let order: Vec<&conscience::Challenge> = ls.iter().collect();
2864 let call = Call { eligible: 2, order: &order, tail: &[], pt: 0.0, model: "", prompt_hash: String::new(), dur_ms: 1, usd: 0.0 };
2865 let s = summary::Summary::default();
2866 let basis = Basis { summary: &s, had: &[], why: "" };
2867 let routed = |source: &'static str, xk: Option<u32>, xs: Option<u32>| Routed {
2868 ask: Vec::new(),
2869 free: vec![&ls[0], &ls[1]],
2870 placebo: Vec::new(),
2871 p: vec![0.0, 0.0],
2872 pf: vec![1.0, 1.0],
2873 log: Log { policy: "learned", source, xk, xs, ..Log::default() },
2874 };
2875 let record = |r: Option<&Routed>| graded_outcome("s", "r", "0123456789ab", true, &applied, r.map(|r| (r, &basis)), &s, &call);
2876 let drawn = record(Some(&routed(policy::EXPERIMENT_CONTROL, Some(2), Some(0))));
2877 assert_eq!((drawn.source.as_str(), drawn.xk, drawn.xs), (policy::EXPERIMENT_CONTROL, Some(2), Some(0)));
2878 let outside = record(Some(&routed(policy::EVIDENCE, None, None)));
2879 assert_eq!((outside.source.as_str(), outside.xk, outside.xs), (policy::EVIDENCE, None, None));
2880 let failed = record(None);
2881 assert_eq!((failed.failed, failed.xk, failed.xs), (true, None, None));
2882 }
2883
2884 fn graded_records(lessons: &std::path::Path) -> Vec<outcome::Outcome> {
2885 outcome::read(&outcome::path_beside(lessons)).into_iter().filter(|o| o.kind == outcome::GRADED).collect()
2886 }
2887
2888 #[test]
2891 fn a_check_decides_on_the_summary_under_the_lock_with_every_decision_before_it() {
2892 use crate::select::{Policy, policy, summary};
2893 let lessons = decide_store("fresh");
2894 let stale = summary::refresh(&lessons);
2896 let c = |id: &str| conscience::Challenge { id: id.into(), ..Default::default() };
2897 let ls = [c("A"), c("B"), c("C"), c("D")];
2898 let applied: Vec<(&conscience::Challenge, u8)> = ls.iter().zip([3, 1, 2, 1]).collect();
2899 let mut gates = Vec::new();
2900 for check in ["0000000000a1", "0000000000b2"] {
2903 let at = Decide { session: "decide-fresh", check, channel: "live", lessons: &lessons, tokens: 0, recorded: true };
2904 let r = decide(Policy::Learned, &applied, &at, &stale, DECIDE_WAIT, |r, b| record_beside(&lessons, &applied, check, r, b));
2905 gates.push(r.log.gate);
2906 }
2907 let g = graded_records(&lessons);
2908 assert_eq!(g.len(), 2);
2909 assert!(g.iter().all(|o| o.policy == "learned" && o.reason.is_empty()), "{g:?}");
2910 assert_ne!(g[0].free, Vec::<String>::new(), "the first deviates: everything free at a live check, {:?}", g[0]);
2911 assert_eq!(g[0].seen, stale.key(), "nothing was decided before the first");
2912 let log = std::fs::read_to_string(outcome::path_beside(&lessons)).unwrap();
2914 let first = log.lines().next().unwrap();
2915 let after = summary::fold(&format!("{first}\n"), stale.clone());
2916 assert_eq!(after.gate.checks, stale.gate.checks + 1, "the first's decision is in the gate's ledger");
2917 assert_eq!(g[1].seen, after.key(), "decided on the summary loaded under the lock, not the one read at its start");
2918 assert_eq!(gates[1], policy::remaining(&after.gate).max(0.0), "against the gate with the first's entry");
2919 let _ = std::fs::remove_dir_all(lessons.parent().unwrap());
2920 }
2921
2922 #[test]
2928 fn two_checks_deciding_at_once_never_both_take_the_gate() {
2929 use crate::select::{Policy, policy, summary};
2930 let c = |id: &str| conscience::Challenge { id: id.into(), ..Default::default() };
2931 let ls = [c("A"), c("B"), c("C"), c("D")];
2932 let applied: Vec<(&conscience::Challenge, u8)> = ls.iter().zip([3, 1, 2, 1]).collect();
2933 let mut stores = Vec::new();
2934 for (name, sure, sources) in [("race", true, &[policy::EVIDENCE][..]), ("race-test", false, &[policy::EXPERIMENT, policy::EXPERIMENT_CONTROL][..])] {
2935 let lessons = decide_store_with(name, sure);
2936 let stale = summary::refresh(&lessons);
2937 let both = std::sync::Barrier::new(2);
2940 std::thread::scope(|s| {
2941 for check in ["0000000000c1", "0000000000c2"] {
2942 let (applied, lessons, stale, both) = (&applied, &lessons, &stale, &both);
2943 s.spawn(move || {
2944 let at = Decide { session: "decide-race", check, channel: "live", lessons, tokens: 0, recorded: true };
2945 decide(Policy::Learned, applied, &at, stale, std::time::Duration::ZERO, |r, b| {
2946 both.wait();
2947 record_beside(lessons, applied, check, r, b)
2948 });
2949 });
2950 }
2951 });
2952 let mut got: Vec<(String, String, String, bool)> =
2953 graded_records(&lessons).into_iter().map(|o| (o.policy, o.source, o.reason, o.xk.is_some())).collect();
2954 got.sort();
2955 assert_eq!(got.len(), 2, "{name}: {got:?}");
2956 assert_eq!(got[0], ("fixed".to_string(), "fixed".to_string(), outcome::DECIDED_BUSY.to_string(), false), "{name}: the other took the fixed rule");
2957 let (policy, source, reason, drawn) = &got[1];
2958 assert!(policy == "learned" && sources.contains(&source.as_str()) && reason.is_empty(), "{name}: one decided under the lock: {got:?}");
2959 assert_eq!(*drawn, !sure, "{name}: the test's draw on its record alone");
2960 assert!(policy::remaining(&summary::refresh(&lessons).gate) >= -1e-9, "{name}: the gate never overspent");
2961 stores.push(lessons);
2962 }
2963 let stale = summary::refresh(&stores[0]);
2965 let gone = std::path::Path::new("/nonexistent/borg-decide/lessons.jsonl");
2966 let at = Decide { session: "decide-race", check: "0000000000c3", channel: "live", lessons: gone, tokens: 0, recorded: true };
2967 let mut why = "";
2968 let r = decide(Policy::Learned, &applied, &at, &stale, DECIDE_WAIT, |_, b| {
2969 why = b.why;
2970 true
2971 });
2972 assert_eq!((r.log.policy, why), ("fixed", outcome::DECIDED_NO_LOCK));
2973 for lessons in stores {
2974 let _ = std::fs::remove_dir_all(lessons.parent().unwrap());
2975 }
2976 }
2977
2978 #[test]
2982 fn a_policy_that_reads_no_gate_decides_by_itself_whoever_holds_the_lock() {
2983 use crate::select::{Ctx, Policy, graded_under, summary};
2984 let lessons = decide_store("nolock");
2985 let stale = summary::refresh(&lessons);
2986 let c = |id: &str| conscience::Challenge { id: id.into(), ..Default::default() };
2987 let ls = [c("A"), c("B"), c("C"), c("D")];
2988 let applied: Vec<(&conscience::Challenge, u8)> = ls.iter().zip([3, 1, 3, 2]).collect();
2989 let ids = |cs: &[&conscience::Challenge]| cs.iter().map(|c| c.id.clone()).collect::<Vec<_>>();
2990 let held = lock_within(&decide_lock(&lessons), std::time::Duration::ZERO).unwrap();
2991 let check = "0000000000e1";
2992 let at = Decide { session: "decide-nolock", check, channel: "stop", lessons: &lessons, tokens: 0, recorded: true };
2993 let ctx = Ctx {
2994 session: at.session,
2995 check,
2996 channel: at.channel,
2997 lessons: &lessons,
2998 summary: &stale,
2999 tokens: 0,
3000 had: &[],
3001 alpha: crate::select::alpha(&lessons),
3002 };
3003 let fixed = ids(&graded_under(Policy::Fixed, &applied, &ctx).ask);
3004 for policy in [Policy::Fixed, Policy::Cap(1), Policy::Attention] {
3005 let own = graded_under(policy, &applied, &ctx);
3006 let mut got = None;
3007 let r = decide(policy, &applied, &at, &stale, std::time::Duration::ZERO, |r, b| {
3008 got = Some((r.log.policy, b.why, b.summary.key()));
3009 true
3010 });
3011 assert_eq!(got, Some((policy.name(), "", stale.key())), "{policy:?}");
3012 assert_eq!((ids(&r.ask), ids(&r.free)), (ids(&own.ask), ids(&own.free)), "{policy:?}: its own rule");
3013 }
3014 assert_ne!(ids(&graded_under(Policy::Cap(1), &applied, &ctx).ask), fixed);
3016 let mut why = "";
3017 let r = decide(Policy::Learned, &applied, &at, &stale, std::time::Duration::ZERO, |_, b| {
3018 why = b.why;
3019 true
3020 });
3021 assert_eq!((r.log.policy, why), ("fixed", outcome::DECIDED_BUSY), "the learned policy alone waits for the lock");
3022 drop(held);
3023 let _ = std::fs::remove_dir_all(lessons.parent().unwrap());
3024 }
3025
3026 #[test]
3031 fn a_learned_decision_whose_record_cannot_land_takes_the_fixed_rule() {
3032 use crate::select::{Ctx, Policy, graded_under, policy, summary};
3033 let lessons = decide_store("unrecorded");
3034 let c = |id: &str| conscience::Challenge { id: id.into(), ..Default::default() };
3035 let ls = [c("A"), c("B"), c("C"), c("D")];
3036 let applied: Vec<(&conscience::Challenge, u8)> = ls.iter().zip([3, 1, 2, 1]).collect();
3037 let ids = |cs: &[&conscience::Challenge]| cs.iter().map(|c| c.id.clone()).collect::<Vec<_>>();
3038 let at = |check: &'static str, recorded: bool| Decide { session: "decide-unrecorded", check, channel: "live", lessons: &lessons, tokens: 0, recorded };
3039 let fixed = |check: &str, s: &summary::Summary| {
3040 let ctx = Ctx {
3041 session: "decide-unrecorded",
3042 check,
3043 channel: "live",
3044 lessons: &lessons,
3045 summary: s,
3046 tokens: 0,
3047 had: &[],
3048 alpha: crate::select::alpha(&lessons),
3049 };
3050 let r = graded_under(Policy::Fixed, &applied, &ctx);
3051 (ids(&r.ask), ids(&r.free), ids(&r.placebo))
3052 };
3053 let stale = summary::refresh(&lessons);
3055 let r = decide(Policy::Learned, &applied, &at("0000000000f1", true), &stale, std::time::Duration::ZERO, |r, b| {
3056 record_beside(&lessons, &applied, "0000000000f1", r, b)
3057 });
3058 assert_eq!(r.log.source, policy::EVIDENCE, "{:?}", r.log);
3059 let (ask, free, _) = fixed("0000000000f1", &stale);
3060 assert_ne!((ids(&r.ask), ids(&r.free)), (ask, free), "it deviated");
3061 let gate = summary::refresh(&lessons).gate;
3062 for check in ["0000000000f2", "0000000000f3"] {
3064 let stale = summary::refresh(&lessons);
3065 let mut tried = Vec::new();
3066 let r = decide(Policy::Learned, &applied, &at(check, false), &stale, std::time::Duration::ZERO, |r, b| {
3067 tried.push((r.log.policy, b.why));
3068 false
3069 });
3070 assert_eq!(tried, [("fixed", outcome::DECIDED_NO_RECORD)], "{check}");
3071 assert_eq!((ids(&r.ask), ids(&r.free), ids(&r.placebo)), fixed(check, &stale), "{check}");
3072 }
3073 let stale = summary::refresh(&lessons);
3076 let mut tried = Vec::new();
3077 let r = decide(Policy::Learned, &applied, &at("0000000000f4", true), &stale, DECIDE_WAIT, |r, b| {
3079 tried.push((r.log.policy, b.why));
3080 false
3081 });
3082 assert_eq!(tried, [("learned", ""), ("fixed", outcome::DECIDED_NO_RECORD)]);
3083 assert_eq!((ids(&r.ask), ids(&r.free), ids(&r.placebo)), fixed("0000000000f4", &stale));
3084 assert_eq!(graded_records(&lessons).len(), 1, "only the first check's record");
3085 assert_eq!(summary::refresh(&lessons).gate, gate, "no unrecorded decision moved the gate");
3086 let _ = std::fs::remove_dir_all(lessons.parent().unwrap());
3087 }
3088
3089 #[test]
3094 fn a_lesson_waiting_in_the_queue_never_takes_a_free_or_placebo_slot() {
3095 use crate::select::{Policy, summary};
3096 let lessons = decide_store("queued");
3097 let stale = summary::refresh(&lessons);
3098 let session = format!("decide-queued-{}", std::process::id());
3099 let _ = std::fs::remove_file(state_file(&session));
3100 std::fs::write(queued_file(&session), "X @0000000000d0\nlive Y @0000000000d0\nplacebo Z @0000000000d0\n").unwrap();
3101 let c = |id: &str| conscience::Challenge { id: id.into(), ..Default::default() };
3102 let named: Vec<String> = (1..=10).map(|i| format!("L{i:02}")).collect();
3103 let ls: Vec<conscience::Challenge> = ["X", "Y", "Z"].iter().map(|i| c(i)).chain(named.iter().map(|i| c(i))).collect();
3104 let ids = |cs: &[&conscience::Challenge]| cs.iter().map(|c| c.id.clone()).collect::<Vec<_>>();
3105 let first: Vec<(&conscience::Challenge, u8)> = ls.iter().map(|c| (c, if ["X", "Y"].contains(&c.id.as_str()) { 2 } else { 1 })).collect();
3108 let last: Vec<(&conscience::Challenge, u8)> = ls.iter().map(|c| (c, if c.id.starts_with('L') { 2 } else { 1 })).collect();
3109 let waits = |l: &[String]| l.iter().any(|i| i == "X" || i == "Y");
3110 for (check, applied) in [("0000000000d1", &first), ("0000000000d2", &last)] {
3111 let at = Decide { session: &session, check, channel: "stop", lessons: &lessons, tokens: 0, recorded: true };
3112 let r = decide(Policy::Fixed, applied, &at, &stale, std::time::Duration::ZERO, |r, b| record_beside(&lessons, applied, check, r, b));
3113 let (free, placebo) = (ids(&r.free), ids(&r.placebo));
3114 assert_eq!(free.len(), conscience::CAP, "{check}: every free slot taken: {free:?}");
3115 assert!(!waits(&free) && !waits(&placebo), "{check}: free {free:?}, placebo {placebo:?}");
3116 }
3117 assert_eq!(graded_records(&lessons)[1].placebo, ["Z"], "waiting as a placebo, Z is still drawn");
3118 assert!(graded_records(&lessons)[0].free.contains(&"Z".to_string()), "and still goes free");
3119 let g = graded_records(&lessons);
3120 assert_eq!(g.iter().map(|o| o.nofree.clone()).collect::<Vec<_>>(), [["X", "Y"], ["X", "Y"]], "{g:?}");
3121 let _ = std::fs::remove_file(queued_file(&session));
3122 let _ = std::fs::remove_dir_all(lessons.parent().unwrap());
3123 }
3124
3125 #[test]
3126 fn only_an_adapter_reads_which_messages_an_answer_showed() {
3127 let out = json!({"hookSpecificOutput": {"additionalContext": "[borg] Message from s1: hi"}, "shown_ids": ["m0123456789ab"]});
3128 for name in ["claude", "codex"] {
3129 let h = harness::by_name(name).unwrap();
3130 assert_eq!(for_harness(h, out.clone()), json!({"hookSpecificOutput": out["hookSpecificOutput"]}), "{name}");
3131 }
3132 for name in ["omp", "opencode"] {
3133 assert_eq!(for_harness(harness::by_name(name).unwrap(), out.clone()), out, "{name}");
3134 }
3135 }
3136}