//! Deciding where a capture goes from what was seen around it (`docs/routing.md`).
//!
//! `look` gathers [`Evidence`]; [`decide`] turns it into a [`Judgement`] without reading the
//! clock or doing I/O, so the same evidence always gives the same decision.
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::model::Destination;
/// A send needs at least this score from clues alone (recency doesn't count toward it)...
pub const SEND_AT: u32 = 95;
/// ...and this lead over the second candidate.
pub const LEAD: u32 = 15;
/// Below this a candidate isn't worth suggesting.
pub const OFFER_AT: u32 = 40;
/// A runner-up needs this much from clues to be offered one click away.
pub const ALT_AT: u32 = 15;
/// At most this many runners-up are offered beside the best.
const ALTERNATIVES: usize = 2;
/// Everything [`decide`] needs. Plain data, saved as the bundle's `routing.json`.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Evidence {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub address: Option
,
#[serde(default)]
pub clues: Vec,
#[serde(default)]
pub candidates: Vec,
/// The capture's end, epoch ms; recency is measured from here.
pub now_ms: u64,
/// The browser tab's URL, when there was one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option,
/// The captured terminal's project folder, what a `routing.terminals` rule keys on.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub terminal: Option,
/// Why OpenCode's sessions couldn't all be read, when they couldn't: `candidates` holds
/// what was read before it failed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sessions_error: Option,
}
/// A destination someone stated. Obeyed, never weighed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind", content = "session")]
pub enum Address {
/// The user picked it (`--session`, a chip).
Chosen(String),
/// The recording carries it (a ScrawlKit timeline's `session`, an earlier routing).
Recorded(String),
}
impl Clue {
/// The project this clue names, if any.
fn directory(&self) -> Option {
match &self.pointer {
Pointer::Session { directory, .. } => directory.clone(),
Pointer::Folder(folder) => Some(folder.root.clone()),
Pointer::Words { .. } => None,
}
}
}
impl Address {
pub fn session(&self) -> &str {
match self {
Self::Chosen(id) | Self::Recorded(id) => id,
}
}
}
/// An observed fact pointing at sessions.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Clue {
pub source: Source,
pub pointer: Pointer,
/// What was seen, for explanations.
pub note: String,
/// Full points when this clue is worth more or less than its source usually is (the viewed
/// session when the capture is about OpenCode's own interface, say).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub points: Option,
}
impl Clue {
pub fn new(source: Source, pointer: Pointer, note: impl Into) -> Self {
Self {
source,
pointer,
note: note.into(),
points: None,
}
}
pub fn worth(mut self, points: u32) -> Self {
self.points = Some(points);
self
}
fn full(&self) -> u32 {
self.points.unwrap_or_else(|| self.source.points())
}
}
/// Where a clue came from. Each source counts once per candidate.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Source {
/// A session named at the start of what was said ("tell scrawl …"; `named`). Obeyed ahead
/// of everything but an address.
Named,
/// The session a page names itself, by a `` tag or an
/// `.opencode-session` file in its folder (`served::marker`). Obeyed ahead of rules.
Signed,
/// A `routing.sites` rule covering the tab's URL. Obeyed ahead of weighing when it finds a
/// session.
Rule,
/// A `routing.apps` rule covering the captured app (Jev routing). Obeyed like a site rule.
AppRule,
/// A `routing.terminals` rule covering the captured terminal's folder. Obeyed like a site
/// rule.
TerminalRule,
/// The git working tree the captured app's executable runs from (Jev routing): a dev build
/// names its project like a localhost port does.
DevBuild,
/// The tab registered through `/sdk.js`.
Page,
/// The process serving the tab's port on this Mac.
Port,
/// Who published the file the tab shows, when a server serves it from outside its own
/// project: the session the page names, or the one whose tool call wrote the file.
Publisher,
/// The session OpenCode shows in the captured terminal: named by its window title or its
/// command line. Weighed, worth a little more than a folder.
TerminalSession,
/// The captured terminal's focused pane.
Terminal,
/// The file the tab shows, when it's from outside the server's project: its path's words.
Document,
/// The session OpenCode Desktop showed last.
Viewed,
/// The captured app: its name (an app being built names its project), and the checkout it's
/// built from when one is open.
App,
/// Words in the window or tab title.
Title,
/// Words that were said.
Speech,
}
impl Source {
/// The `via` written into `scrawl.json`'s `destination`. The ladder's two keep their names.
pub fn via(self) -> &'static str {
match self {
Self::Page => "sdk",
Self::Port => "localhost",
other => other.label(),
}
}
fn label(self) -> &'static str {
match self {
Self::Named => "named",
Self::Signed => "signed",
Self::Rule => "rule",
Self::AppRule => "app-rule",
Self::TerminalRule => "terminal-rule",
Self::DevBuild => "dev-build",
Self::Page => "page",
Self::Port => "port",
Self::Publisher => "publisher",
Self::TerminalSession => "terminal-session",
Self::Terminal => "terminal",
Self::Document => "document",
Self::Viewed => "viewed",
Self::App => "app",
Self::Title => "title",
Self::Speech => "speech",
}
}
/// Full points for a clue of this source that names a candidate.
fn points(self) -> u32 {
match self {
Self::Named | Self::Signed | Self::TerminalSession => 100,
Self::Rule
| Self::AppRule
| Self::TerminalRule
| Self::DevBuild
| Self::Page
| Self::Port
| Self::Publisher => 95,
Self::Terminal => 70,
Self::Viewed => 60,
Self::App => 50,
Self::Title | Self::Document => 40,
Self::Speech => 25,
}
}
}
/// A page naming its session outright is worth a little more than a folder.
const PAGE_SESSION: u32 = 100;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum Pointer {
/// `directory` is a folder the page also named, kept for the record.
Session {
id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
directory: Option,
},
Folder(Folder),
Words {
words: Vec,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Folder {
pub path: PathBuf,
/// Its project: the git root, or `path` outside a repository.
pub root: PathBuf,
/// Whether sessions anywhere under `root` count (inside a repository).
pub tree: bool,
/// The repository's main checkout, shared by its worktrees.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub repo: Option,
}
/// An open root session.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Candidate {
pub id: String,
#[serde(default)]
pub title: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub directory: Option,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub repo: Option,
#[serde(default)]
pub updated_ms: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub viewed_ms: Option,
}
impl Candidate {
pub fn label(&self) -> &str {
if self.title.is_empty() {
&self.id
} else {
&self.title
}
}
/// The words that name it, and how: its title's words, its folder's or repository's name
/// when that's one word, and the pieces of its folder's name split on `-`, `_` and `.`.
fn names(&self) -> BTreeMap {
let mut names = BTreeMap::new();
let mut add = |word: String, naming: Naming| {
let entry = names.entry(word).or_insert(naming);
*entry = (*entry).min(naming);
};
let title = words(&self.title);
if let [whole] = title.as_slice() {
add(whole.clone(), Naming::Whole);
} else {
for word in title {
add(word, Naming::Title);
}
}
let base = |path: &Path| {
path.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default()
};
for path in [self.directory.as_deref(), self.repo.as_deref()]
.into_iter()
.flatten()
{
if let [whole] = words(&base(path)).as_slice()
&& base(path).eq_ignore_ascii_case(whole)
{
add(whole.clone(), Naming::Whole);
}
}
if let Some(dir) = self.directory.as_deref() {
// OpenCode's own worktrees get made-up names ("stellar-star"): they name nothing.
let made_up = dir.components().any(|c| c.as_os_str() == "worktree");
let worktree = self.repo.as_deref().is_some_and(|repo| repo != dir);
if !made_up {
for word in words(&base(dir)) {
add(
word,
if worktree {
Naming::Worktree
} else {
Naming::Folder
},
);
}
}
}
names
}
}
/// How a word names a candidate, strongest first.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Naming {
/// Its whole title, or its folder's or repository's whole name.
Whole,
/// A word of its title.
Title,
/// A piece of its folder's name.
Folder,
/// A piece of a worktree's name, worth half: worktrees are named for a task's words.
Worktree,
}
impl Naming {
/// Whether `word` names a candidate this way. Ordinary words ("loading", "search", "chat")
/// are in names for what the work is about, and said for everything else, so for them only a
/// whole name counts.
fn counts(self, word: &str) -> bool {
self == Self::Whole || !is_common(word)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Policy {
/// Smart routing off: `routing::route_capture`'s ladder, which the tests check this
/// reproduces. The first source with a clue decides, and its newest session wins.
Ladder,
/// Weigh every clue and send only when one candidate is clearly ahead.
Weigh,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Judgement {
pub decision: Decision,
/// Supported candidates, best first.
pub ranking: Vec,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum Decision {
/// `instead`: runners-up the undo window offers one click away.
Send {
to: Scored,
#[serde(skip_serializing_if = "Vec::is_empty")]
instead: Vec,
},
/// The suggestion first, then its runners-up. Nothing is sent until one is picked.
Offer {
choices: Vec,
},
Keep {
reason: String,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Scored {
pub candidate: Candidate,
pub score: u32,
pub reasons: Vec,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Reason {
pub basis: Basis,
pub points: u32,
pub why: String,
/// The project the clue named, recorded as the destination's `directory`.
#[serde(skip_serializing_if = "Option::is_none")]
pub directory: Option,
}
/// What a reason rests on.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind", content = "source")]
pub enum Basis {
Chosen,
Recorded,
Clue(Source),
Recent,
/// Jev's pick (`jev`).
Jev,
/// HOME, where captures go when Jev can't tell.
JevHome,
}
impl Basis {
fn label(self) -> &'static str {
match self {
Self::Chosen => "chosen",
Self::Recorded => "recorded",
Self::Clue(source) => source.label(),
Self::Recent => "recent",
Self::Jev => "jev",
Self::JevHome => "jev-home",
}
}
}
impl Scored {
/// The score from clues alone, without recency.
pub fn clues(&self) -> u32 {
self.reasons
.iter()
.filter(|r| r.basis != Basis::Recent)
.fold(0, |sum, r| sum.saturating_add(r.points))
}
/// The reason that gave the most points (the first on a tie), which names how it was found.
pub fn lead(&self) -> Option<&Reason> {
self.reasons
.iter()
.filter(|r| r.basis != Basis::Recent)
.fold(None, |best: Option<&Reason>, r| match best {
Some(b) if b.points >= r.points => Some(b),
_ => Some(r),
})
}
}
/// Where the evidence says the capture goes.
pub fn decide(evidence: &Evidence, policy: Policy) -> Judgement {
if let Some(address) = &evidence.address {
let to = addressed(evidence, address);
return Judgement {
decision: Decision::Send {
to: to.clone(),
instead: Vec::new(),
},
ranking: vec![to],
};
}
if let Some(judgement) = ruled(evidence, Source::Named) {
return judgement;
}
for source in [
Source::Signed,
Source::Rule,
Source::AppRule,
Source::TerminalRule,
Source::DevBuild,
] {
if let Some(judgement) = ruled(evidence, source) {
return judgement;
}
}
match policy {
Policy::Ladder => ladder(evidence),
Policy::Weigh => weigh(evidence),
}
}
fn addressed(evidence: &Evidence, address: &Address) -> Scored {
let id = address.session();
let candidate = find(&evidence.candidates, id).unwrap_or_else(|| bare(id));
let (basis, why) = match address {
Address::Chosen(_) => (Basis::Chosen, "you chose it"),
Address::Recorded(_) => (Basis::Recorded, "the recording was addressed to it"),
};
Scored {
candidate,
score: u32::MAX,
reasons: vec![Reason {
basis,
points: u32::MAX,
why: why.into(),
directory: None,
}],
}
}
/// The session a named address, a signed page, a `routing.sites` or `routing.apps` rule, or a
/// dev build (`source`) names, or the newest in its
/// folder (any folder of the folder's repository counts), sent to without weighing. `None` when
/// it names none open.
fn ruled(evidence: &Evidence, source: Source) -> Option {
let clue = evidence.clues.iter().find(|c| c.source == source)?;
let candidate = match &clue.pointer {
Pointer::Session { id, .. } => find(&evidence.candidates, id).unwrap_or_else(|| bare(id)),
// Sessions in the folder named come before the rest of its project.
Pointer::Folder(folder) => evidence
.candidates
.iter()
.filter(|c| in_project(c, folder) || same_repo(c, folder))
.max_by(|a, b| {
let named = |c: &Candidate| {
c.directory
.as_deref()
.is_some_and(|d| d.starts_with(&folder.path))
};
named(a)
.cmp(&named(b))
.then(a.updated_ms.cmp(&b.updated_ms))
.then(b.id.cmp(&a.id))
})
.cloned()?,
Pointer::Words { .. } => return None,
};
let to = Scored {
candidate,
score: clue.full(),
reasons: vec![Reason {
basis: Basis::Clue(source),
points: clue.full(),
why: clue.note.clone(),
directory: clue.directory(),
}],
};
Some(Judgement {
decision: Decision::Send {
to: to.clone(),
instead: Vec::new(),
},
ranking: vec![to],
})
}
fn find(candidates: &[Candidate], id: &str) -> Option {
candidates.iter().find(|c| c.id == id).cloned()
}
/// A session known only by its ID (not among the candidates read).
fn bare(id: &str) -> Candidate {
Candidate {
id: id.to_owned(),
title: String::new(),
directory: None,
repo: None,
updated_ms: 0,
viewed_ms: None,
}
}
// MARK: The ladder
/// The rungs, in order. Only the first source that has a clue is consulted.
const RUNGS: [Source; 2] = [Source::Page, Source::Port];
fn ladder(evidence: &Evidence) -> Judgement {
let keep = |reason: String| Judgement {
decision: Decision::Keep { reason },
ranking: Vec::new(),
};
let Some(clue) = RUNGS
.iter()
.find_map(|rung| evidence.clues.iter().find(|c| c.source == *rung))
else {
return keep("no page registration or local dev server".into());
};
let pick = match &clue.pointer {
Pointer::Session { id, .. } => {
Some(find(&evidence.candidates, id).unwrap_or_else(|| bare(id)))
}
Pointer::Folder(folder) => newest_in(&evidence.candidates, folder),
Pointer::Words { .. } => None,
};
match pick {
Some(candidate) => {
let to = Scored {
candidate,
score: clue.source.points(),
reasons: vec![Reason {
basis: Basis::Clue(clue.source),
points: clue.source.points(),
why: clue.note.clone(),
directory: clue.directory(),
}],
};
Judgement {
decision: Decision::Send {
to: to.clone(),
instead: Vec::new(),
},
ranking: vec![to],
}
}
None => keep(match &clue.pointer {
Pointer::Folder(folder) => {
format!("no open OpenCode session in {}", folder.root.display())
}
_ => clue.note.clone(),
}),
}
}
/// The most recently updated candidate in `folder`'s project.
fn newest_in(candidates: &[Candidate], folder: &Folder) -> Option {
candidates
.iter()
.filter(|c| in_project(c, folder))
.max_by(|a, b| a.updated_ms.cmp(&b.updated_ms).then(b.id.cmp(&a.id)))
.cloned()
}
/// The home folder or a filesystem root: `/` on macOS and Linux, or `/` or a
/// drive's root (`C:\`) on Windows. A root is a path with no parent.
pub(crate) fn is_home_or_root(path: &Path) -> bool {
(path.has_root() && path.parent().is_none())
|| crate::user_dirs::home_dir().is_some_and(|home| path == home)
}
fn in_project(candidate: &Candidate, folder: &Folder) -> bool {
if is_home_or_root(&folder.root) {
return false;
}
candidate
.directory
.as_deref()
.is_some_and(|dir| dir == folder.root || (folder.tree && dir.starts_with(&folder.root)))
}
// MARK: Weighing
fn weigh(evidence: &Evidence) -> Judgement {
let candidates = with_named_sessions(evidence);
let frequency = word_frequency(&candidates);
// For each folder clue, how close its closest candidate is.
let closest: Vec