feat: add bounded M13.2 process metadata selectors

Enrich local Pulse streams outside native callbacks with executable, working directory and allowlisted Steam IDs. Preserve unavailable data, check start-time consistency and never infer Steam launch from paths. Add capture fields and document best-effort limitations; diagnostics qualification remains pending.

Verification passed: enriched_process schema regression (initially failed on unknown field); process_metadata tests; cargo fmt --all -- --check; cargo check --workspace --all-targets --all-features; cargo test --workspace --all-targets --all-features --quiet; cargo test --workspace --doc --all-features; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo build --workspace --release --all-features; default/no-default workspace builds; volume_lib without defaults and with pulse; midi midir build. Hardware fixtures remain opt-in.
This commit is contained in:
Dandaedre 2026-10-18 22:25:46 +02:00
parent 64f08e9db0
commit 0e224c664b
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
13 changed files with 416 additions and 9 deletions

View File

@ -136,8 +136,8 @@ All outer crates depend inward on domain contracts; core depends on none of them
The agreed stretch-goal order is AND selectors and richer process metadata,
then targeted MPRIS media controls (M13 in `task.md`). Selector composition is
implemented in the domain/configuration layer and the fader editor's Match
captures toggle (Any/OR or All/AND); process metadata and media
controls remain future work, not additions to the current profile schema.
captures toggle (Any/OR or All/AND). Process metadata has a first bounded Pulse
adapter implementation; media controls remain planned, not current schema.
The existing `media.name` regex `(?i) - YouTube$` is sufficient for YouTube
streams whose reported title has that suffix. Do not couple this use case to
@ -151,7 +151,18 @@ with bounded reads, process-reuse checks, and unavailable values on failure.
Read only relevant environment keys; do not expose entire environments or
command lines in diagnostics. Steam IDs and launch context are evidence;
`steamapps` paths are a fallback installation hint, not proof of launch origin.
Exact normalized field names and schema syntax remain implementation decisions.
The implemented process fields are `application.process.executable`,
`application.process.working_directory`, `steam.app_id` and `steam.game_id`.
Pulse callbacks copy only reported PID/machine ID; enrichment runs afterward on
the adapter worker. Require the reported machine ID to equal the local one,
read start time before/after inspection, and discard values if the process
changes or disappears. Reads are bounded (stat 4 KiB, environment 64 KiB), and
only nonzero numeric SteamAppId/SteamGameId values leave the environment parser.
Missing/oversized/inaccessible values remain absent; paths are not launch proof.
Reported PIDs are best-effort hints, not authenticated identities; remote and
namespace-restricted applications may be unavailable. No command lines or full
environments enter diagnostics. The start-time check follows Linux
[/proc/pid/stat](https://man7.org/linux/man-pages/man5/proc_pid_stat.5.html).
MPRIS controls will address matched player instances over D-Bus using identity,
desktop ID or bus-name selectors, with Play, Pause and PlayPause actions. Keep

View File

@ -173,6 +173,14 @@ pub enum SelectorField {
ProcessBinary,
#[serde(rename = "media.name")]
MediaName,
#[serde(rename = "application.process.executable")]
ProcessExecutable,
#[serde(rename = "application.process.working_directory")]
ProcessWorkingDirectory,
#[serde(rename = "steam.app_id")]
SteamAppId,
#[serde(rename = "steam.game_id")]
SteamGameId,
}
impl SelectorField {
@ -182,6 +190,10 @@ impl SelectorField {
Self::ApplicationId => "application.id",
Self::ProcessBinary => "application.process.binary",
Self::MediaName => "media.name",
Self::ProcessExecutable => "application.process.executable",
Self::ProcessWorkingDirectory => "application.process.working_directory",
Self::SteamAppId => "steam.app_id",
Self::SteamGameId => "steam.game_id",
}
}
}
@ -622,6 +634,10 @@ impl Selector {
SelectorField::ApplicationId => MetadataField::ApplicationId,
SelectorField::ProcessBinary => MetadataField::ProcessBinary,
SelectorField::MediaName => MetadataField::MediaName,
SelectorField::ProcessExecutable => MetadataField::ProcessExecutable,
SelectorField::ProcessWorkingDirectory => MetadataField::ProcessWorkingDirectory,
SelectorField::SteamAppId => MetadataField::SteamAppId,
SelectorField::SteamGameId => MetadataField::SteamGameId,
};
match (&self.exact, &self.regex) {
(Some(pattern), None) => DomainSelector::exact(field, pattern),
@ -1046,6 +1062,10 @@ fn validate_selector(
SelectorField::ApplicationId => MetadataField::ApplicationId,
SelectorField::ProcessBinary => MetadataField::ProcessBinary,
SelectorField::MediaName => MetadataField::MediaName,
SelectorField::ProcessExecutable => MetadataField::ProcessExecutable,
SelectorField::ProcessWorkingDirectory => MetadataField::ProcessWorkingDirectory,
SelectorField::SteamAppId => MetadataField::SteamAppId,
SelectorField::SteamGameId => MetadataField::SteamGameId,
};
match (&selector.exact, &selector.regex) {
(Some(pattern), None) => DomainSelector::exact(field, pattern)

View File

@ -6,6 +6,31 @@ const EXAMPLE: &str = include_str!("../../examples/profiles/desktop.toml");
const ARCH_PIPEWIRE: &str = include_str!("../../examples/profiles/arch-pipewire.toml");
const ARCHITECTURE: &str = include_str!("../../architecture.md");
#[test]
fn enriched_process_fields_match_only_available_values() {
let metadata = StreamMetadata::new().with_process_metadata(
Some("/games/Game/game.exe".into()),
Some("/games/Game".into()),
Some("123".into()),
Some("456".into()),
);
for (field, pattern) in [
("application.process.executable", "/games/Game/game.exe"),
("application.process.working_directory", "/games/Game"),
("steam.app_id", "123"),
("steam.game_id", "456"),
] {
let source = EXAMPLE.replace(
"field = \"application.name\", exact = \"Music Player\"",
&format!("field = {field:?}, exact = {pattern:?}"),
);
let profile = Profile::parse(&source).unwrap();
let matcher = profile.applications()[0].matcher().unwrap();
assert!(matcher.matches(&metadata));
assert!(!matcher.matches(&StreamMetadata::new()));
}
}
#[test]
fn selector_composition_defaults_to_any_and_all_requires_every_field() {
let source = EXAMPLE.replace(

View File

@ -19,6 +19,14 @@ pub enum MetadataField {
ProcessBinary,
/// Backend `media.name`.
MediaName,
/// Locally observed executable path, not merely a reported binary name.
ProcessExecutable,
/// Locally observed working directory.
ProcessWorkingDirectory,
/// SteamAppId launch-environment evidence (not proof of launch origin).
SteamAppId,
/// SteamGameId launch-environment evidence, including non-Steam shortcuts.
SteamGameId,
}
/// Normalized fields plus untouched backend metadata for diagnostics.
@ -28,6 +36,10 @@ pub struct StreamMetadata {
application_id: Option<String>,
process_binary: Option<String>,
media_name: Option<String>,
process_executable: Option<String>,
process_working_directory: Option<String>,
steam_app_id: Option<String>,
steam_game_id: Option<String>,
raw: BTreeMap<String, String>,
}
@ -66,6 +78,22 @@ impl StreamMetadata {
self
}
/// Attaches adapter-observed process metadata. Missing values stay unknown.
#[must_use]
pub fn with_process_metadata(
mut self,
executable: Option<String>,
working_directory: Option<String>,
steam_app_id: Option<String>,
steam_game_id: Option<String>,
) -> Self {
self.process_executable = executable;
self.process_working_directory = working_directory;
self.steam_app_id = steam_app_id;
self.steam_game_id = steam_game_id;
self
}
/// Adds an untouched backend property for inspection.
#[must_use]
pub fn with_raw_property(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
@ -81,6 +109,10 @@ impl StreamMetadata {
MetadataField::ApplicationId => self.application_id.as_deref(),
MetadataField::ProcessBinary => self.process_binary.as_deref(),
MetadataField::MediaName => self.media_name.as_deref(),
MetadataField::ProcessExecutable => self.process_executable.as_deref(),
MetadataField::ProcessWorkingDirectory => self.process_working_directory.as_deref(),
MetadataField::SteamAppId => self.steam_app_id.as_deref(),
MetadataField::SteamGameId => self.steam_game_id.as_deref(),
}
}

View File

@ -124,9 +124,26 @@ selectors = [
```
Supported fields are `application.name`, `application.id`,
`application.process.binary`, and `media.name`. Exact matches are whole-string
`application.process.binary`, `media.name`, `application.process.executable`,
`application.process.working_directory`, `steam.app_id`, and `steam.game_id`.
Exact matches are whole-string
and case-sensitive. Regexes use Rust's bounded `regex` syntax.
The last four fields are best-effort Linux process observations, currently
provided by the Pulse adapter (including PipeWire's Pulse compatibility server).
Enrichment requires a reported PID and a machine ID matching `/etc/machine-id`.
Executable and working-directory values come from `/proc`; Steam IDs come only
from numeric, nonzero `SteamAppId` / `SteamGameId` environment entries. These
are launch-context evidence, not authenticated proof that Steam launched the
process. A path containing `steamapps` never creates a Steam ID.
Unavailable fields do not match. Processes that exit or change start time during
inspection, restricted `/proc`, remote
servers, container/PID namespace differences, and large environments can prevent
enrichment. Environment reads are limited to 64 KiB; only the two allowlisted IDs
are retained, never complete environment contents or command lines. Proton may
report a Wine executable while its working directory identifies the game.
Applications may set `selector_mode = "all"` to require every selector to
match (AND). The default `"any"` preserves OR matching for existing profiles.
The fader editor's **Match captures** row toggles **Any (OR)** / **All (AND)**

View File

@ -459,6 +459,10 @@ fn selector(field: &str, pattern: String, regex: bool) -> Result<SelectorDraft,
"application.id" => SelectorField::ApplicationId,
"application.process.binary" => SelectorField::ProcessBinary,
"media.name" => SelectorField::MediaName,
"application.process.executable" => SelectorField::ProcessExecutable,
"application.process.working_directory" => SelectorField::ProcessWorkingDirectory,
"steam.app_id" => SelectorField::SteamAppId,
"steam.game_id" => SelectorField::SteamGameId,
_ => {
return Err(ConfigError::Validation {
path: "application.selector.field".to_owned(),

View File

@ -290,6 +290,12 @@ const fn selector_field_name(field: fader_config::SelectorField) -> &'static str
fader_config::SelectorField::ApplicationId => "application.id",
fader_config::SelectorField::ProcessBinary => "application.process.binary",
fader_config::SelectorField::MediaName => "media.name",
fader_config::SelectorField::ProcessExecutable => "application.process.executable",
fader_config::SelectorField::ProcessWorkingDirectory => {
"application.process.working_directory"
}
fader_config::SelectorField::SteamAppId => "steam.app_id",
fader_config::SelectorField::SteamGameId => "steam.game_id",
}
}

View File

@ -4,6 +4,8 @@
mod policy;
#[cfg(feature = "pulse")]
mod process_metadata;
#[cfg(feature = "pulse")]
mod pulse;
#[cfg(feature = "pulse")]
mod pulse_worker;

View File

@ -0,0 +1,263 @@
//! Bounded, best-effort Linux process enrichment outside native callbacks.
//!
//! Only explicitly local process IDs are inspected. Environment contents never
//! leave this module: only allowlisted numeric Steam IDs enter stream metadata.
use fader_core::StreamMetadata;
use std::{
fs,
io::{self, Read},
path::Path,
sync::OnceLock,
};
const MAX_ENV_BYTES: u64 = 64 * 1024;
const MAX_STAT_BYTES: u64 = 4096;
#[derive(Default)]
struct ProcessFields {
executable: Option<String>,
cwd: Option<String>,
steam_app_id: Option<String>,
steam_game_id: Option<String>,
}
trait ProcessSource {
fn start_time(&self, pid: u32) -> Option<u64>;
fn link(&self, pid: u32, name: &str) -> Option<String>;
fn environment(&self, pid: u32) -> Option<Vec<u8>>;
}
struct ProcFs;
fn bounded_read(path: &Path, maximum: u64) -> io::Result<Vec<u8>> {
read_limited(fs::File::open(path)?, maximum)
}
fn read_limited(reader: impl Read, maximum: u64) -> io::Result<Vec<u8>> {
let mut bytes = Vec::new();
reader.take(maximum + 1).read_to_end(&mut bytes)?;
if bytes.len() as u64 > maximum {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"process metadata exceeds limit",
));
}
Ok(bytes)
}
fn start_time(stat: &[u8]) -> Option<u64> {
// comm is parenthesized and may contain spaces or parentheses. Field 22 is
// the twentieth field after the closing comm delimiter (state is field 3).
std::str::from_utf8(stat)
.ok()?
.rsplit_once(") ")?
.1
.split_whitespace()
.nth(19)?
.parse()
.ok()
}
impl ProcessSource for ProcFs {
fn start_time(&self, pid: u32) -> Option<u64> {
start_time(&bounded_read(Path::new(&format!("/proc/{pid}/stat")), MAX_STAT_BYTES).ok()?)
}
fn link(&self, pid: u32, name: &str) -> Option<String> {
fs::read_link(format!("/proc/{pid}/{name}"))
.ok()?
.into_os_string()
.into_string()
.ok()
}
fn environment(&self, pid: u32) -> Option<Vec<u8>> {
bounded_read(Path::new(&format!("/proc/{pid}/environ")), MAX_ENV_BYTES).ok()
}
}
fn steam_id(environment: &[u8], key: &[u8]) -> Option<String> {
let mut matches = environment.split(|byte| *byte == 0).filter_map(|entry| {
let value = entry.strip_prefix(key)?.strip_prefix(b"=")?;
if value.is_empty() || value.len() > 20 || !value.iter().all(u8::is_ascii_digit) {
return None;
}
let value = std::str::from_utf8(value).ok()?.parse::<u64>().ok()?;
(value != 0).then(|| value.to_string())
});
let first = matches.next()?;
// Duplicate conflicting keys are not reliable evidence.
matches.all(|value| value == first).then_some(first)
}
fn inspect(source: &impl ProcessSource, pid: u32) -> ProcessFields {
let Some(before) = source.start_time(pid) else {
return ProcessFields::default();
};
let executable = source.link(pid, "exe");
let cwd = source.link(pid, "cwd");
let environment = source.environment(pid);
let fields = ProcessFields {
executable,
cwd,
steam_app_id: environment
.as_deref()
.and_then(|value| steam_id(value, b"SteamAppId")),
steam_game_id: environment
.as_deref()
.and_then(|value| steam_id(value, b"SteamGameId")),
};
if source.start_time(pid) == Some(before) {
fields
} else {
ProcessFields::default()
}
}
pub(crate) fn enrich(metadata: StreamMetadata) -> StreamMetadata {
static MACHINE_ID: OnceLock<Option<String>> = OnceLock::new();
let local = MACHINE_ID.get_or_init(|| {
let bytes = bounded_read(Path::new("/etc/machine-id"), 128).ok()?;
let value = String::from_utf8(bytes).ok()?.trim().to_owned();
(!value.is_empty()).then_some(value)
});
let reported_machine = metadata.raw().get("application.process.machine_id");
if local.is_none() || reported_machine != local.as_ref() {
return metadata;
}
let Some(pid) = metadata
.raw()
.get("application.process.id")
.and_then(|value| value.parse::<u32>().ok())
.filter(|pid| *pid > 0)
else {
return metadata;
};
let fields = inspect(&ProcFs, pid);
metadata.with_process_metadata(
fields.executable,
fields.cwd,
fields.steam_app_id,
fields.steam_game_id,
)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
struct FakeProc {
reused: bool,
denied: bool,
steam: bool,
reads: Cell<u32>,
}
impl ProcessSource for FakeProc {
fn start_time(&self, _: u32) -> Option<u64> {
let count = self.reads.get();
self.reads.set(count + 1);
(!self.denied).then_some(if self.reused && count > 0 { 2 } else { 1 })
}
fn link(&self, _: u32, name: &str) -> Option<String> {
Some(
if name == "exe" {
"/games/steamapps/common/Game/game.exe"
} else {
"/games/steamapps/common/Game"
}
.into(),
)
}
fn environment(&self, _: u32) -> Option<Vec<u8>> {
self.steam
.then(|| b"SECRET=never-publish\0SteamAppId=123\0SteamGameId=123\0".to_vec())
}
}
#[test]
fn steam_launch_evidence_is_allowlisted_and_paths_are_not_launch_proof() {
for steam in [false, true] {
let fields = inspect(
&FakeProc {
reused: false,
denied: false,
steam,
reads: Cell::new(0),
},
42,
);
assert!(fields.executable.unwrap().contains("steamapps"));
assert_eq!(fields.steam_app_id.as_deref(), steam.then_some("123"));
assert_eq!(fields.steam_game_id.as_deref(), steam.then_some("123"));
}
}
#[test]
fn reused_or_unavailable_process_never_supplies_metadata() {
for (reused, denied) in [(true, false), (false, true)] {
let fields = inspect(
&FakeProc {
reused,
denied,
steam: true,
reads: Cell::new(0),
},
42,
);
assert!(fields.executable.is_none());
assert!(fields.cwd.is_none());
assert!(fields.steam_app_id.is_none());
}
}
#[test]
fn malformed_or_conflicting_steam_ids_are_unavailable() {
for value in [
b"SteamAppId=0\0".as_slice(),
b"SteamAppId=nope\0",
b"SteamAppId=1\0SteamAppId=2\0",
] {
assert!(steam_id(value, b"SteamAppId").is_none());
}
assert_eq!(
steam_id(b"SteamGameId=1234567890123\0", b"SteamGameId").as_deref(),
Some("1234567890123")
);
}
#[test]
fn stat_parsing_handles_spaces_and_parentheses_in_comm() {
let stat = format!("42 (a ) b) S {} 12345 999", "0 ".repeat(18));
assert_eq!(start_time(stat.as_bytes()), Some(12345));
assert_eq!(start_time(b"truncated"), None);
}
#[test]
fn bounded_reads_reject_truncation_and_stop_at_limit_plus_one() {
let mut reader = io::Cursor::new(vec![b'x'; 100]);
assert!(read_limited(&mut reader, 8).is_err());
assert_eq!(reader.position(), 9);
assert_eq!(
read_limited(io::Cursor::new(b"12345678"), 8).unwrap(),
b"12345678"
);
}
#[test]
fn foreign_or_unknown_machine_never_enriches_a_local_pid() {
for machine in ["", "not-the-local-machine-id"] {
let metadata = enrich(
StreamMetadata::new()
.with_raw_property("application.process.machine_id", machine)
.with_raw_property("application.process.id", std::process::id().to_string()),
);
assert!(
metadata
.value(fader_core::MetadataField::ProcessExecutable)
.is_none()
);
}
}
}

View File

@ -504,6 +504,15 @@ fn copy_stream(
properties::MEDIA_NAME,
info.proplist.get_str(properties::MEDIA_NAME),
),
(
properties::APPLICATION_PROCESS_ID,
info.proplist.get_str(properties::APPLICATION_PROCESS_ID),
),
(
properties::APPLICATION_PROCESS_MACHINE_ID,
info.proplist
.get_str(properties::APPLICATION_PROCESS_MACHINE_ID),
),
]
.into_iter()
.fold(StreamMetadata::new(), |metadata, (key, value)| {
@ -515,7 +524,7 @@ fn copy_stream(
properties::APPLICATION_ID => metadata.with_application_id(value),
properties::APPLICATION_PROCESS_BINARY => metadata.with_process_binary(value),
properties::MEDIA_NAME => metadata.with_media_name(value),
_ => metadata,
_ => metadata.with_raw_property(key, value),
}
});
let gains = info

View File

@ -743,7 +743,7 @@ fn emit_stream(
) -> bool {
events.emit(WorkerEvent::StreamMetadata {
stream: handle,
metadata: stream.metadata,
metadata: crate::process_metadata::enrich(stream.metadata),
volume_writable: stream.volume_writable,
}) && events.emit(WorkerEvent::Adapter(AdapterEvent::Observed {
stream: handle,

View File

@ -599,6 +599,12 @@ YouTube capture use case; no browser-name condition is needed.
unavailable state for exited/inaccessible/sandboxed processes. Tests cover
native and Proton-like fixtures, Steam IDs, non-Steam processes and path-only
hints; a `steamapps` path must not be treated as proof Steam launched a game.
First slice: bounded Pulse-worker enrichment and four selectable fields
(executable, working_directory, steam.app_id, steam.game_id), local-machine
guard and start-time consistency check. Fixture coverage includes missing
process data, PID reuse, Steam/path-only cases, malformed IDs and bounded
reads. Dedicated per-stream metadata diagnostics and fuller sandbox/native
integration qualification remain pending; do not mark this milestone complete.
- [ ] **M13.3 Targeted MPRIS controls:** add Play, Pause and PlayPause via matched
player identity/desktop ID/bus name, without keyboard simulation.
Dependencies: M13.1, M13.2, M5.2, M9.5. Acceptance: a QBZ-specific binding

View File

@ -3114,7 +3114,7 @@ impl<C: MixerClient> LiveTui<C> {
KeyCode::Up => editor.selected = editor.selected.saturating_sub(1),
KeyCode::Down => editor.selected = (editor.selected + 1).min(3),
KeyCode::Left if editor.selected == 0 => editor.field = editor.field.saturating_sub(1),
KeyCode::Right if editor.selected == 0 => editor.field = (editor.field + 1).min(3),
KeyCode::Right if editor.selected == 0 => editor.field = (editor.field + 1).min(7),
KeyCode::Left | KeyCode::Right if editor.selected == 1 => editor.regex = !editor.regex,
KeyCode::Enter if editor.selected < 2 => editor.selected += 1,
KeyCode::Enter if editor.selected == 2 => {
@ -3234,7 +3234,11 @@ impl<C: MixerClient> LiveTui<C> {
0 => fader_core::MetadataField::ApplicationName,
1 => fader_core::MetadataField::ApplicationId,
2 => fader_core::MetadataField::ProcessBinary,
_ => fader_core::MetadataField::MediaName,
3 => fader_core::MetadataField::MediaName,
4 => fader_core::MetadataField::ProcessExecutable,
5 => fader_core::MetadataField::ProcessWorkingDirectory,
6 => fader_core::MetadataField::SteamAppId,
_ => fader_core::MetadataField::SteamGameId,
};
let validated = if editor.regex {
fader_core::ApplicationSelector::regex(field, editor.pattern.clone())
@ -4011,7 +4015,11 @@ const fn selector_field_name(index: usize) -> &'static str {
0 => "application.name",
1 => "application.id",
2 => "application.process.binary",
_ => "media.name",
3 => "media.name",
4 => "application.process.executable",
5 => "application.process.working_directory",
6 => "steam.app_id",
_ => "steam.game_id",
}
}
@ -4028,6 +4036,10 @@ fn selector_field_index(field: &str) -> usize {
"application.id" => 1,
"application.process.binary" => 2,
"media.name" => 3,
"application.process.executable" => 4,
"application.process.working_directory" => 5,
"steam.app_id" => 6,
"steam.game_id" => 7,
_ => 0,
}
}