The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Setup scan stays off backend globals; audit lint and RPC fixes (#129341)
Siddharth Balyanf9102e4ca450
diff --git a/apps/desktop/src/lib/media.ts b/apps/desktop/src/lib/media.tsindex 575d0adc7c3..d7529700817 100644--- a/apps/desktop/src/lib/media.ts+++ b/apps/desktop/src/lib/media.ts@@ -426,5 +426,3 @@ export function captureGatewayFileDownload() {return (path: string, suggestedName: string) =>downloadGatewayFileWithFeedback(path, { owner: { connectionId, profile }, suggestedName })}--diff --git a/hermes_cli/setup_profile.py b/hermes_cli/setup_profile.pyindex a4f425238ef..5851157d85a 100644--- a/hermes_cli/setup_profile.py+++ b/hermes_cli/setup_profile.py@@ -130,7 +130,7 @@ def record_failed_start() -> dict:return _change_state(change)-def mark_seen() -> dict:+def mark_intro_seen() -> dict:return _change_state(lambda state: {**state, "intro": "seen"})diff --git a/optional-skills/creative/comfyui/scripts/auto_fix_deps.py b/optional-skills/creative/comfyui/scripts/auto_fix_deps.pyindex 9c6bee96a3f..d565459f2c2 100755--- a/optional-skills/creative/comfyui/scripts/auto_fix_deps.py+++ b/optional-skills/creative/comfyui/scripts/auto_fix_deps.py@@ -51,7 +51,8 @@ def run_cmd(cmd: list[str], *, dry_run: bool = False) -> tuple[int, str]:if dry_run:return 0, "[dry-run]"log(f"$ {' '.join(cmd)}")- proc = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', check=False)+ proc = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', check=False,+ stdin=subprocess.DEVNULL)out = (proc.stdout or "") + (proc.stderr or "")return proc.returncode, outdiff --git a/optional-skills/productivity/initiate-setup/scripts/host_facts.py b/optional-skills/productivity/initiate-setup/scripts/host_facts.pyindex 52cc88951c9..4495564cf06 100644--- a/optional-skills/productivity/initiate-setup/scripts/host_facts.py+++ b/optional-skills/productivity/initiate-setup/scripts/host_facts.py@@ -19,6 +19,8 @@ from __future__ import annotationsimport argparseimport contextvars+import importlib+import importlib.utilimport jsonimport osimport platform@@ -51,6 +53,9 @@ _FORK_QUESTION = "Know what you'd like it to make?"_FALLBACK_QUESTION = "What sounds better?"SCAN_DIR = Path(__file__).resolve().parent / "userscan"+# The scanner package's import name. It is private so that loading it never adds SCAN_DIR (and its+# top-level run.py) to sys.path of the backend process that runs this file.+_SCANNER = "initiate_setup_userscan"SCAN_TIER = "T1"SCAN_CACHE_MAX_AGE_S = 24 * 3600SCAN_DEADLINE_S = 11@@ -369,22 +374,35 @@ def _full_scan(run, path: Path | None) -> dict:return profile-def _scan_now() -> tuple[dict, str]:- if str(SCAN_DIR) not in sys.path:- sys.path.insert(0, str(SCAN_DIR))- import userscan.specs # noqa: F401- from userscan import __version__- from userscan.host import detect_os- from userscan.registry import REGISTRY- from userscan.runner import run+def _scanner(module: str):+ """A submodule of the scanner package, loaded once per process under ``_SCANNER``. The package+ body imports nothing, so it runs before it is registered: a thread that loses the registration+ race drops a complete copy, and the submodule imports that follow take the import lock."""+ if _SCANNER not in sys.modules:+ init = SCAN_DIR / "userscan" / "__init__.py"+ spec = importlib.util.spec_from_file_location(_SCANNER, init, submodule_search_locations=[str(init.parent)])+ package = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(package)+ sys.modules.setdefault(_SCANNER, package)+ return importlib.import_module(f"{_SCANNER}.{module}")++def _scan_now() -> tuple[dict, str]:+ _scanner("specs")+ version = sys.modules[_SCANNER].__version__+ detect_os = _scanner("host").detect_os+ registry = _scanner("registry").REGISTRY++ # The scan's children (git, ps, tmux, ...) act for the served profile, not the launch one.+ from tools.environments.local import served_profile_child_env+ run = partial(_scanner("runner").run, child_env=served_profile_child_env())home = _hermes_home()path = home / "insights" / "profile.json" if home else Nonecached = _read_json(path)- if cached and _cache_is_fresh(cached, __version__):+ if cached and _cache_is_fresh(cached, version):here = detect_os()- l1 = run(max_tier=SCAN_TIER, only=sorted({p.id for p in REGISTRY.values()- if p.level == "L1" and p.os in ("any", here)}))+ l1 = run(max_tier=SCAN_TIER, only=sorted({p.id for p in registry.values()+ if p.level == "L1" and p.os in ("any", here)}))if _l1_fired(l1) == _l1_fired(cached):return cached, "cache"if path is None:@@ -393,12 +411,12 @@ def _scan_now() -> tuple[dict, str]:# backends on the desktop, and the inline-shell hook runs this file as its own process.lease = path.with_name(f"{path.name}.scanning")seen = _started(cached) if cached else None- while (done := _published(path, seen, __version__)) is None:+ while (done := _published(path, seen, version)) is None:try:path.parent.mkdir(parents=True, exist_ok=True)fd = os.open(lease, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)except FileExistsError:- _await_lease(lease, path, seen, __version__)+ _await_lease(lease, path, seen, version)continueexcept OSError:return _full_scan(run, path), "fresh"diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/run.py b/optional-skills/productivity/initiate-setup/scripts/userscan/run.pyindex d7fd8d1a61e..0ce28dd887f 100644--- a/optional-skills/productivity/initiate-setup/scripts/userscan/run.py+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/run.py@@ -18,7 +18,9 @@ import syssys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-from userscan.runner import run, scan_accounts # noqa: E402+from userscan.cli import override_env, scan_accounts # noqa: E402+from userscan.host import collect_l0 # noqa: E402+from userscan.runner import run # noqa: E402def main(argv=None):@@ -62,9 +64,11 @@ def main(argv=None):if getattr(args, k) is not None}# The account pass runs first: its read guard is process-wide and must not overlap run()'s threads.accounts = scan_accounts(os_override=os_override, include_operator=args.include_operator) if args.all_users else None- out = run(max_tier=args.max_tier, budget_ms=args.budget_ms, allow_vss=args.allow_vss,- only=only, skip_family=list(args.skip_family or []), include_deep=args.deep,- os_override=os_override, overrides=overrides or None)+ # Probes that read os.environ directly follow the overrides only while the process env points there.+ with override_env(collect_l0("env", os_override=os_override, overrides=overrides or None)):+ out = run(max_tier=args.max_tier, budget_ms=args.budget_ms, allow_vss=args.allow_vss,+ only=only, skip_family=list(args.skip_family or []), include_deep=args.deep,+ os_override=os_override, overrides=overrides or None)if accounts is not None:out["all_users"] = accountstext = json.dumps(out, indent=2, default=str)diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/cli.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/cli.pynew file mode 100644index 00000000000..de3a3d32f82--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/cli.py@@ -0,0 +1,180 @@+"""Process-wide machinery for the standalone CLI (run.py) only: environment retargeting for --home+and friends, and the --all-users pass with its read guard. Both patch process globals (os.environ,+builtins.open, sqlite3.connect, subprocess.Popen), so an in-process caller such as a Hermes backend+must never import this module; it calls runner.run(), which touches none of them."""+from __future__ import annotations++import builtins+import contextlib+import io+import os+import time+import uuid++from .host import OVERRIDABLE, HostAccess, collect_l0, per_user_overrides+from .registry import REGISTRY+from .runner import _truthy++USER_FAMILIES = ("apps", "ai_agents", "dev", "browser", "comms_work", "files", "gaming", "media")+++class AggregateHostAccess(HostAccess):+ """HostAccess for an --all-users pass: stat/scandir/registry only. SQLite, file copies and+ subprocesses are refused so a probe cannot pull contents out of another account's home."""++ def sqlite(self, path, query, params=(), timeout_ms=1500):+ return None++ def copy_locked(self, path, dst_name=None, allow_vss=False):+ return None, "blocked"++ def run(self, args, timeout_ms=5000, text=True, env=None):+ return None++ def powershell(self, script, timeout_ms=8000):+ return None+++class _ReadGuard:+ def __init__(self, roots):+ self.roots = [os.path.normcase(os.path.realpath(r)).rstrip("\\/") for r in roots if r]+ self.blocked = 0++ def denies(self, file) -> bool:+ if isinstance(file, int):+ return False+ try:+ p = os.path.normcase(os.path.realpath(os.fspath(file)))+ except (TypeError, ValueError, OSError):+ return False+ for r in self.roots:+ if p == r or p.startswith(r + os.sep):+ self.blocked += 1+ return True+ return False+++def deny_reads_under(roots):+ """While active: open(), sqlite3.connect() and subprocess spawns fail with PermissionError for any+ path under `roots` (spawns are refused outright). stat/scandir still work, so presence probes run."""+ import sqlite3 as _sq+ import subprocess as _sp+ guard = _ReadGuard(roots)+ real_open, real_io_open, real_connect, real_popen = builtins.open, io.open, _sq.connect, _sp.Popen++ def g_open(file, *a, **kw):+ if guard.denies(file):+ raise PermissionError(f"all-users pass: content read refused: {file}")+ return real_open(file, *a, **kw)++ def g_connect(database, *a, **kw):+ target = str(database)+ if target.startswith("file:"):+ target = target[5:].split("?", 1)[0]+ if guard.denies(target):+ raise PermissionError("all-users pass: sqlite refused")+ return real_connect(database, *a, **kw)++ class g_popen(real_popen):+ def __init__(self, *a, **kw):+ self._child_created = False+ guard.blocked += 1+ raise PermissionError("all-users pass: subprocess refused")++ builtins.open = io.open = g_open+ _sq.connect = g_connect+ _sp.Popen = g_popen+ try:+ yield guard+ finally:+ builtins.open, io.open, _sq.connect, _sp.Popen = real_open, real_io_open, real_connect, real_popen+++def override_env(l0: dict):+ """Point HOME/USERPROFILE/LOCALAPPDATA/APPDATA/HERMES_HOME at the l0 values named in+ l0["overridden"] for the duration of a run, so probes that call os.path.expanduser or read+ os.environ directly follow the override. Empty value = variable unset. Restored on exit."""+ saved = {}+ try:+ for key in l0.get("overridden", ()):+ for name in OVERRIDABLE.get(key, ()):+ saved[name] = os.environ.get(name)+ v = l0.get(key) or ""+ if v:+ os.environ[name] = v+ else:+ os.environ.pop(name, None)+ yield+ finally:+ for name, v in saved.items():+ if v is None:+ os.environ.pop(name, None)+ else:+ os.environ[name] = v+++def scan_accounts(os_override: str = None, include_operator: bool = False) -> dict:+ """--all-users: one presence-only pass per login account. Per account it writes the username,+ home_present, process_count and one boolean per user-level L1 detector. Nothing else from the+ pass leaves this function: no probe values, no file names, no contents."""+ t0 = time.perf_counter()+ run_id = uuid.uuid4().hex[:12]+ base = collect_l0(run_id, os_override=os_override)+ h = HostAccess(base)+ users = h.list_users(include_operator=include_operator)+ procs = h.process_counts()+ homes = [u["home"] for u in users if u["home"]]+ me_home = os.path.normcase(os.path.realpath(base["home"]))+ detectors = sorted((p for p in REGISTRY.values()+ if p.fn and p.level == "L1" and p.family in USER_FAMILIES+ and p.os in ("any", base["os"])), key=lambda q: q.id)+ accounts, touched = [], []+ for u in users:+ s = time.perf_counter()+ home = u["home"]+ present = bool(home) and os.path.isdir(home)+ readable = present and os.access(home, os.R_OK | os.X_OK)+ is_self = present and os.path.normcase(os.path.realpath(home)) == me_home+ rec = {"user": u["user"], "home_present": present, "home_readable": readable,+ "is_invoking_user": is_self,+ "process_count": (procs.get(u["user"], 0) if procs is not None else None),+ "apps": None, "status": "ok", "detectors_run": 0, "errors": 0, "refused": 0}+ if not present:+ rec["status"] = "home_absent"+ elif not readable:+ rec["status"] = "home_unreadable"+ else:+ touched.append(u["user"])+ l0u = collect_l0(run_id, os_override=os_override, overrides=per_user_overrides(base["os"], home))+ l0u["user"] = u["user"]+ l0u["foreign_user"] = not is_self+ hu = AggregateHostAccess(l0u)+ apps, facts = {}, {}+ with override_env(l0u), deny_reads_under(homes) as guard:+ for p in detectors:+ if p.gate is not None and not _truthy(facts.get(p.gate)):+ apps[p.id] = False+ continue+ rec["detectors_run"] += 1+ try:+ v = p.fn(hu, facts)+ except Exception:+ rec["errors"] += 1+ v = None+ if _truthy(v):+ facts[p.id] = v+ apps[p.id] = _truthy(v)+ hu.cleanup()+ rec["apps"] = apps+ rec["refused"] = guard.blocked+ rec["ms"] = round((time.perf_counter() - s) * 1000, 1)+ accounts.append(rec)+ return {"os": base["os"], "os_detected": base["os_detected"], "families": list(USER_FAMILIES),+ "detectors": len(detectors),+ "process_counts_visible": procs is not None,+ "processes_other_accounts": (sum(n for u, n in procs.items() if u not in {a["user"] for a in users})+ if procs is not None else None),+ "accounts": accounts, "touched": touched,+ "ms": round((time.perf_counter() - t0) * 1000, 1)}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/host.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/host.pyindex fa9da868ae5..90b7596a458 100644--- a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/host.py+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/host.py@@ -1,9 +1,6 @@"""L0 host facts + HostAccess facade (all the primitives probes may use). No I/O at import time."""from __future__ import annotations-import builtins-import contextlib-import ioimport jsonimport osimport platform@@ -83,8 +80,9 @@ def _is_admin() -> bool:class HostAccess:"""Primitives every probe may call. `scratch()` is a per-run temp dir, removed at exit."""- def __init__(self, facts: dict):+ def __init__(self, facts: dict, child_env: dict = None):self.l0 = facts+ self._child_env = dict(child_env) if child_env is not None else Noneself.os = facts["os"]self.real_os = facts.get("os_detected", detect_os())# True when this pass targets an account other than the invoking one: HKCU is not theirs.@@ -100,6 +98,12 @@ class HostAccess:def last_via(self, v):self._via.v = v+ def child_env(self, **extra) -> dict:+ """Environment for a spawned child: the one the caller passed (a Hermes backend passes the+ served profile's clean env), else this process's. `extra` entries win."""+ base = self._child_env if self._child_env is not None else os.environ+ return {**base, **extra}+# -- paths ------------------------------------------------------def expand(self, path: str) -> str:"""~ resolves to l0 home and %VAR% to the l0 value for HOME/USERPROFILE/LOCALAPPDATA/APPDATA/@@ -237,7 +241,8 @@ class HostAccess:if rung == "vss" and not allow_vss:continuetry:- r = subprocess.run(args, capture_output=True, timeout=30)+ r = subprocess.run(args, capture_output=True, timeout=30, stdin=subprocess.DEVNULL,+ env=self.child_env())if r.returncode == 0 and os.path.exists(dst):return dst, rungexcept Exception:@@ -245,13 +250,13 @@ class HostAccess:return None, "failed"# -- powershell / subprocess -------------------------------------- def run(self, args, timeout_ms: int = 5000, text: bool = True):+ def run(self, args, timeout_ms: int = 5000, text: bool = True, env: dict | None = None):"""Run a command and return its stdout as str (decoded utf-8, errors replaced).The `text` argument is kept for backward compatibility and is ignored: every- caller wants str (regex on bytes raises TypeError)."""+ caller wants str (regex on bytes raises TypeError). `env` entries go on top of child_env()."""try:- r = subprocess.run(args, capture_output=True, timeout=timeout_ms / 1000.0,- creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ r = subprocess.run(args, capture_output=True, timeout=timeout_ms / 1000.0, stdin=subprocess.DEVNULL,+ env=self.child_env(**(env or {})), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))return (r.stdout or b"").decode("utf-8", "replace")except Exception:return None@@ -443,103 +448,6 @@ class HostAccess:pass-class AggregateHostAccess(HostAccess):- """HostAccess for an --all-users pass: stat/scandir/registry only. SQLite, file copies and- subprocesses are refused so a probe cannot pull contents out of another account's home."""-- def sqlite(self, path, query, params=(), timeout_ms=1500):- return None-- def copy_locked(self, path, dst_name=None, allow_vss=False):- return None, "blocked"-- def run(self, args, timeout_ms=5000, text=True):- return None-- def powershell(self, script, timeout_ms=8000):- return None---class _ReadGuard:- def __init__(self, roots):- self.roots = [os.path.normcase(os.path.realpath(r)).rstrip("\\/") for r in roots if r]- self.blocked = 0-- def denies(self, file) -> bool:- if isinstance(file, int):- return False- try:- p = os.path.normcase(os.path.realpath(os.fspath(file)))- except (TypeError, ValueError, OSError):- return False- for r in self.roots:- if p == r or p.startswith(r + os.sep):- self.blocked += 1- return True- return False---def deny_reads_under(roots):- """While active: open(), sqlite3.connect() and subprocess spawns fail with PermissionError for any- path under `roots` (spawns are refused outright). stat/scandir still work, so presence probes run."""- import sqlite3 as _sq- import subprocess as _sp- guard = _ReadGuard(roots)- real_open, real_io_open, real_connect, real_popen = builtins.open, io.open, _sq.connect, _sp.Popen-- def g_open(file, *a, **kw):- if guard.denies(file):- raise PermissionError(f"all-users pass: content read refused: {file}")- return real_open(file, *a, **kw)-- def g_connect(database, *a, **kw):- target = str(database)- if target.startswith("file:"):- target = target[5:].split("?", 1)[0]- if guard.denies(target):- raise PermissionError("all-users pass: sqlite refused")- return real_connect(database, *a, **kw)-- class g_popen(real_popen):- def __init__(self, *a, **kw):- self._child_created = False- guard.blocked += 1- raise PermissionError("all-users pass: subprocess refused")-- builtins.open = io.open = g_open- _sq.connect = g_connect- _sp.Popen = g_popen- try:- yield guard- finally:- builtins.open, io.open, _sq.connect, _sp.Popen = real_open, real_io_open, real_connect, real_popen---def override_env(l0: dict):- """Point HOME/USERPROFILE/LOCALAPPDATA/APPDATA/HERMES_HOME at the l0 values named in- l0["overridden"] for the duration of a run, so probes that call os.path.expanduser or read- os.environ directly follow the override. Empty value = variable unset. Restored on exit."""- saved = {}- try:- for key in l0.get("overridden", ()):- for name in OVERRIDABLE.get(key, ()):- saved[name] = os.environ.get(name)- v = l0.get(key) or ""- if v:- os.environ[name] = v- else:- os.environ.pop(name, None)- yield- finally:- for name, v in saved.items():- if v is None:- os.environ.pop(name, None)- else:- os.environ[name] = v--def per_user_overrides(os_name: str, home: str) -> dict:"""The l0 overrides that retarget a run at `home`. HERMES_HOME is cleared (the invoking user'svalue must not leak into another account's pass); probes fall back to the default location."""diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/runner.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/runner.pyindex ddc78c04c4a..5724237eada 100644--- a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/runner.py+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/runner.py@@ -8,8 +8,8 @@ import threadingimport timeimport uuid-from .host import (AggregateHostAccess, HostAccess, collect_l0, deny_reads_under, override_env,- per_user_overrides)+from . import __version__+from .host import HostAccess, collect_l0from .registry import REGISTRY, INSIGHTS, TIERS@@ -44,269 +44,223 @@ def _filter_values(out: dict, max_tier: str) -> None:f["value"] = v[:5]-USER_FAMILIES = ("apps", "ai_agents", "dev", "browser", "comms_work", "files", "gaming", "media")--def run(max_tier: str = "T1", budget_ms: int = 4000, allow_vss: bool = False,only: list = None, skip_family: list = None, include_deep: bool = False,- os_override: str = None, overrides: dict = None) -> dict:+ os_override: str = None, overrides: dict = None, child_env: dict = None) -> dict:"""One collection pass. `os_override` pretends to be another OS for probe selection;- `overrides` retargets home/localappdata/appdata/hermes_home (see host.collect_l0)."""+ `overrides` retargets home/localappdata/appdata/hermes_home as l0 data only (see host.collect_l0);+ probes that read os.environ directly follow them only under cli.override_env, which the CLI applies;+ `child_env` is the environment every spawned child gets (default: this process's)."""run_id = uuid.uuid4().hex[:12]t0 = time.perf_counter()l0 = collect_l0(run_id, allow_vss=allow_vss, os_override=os_override, overrides=overrides)- with override_env(l0):- return _run(l0, t0, max_tier, budget_ms, allow_vss, only, skip_family, include_deep)+ return _run(l0, t0, max_tier, budget_ms, allow_vss, only, skip_family, include_deep, child_env)+++def _run(l0, t0, max_tier, budget_ms, allow_vss, only, skip_family, include_deep, child_env):+ ps = _Pass(l0, HostAccess(l0, child_env), max_tier, only, skip_family, include_deep)+ ps.run_l1()+ ps.run_l2(budget_ms, allow_vss)+ insights, no_input = ps.run_l3()+ ps.h.cleanup()+ out = {+ "schema": "user-insights/1",+ "run": {"id": l0["run_id"], "max_tier": max_tier, "budget_ms": budget_ms,+ "allow_vss": allow_vss, "collector_version": __version__},+ "host": l0,+ "timing": ps.timing,+ "facts": ps.facts,+ "insights": insights,+ "coverage": {+ "detectors_total": sum(1 for p in REGISTRY.values() if ps.selected(p)),+ "fired": sum(1 for v in ps.facts.values() if v["status"] == "ok"),+ "extractors_run": sum(1 for v in ps.facts.values() if v["level"] == "L2" and v["status"] == "ok"),+ "skipped": ps.skipped,+ "errors": ps.errors,+ "insights_no_input": no_input,+ },+ }+ out["run"]["wall_ms"] = round((time.perf_counter() - t0) * 1000, 1)+ _filter_values(out, max_tier)+ return out++class _Pass:+ """State of one collection pass; each run_* method is one layer."""-def _run(l0, t0, max_tier, budget_ms, allow_vss, only, skip_family, include_deep):- run_id = l0["run_id"]- h = HostAccess(l0)- skip_family = set(skip_family or [])- only = set(only) if only else None+ def __init__(self, l0, h, max_tier, only, skip_family, include_deep):+ self.l0, self.h, self.max_tier, self.include_deep = l0, h, max_tier, include_deep+ self.skip_family = set(skip_family or [])+ self.only = set(only) if only else None+ self.facts: dict = {}+ self.timing = {}+ self.skipped: dict = {}+ self.errors: dict = {}- def selected(p):- if p.os not in ("any", l0["os"]):+ def selected(self, p):+ if p.os not in ("any", self.l0["os"]):return False- if p.family in skip_family:+ if p.family in self.skip_family:return False- if p.collect == "deep" and not include_deep:+ if p.collect == "deep" and not self.include_deep:return False- if only is not None and p.id not in only and p.family not in only:+ if self.only is not None and p.id not in self.only and p.family not in self.only:return False- if p.needs_admin and not l0["admin"]:+ if p.needs_admin and not self.l0["admin"]:return Falsereturn True- facts: dict = {}- timing = {}- skipped: dict = {}- errors: dict = {}+ def record(self, p, status, ms, value=None, via=None):+ self.facts[p.id] = {"level": p.level, "tier": p.tier, "family": p.family,+ "status": status, "ms": round(ms, 3),+ "method": (p.ps and "powershell") or (p.fn.__name__ if p.fn else "ps"),+ "via": via, "value": value if status == "ok" else None}- def record(p, status, ms, value=None, via=None):- facts[p.id] = {"level": p.level, "tier": p.tier, "family": p.family,- "status": status, "ms": round(ms, 3),- "method": (p.ps and "powershell") or (p.fn.__name__ if p.fn else "ps"),- "via": via, "value": value if status == "ok" else None}+ def gate_ok(self, p):+ return p.gate is None or _truthy(self.facts.get(p.gate, {}).get("value"))- def gate_ok(p):- return p.gate is None or _truthy(facts.get(p.gate, {}).get("value"))+ def run_l1(self):+ """L1 detectors, serially."""+ t = time.perf_counter()+ for p in sorted((q for q in REGISTRY.values() if self.selected(q) and q.level == "L1"), key=lambda q: q.id):+ if not self.gate_ok(p):+ self.record(p, "skipped_flag", 0)+ continue+ s = time.perf_counter()+ try:+ v = p.fn(self.h, self.facts) if p.fn else None+ self.record(p, "ok" if _truthy(v) else "absent", (time.perf_counter() - s) * 1000,+ v if _truthy(v) else {"present": False})+ except Exception as e:+ self.errors[p.id] = f"{type(e).__name__}: {e}"+ self.record(p, "error", (time.perf_counter() - s) * 1000)+ self.timing["l1_ms"] = round((time.perf_counter() - t) * 1000, 1)- # ---------------- L1 (serial) ----------------- t = time.perf_counter()- for p in sorted((q for q in REGISTRY.values() if selected(q) and q.level == "L1"), key=lambda q: q.id):- if not gate_ok(p):- record(p, "skipped_flag", 0)- continue- s = time.perf_counter()- try:- v = p.fn(h, facts) if p.fn else None- record(p, "ok" if _truthy(v) else "absent", (time.perf_counter() - s) * 1000, v if _truthy(v) else {"present": False})- except Exception as e:- errors[p.id] = f"{type(e).__name__}: {e}"- record(p, "error", (time.perf_counter() - s) * 1000)- timing["l1_ms"] = round((time.perf_counter() - t) * 1000, 1)+ def run_l2(self, budget_ms, allow_vss):+ """L2 extractors: batched PowerShell on a sidecar thread in parallel with the python probes."""+ ps_probes = [p for p in REGISTRY.values() if self.selected(p) and p.level == "L2" and p.ps]+ if ps_probes and self.l0.get("os_detected") != "windows":+ for p in ps_probes:+ self.record(p, "skipped_os", 0)+ self.skipped[p.id] = "skipped_os"+ ps_probes = []+ ps_holder = {}+ ps_start = time.perf_counter()- # ---------------- L2: batched PowerShell in parallel with the python probes ----------------- ps_probes = [p for p in REGISTRY.values() if selected(p) and p.level == "L2" and p.ps]- if ps_probes and l0.get("os_detected") != "windows":- for p in ps_probes:- record(p, "skipped_os", 0)- skipped[p.id] = "skipped_os"- ps_probes = []- ps_holder = {}- ps_start = time.perf_counter()+ def _ps_worker():+ ps_holder["results"] = _run_ps_batch(ps_probes, self.h, self.gate_ok, self.max_tier, allow_vss,+ self.skipped)- def _ps_worker():- ps_holder["results"] = _run_ps_batch(ps_probes, h, gate_ok, max_tier, allow_vss, skipped)+ ps_thread = threading.Thread(target=_ps_worker, daemon=True) if ps_probes else None+ if ps_thread:+ ps_thread.start()- ps_thread = threading.Thread(target=_ps_worker, daemon=True) if ps_probes else None- if ps_thread:- ps_thread.start()+ t = time.perf_counter()+ deadline = self._run_python_l2(budget_ms)+ if ps_thread:+ ps_thread.join(timeout=max(1.0, deadline - time.perf_counter() + 2.0))+ for p, status, ms, value in ps_holder.get("results", []):+ self.record(p, status, ms, value, via="ps")+ for p in ps_probes:+ if p.id not in self.facts:+ self.record(p, "timeout", 0)+ self.timing["ps_sidecar_ms"] = round((time.perf_counter() - ps_start) * 1000, 1)+ self.timing["l2_ms"] = round((time.perf_counter() - t) * 1000, 1)- # ---------------- L2: python probes on worker threads ----------------- t = time.perf_counter()- py_probes = [p for p in REGISTRY.values() if selected(p) and p.level == "L2" and not p.ps]- t_now = time.perf_counter()- deadline = t_now + budget_ms / 1000.0- lock = threading.Lock()- queue = [p for p in py_probes if gate_ok(p)]- order = sorted(queue, key=lambda q: (q.collect != "core", q.collect == "deep", q.id))+ def _run_python_l2(self, budget_ms):+ """Python L2 probes on worker threads. Returns the pass deadline."""+ h, facts, errors = self.h, self.facts, self.errors+ py_probes = [p for p in REGISTRY.values() if self.selected(p) and p.level == "L2" and not p.ps]+ t_now = time.perf_counter()+ deadline = t_now + budget_ms / 1000.0+ lock = threading.Lock()+ queue = [p for p in py_probes if self.gate_ok(p)]+ order = sorted(queue, key=lambda q: (q.collect != "core", q.collect == "deep", q.id))- # Each probe gets its own deadline: its own timeout_ms, or the remaining budget, whichever- # is larger for a deep probe (a 25 s profile walk must not be starved by a 4 s budget) and- # whichever is smaller otherwise. Nothing is force-killed; a probe past its deadline is- # recorded as "timeout" and the runner moves on.- def _probe_deadline(p):- own = p.timeout_ms / 1000.0- remaining = max(0.0, deadline - time.perf_counter())- return time.perf_counter() + (max(own, remaining) if p.collect == "deep" else min(own, remaining))+ # Each probe gets its own deadline: its own timeout_ms, or the remaining budget, whichever+ # is larger for a deep probe (a 25 s profile walk must not be starved by a 4 s budget) and+ # whichever is smaller otherwise. Nothing is force-killed; a probe past its deadline is+ # recorded as "timeout" and the runner moves on.+ def _probe_deadline(p):+ own = p.timeout_ms / 1000.0+ remaining = max(0.0, deadline - time.perf_counter())+ return time.perf_counter() + (max(own, remaining) if p.collect == "deep" else min(own, remaining))- join_deadline = max([_probe_deadline(p) for p in order] or [deadline])- idx = [0]+ join_deadline = max([_probe_deadline(p) for p in order] or [deadline])+ idx = [0]- def worker():- while True:- with lock:- i = idx[0]- if i >= len(order):- return- idx[0] = i + 1- p = order[i]- if time.perf_counter() > deadline and p.collect != "deep":- record(p, "skipped_budget", 0)- continue- s = time.perf_counter()- try:- v = p.fn(h, facts)- record(p, "ok" if _truthy(v) else "absent", (time.perf_counter() - s) * 1000, v if _truthy(v) else {"present": False}, via=h.last_via if hasattr(h, "last_via") else "live")- except Exception as e:+ def worker():+ while True:with lock:- errors[p.id] = f"{type(e).__name__}: {e}"- record(p, "error", (time.perf_counter() - s) * 1000)+ i = idx[0]+ if i >= len(order):+ return+ idx[0] = i + 1+ p = order[i]+ if time.perf_counter() > deadline and p.collect != "deep":+ self.record(p, "skipped_budget", 0)+ continue+ s = time.perf_counter()+ try:+ v = p.fn(h, facts)+ self.record(p, "ok" if _truthy(v) else "absent", (time.perf_counter() - s) * 1000,+ v if _truthy(v) else {"present": False},+ via=h.last_via if hasattr(h, "last_via") else "live")+ except Exception as e:+ with lock:+ errors[p.id] = f"{type(e).__name__}: {e}"+ self.record(p, "error", (time.perf_counter() - s) * 1000)- workers = [threading.Thread(target=worker, daemon=True) for _ in range(min(8, (os.cpu_count() or 4)))]- for w in workers:- w.start()- for w in workers:- w.join(timeout=max(0.5, join_deadline - time.perf_counter() + 1.0))- for p in order:- if p.id not in facts:- record(p, "timeout", 0)- if ps_thread:- ps_thread.join(timeout=max(1.0, deadline - time.perf_counter() + 2.0))- for p, status, ms, value in ps_holder.get("results", []):- record(p, status, ms, value, via="ps")- for p in ps_probes:+ workers = [threading.Thread(target=worker, daemon=True) for _ in range(min(8, (os.cpu_count() or 4)))]+ for w in workers:+ w.start()+ for w in workers:+ w.join(timeout=max(0.5, join_deadline - time.perf_counter() + 1.0))+ for p in order:if p.id not in facts:- record(p, "timeout", 0)- timing["ps_sidecar_ms"] = round((time.perf_counter() - ps_start) * 1000, 1)- timing["l2_ms"] = round((time.perf_counter() - t) * 1000, 1)+ self.record(p, "timeout", 0)+ return deadline- # ---------------- L3 ----------------- t = time.perf_counter()- cap = TIERS.index(max_tier)- # Rules see only the facts the reader will see. A rule fed a hidden T2 fact would echo it in- # its claim, which is exactly how persona.comms_surface leaked T2 detail into a T1 run.- ok_facts = {k: v["value"] for k, v in facts.items()- if v["status"] == "ok" and TIERS.index(v.get("tier", "T0")) <= cap}- # An input is answered when its probe was selected on this OS and finished (ok, absent, or gated off).- # Rules that return a claim from absence ("no notes app") need at least one answered input; otherwise- # the claim would rest on a probe that does not exist for this OS or that errored/timed out.- selected_ids = {p.id for p in REGISTRY.values() if selected(p)}- unanswered = {k for k, v in facts.items() if v["status"] in ("error", "timeout", "skipped_budget", "skipped_os")}- no_input = []- insights = []- for ins in INSIGHTS.values():- if only is not None and ins.id not in only:- continue- if not any(i in selected_ids and i not in unanswered for i in ins.inputs):- no_input.append(ins.id)- continue- try:- got = ins.fn(ok_facts)- except Exception as e:- errors[ins.id] = f"{type(e).__name__}: {e}"- continue- if not got:- continue- missing = [i for i in ins.inputs if i not in ok_facts]- insights.append({- "id": ins.id,- "claim": got.get("claim", ""),- "strength": got.get("strength", "weak"),- "confidence": "partial" if missing else "full",- "evidence": [i for i in ins.inputs if i in ok_facts],- "value": got.get("value"),- })- timing["l3_ms"] = round((time.perf_counter() - t) * 1000, 1)-- h.cleanup()- out = {- "schema": "user-insights/1",- "run": {"id": run_id, "max_tier": max_tier, "budget_ms": budget_ms,- "allow_vss": allow_vss, "collector_version": __import__("userscan").__version__},- "host": l0,- "timing": timing,- "facts": facts,- "insights": insights,- "coverage": {- "detectors_total": sum(1 for p in REGISTRY.values() if selected(p)),- "fired": sum(1 for v in facts.values() if v["status"] == "ok"),- "extractors_run": sum(1 for v in facts.values() if v["level"] == "L2" and v["status"] == "ok"),- "skipped": skipped,- "errors": errors,- "insights_no_input": no_input,- },- }- out["run"]["wall_ms"] = round((time.perf_counter() - t0) * 1000, 1)- _filter_values(out, max_tier)- return out---def scan_accounts(os_override: str = None, include_operator: bool = False) -> dict:- """--all-users: one presence-only pass per login account. Per account it writes the username,- home_present, process_count and one boolean per user-level L1 detector. Nothing else from the- pass leaves this function: no probe values, no file names, no contents."""- t0 = time.perf_counter()- run_id = uuid.uuid4().hex[:12]- base = collect_l0(run_id, os_override=os_override)- h = HostAccess(base)- users = h.list_users(include_operator=include_operator)- procs = h.process_counts()- homes = [u["home"] for u in users if u["home"]]- me_home = os.path.normcase(os.path.realpath(base["home"]))- detectors = sorted((p for p in REGISTRY.values()- if p.fn and p.level == "L1" and p.family in USER_FAMILIES- and p.os in ("any", base["os"])), key=lambda q: q.id)- accounts, touched = [], []- for u in users:- s = time.perf_counter()- home = u["home"]- present = bool(home) and os.path.isdir(home)- readable = present and os.access(home, os.R_OK | os.X_OK)- is_self = present and os.path.normcase(os.path.realpath(home)) == me_home- rec = {"user": u["user"], "home_present": present, "home_readable": readable,- "is_invoking_user": is_self,- "process_count": (procs.get(u["user"], 0) if procs is not None else None),- "apps": None, "status": "ok", "detectors_run": 0, "errors": 0, "refused": 0}- if not present:- rec["status"] = "home_absent"- elif not readable:- rec["status"] = "home_unreadable"- else:- touched.append(u["user"])- l0u = collect_l0(run_id, os_override=os_override, overrides=per_user_overrides(base["os"], home))- l0u["user"] = u["user"]- l0u["foreign_user"] = not is_self- hu = AggregateHostAccess(l0u)- apps, facts = {}, {}- with override_env(l0u), deny_reads_under(homes) as guard:- for p in detectors:- if p.gate is not None and not _truthy(facts.get(p.gate)):- apps[p.id] = False- continue- rec["detectors_run"] += 1- try:- v = p.fn(hu, facts)- except Exception:- rec["errors"] += 1- v = None- if _truthy(v):- facts[p.id] = v- apps[p.id] = _truthy(v)- hu.cleanup()- rec["apps"] = apps- rec["refused"] = guard.blocked- rec["ms"] = round((time.perf_counter() - s) * 1000, 1)- accounts.append(rec)- return {"os": base["os"], "os_detected": base["os_detected"], "families": list(USER_FAMILIES),- "detectors": len(detectors),- "process_counts_visible": procs is not None,- "processes_other_accounts": (sum(n for u, n in procs.items() if u not in {a["user"] for a in users})- if procs is not None else None),- "accounts": accounts, "touched": touched,- "ms": round((time.perf_counter() - t0) * 1000, 1)}+ def run_l3(self):+ """L3 insights over the facts the reader will see. Returns (insights, ids with no input)."""+ t = time.perf_counter()+ cap = TIERS.index(self.max_tier)+ # Rules see only the facts the reader will see. A rule fed a hidden T2 fact would echo it in+ # its claim, which is exactly how persona.comms_surface leaked T2 detail into a T1 run.+ ok_facts = {k: v["value"] for k, v in self.facts.items()+ if v["status"] == "ok" and TIERS.index(v.get("tier", "T0")) <= cap}+ # An input is answered when its probe was selected on this OS and finished (ok, absent, or gated off).+ # Rules that return a claim from absence ("no notes app") need at least one answered input; otherwise+ # the claim would rest on a probe that does not exist for this OS or that errored/timed out.+ selected_ids = {p.id for p in REGISTRY.values() if self.selected(p)}+ unanswered = {k for k, v in self.facts.items()+ if v["status"] in ("error", "timeout", "skipped_budget", "skipped_os")}+ no_input = []+ insights = []+ for ins in INSIGHTS.values():+ if self.only is not None and ins.id not in self.only:+ continue+ if not any(i in selected_ids and i not in unanswered for i in ins.inputs):+ no_input.append(ins.id)+ continue+ try:+ got = ins.fn(ok_facts)+ except Exception as e:+ self.errors[ins.id] = f"{type(e).__name__}: {e}"+ continue+ if not got:+ continue+ missing = [i for i in ins.inputs if i not in ok_facts]+ insights.append({+ "id": ins.id,+ "claim": got.get("claim", ""),+ "strength": got.get("strength", "weak"),+ "confidence": "partial" if missing else "full",+ "evidence": [i for i in ins.inputs if i in ok_facts],+ "value": got.get("value"),+ })+ self.timing["l3_ms"] = round((time.perf_counter() - t) * 1000, 1)+ return insights, no_inputdef _run_ps_batch(probes, h, gate_ok, max_tier, allow_vss, skipped):@@ -334,7 +288,7 @@ def _run_ps_batch(probes, h, gate_ok, max_tier, allow_vss, skipped):with open(path, "w", encoding="utf-8-sig") as fh:fh.write(script)r = subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", path],- capture_output=True, timeout=120,+ capture_output=True, timeout=120, stdin=subprocess.DEVNULL, env=h.child_env(),creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))raw = (r.stdout or b"").decode("utf-8", "replace")data = json.loads(raw) if raw.strip() else []diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/__init__.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/__init__.pyindex a67a2964465..bdc79b678a8 100644--- a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/__init__.py+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/__init__.py@@ -4,24 +4,35 @@ from __future__ import annotationsimport importlib_MODULES = [- "userscan.specs.host_identity", # L0-ish identity + install age + locale + shell prefs- # (+ security, network, hardware, health, usage on Windows)- "userscan.specs.apps_dev", # installed software, AI agents, dev environment- "userscan.specs.browser_files", # browsers, files and content- "userscan.specs.usage_gaming", # usage habits, gaming, media, hardware health- "userscan.specs.derive", # L3 insights (persona, fresh-vs-old)- "userscan.specs.linux_system", # Linux: host, identity, install_age, locale, shell_prefs,- # security, network, hardware, health, usage- "userscan.specs.linux_apps", # Linux: apps, ai_agents, dev, browser, comms_work, files,- # gaming, media- "userscan.specs.darwin_system", # macOS: host, identity, install_age, locale, shell_prefs,- # security, network, hardware, health, usage- "userscan.specs.darwin_apps", # macOS: apps, ai_agents, dev, browser, comms_work, files,- # gaming, media+ ".host_identity", # L0-ish identity + install age + locale + shell prefs+ # (+ security, network, hardware, health, usage on Windows)+ ".apps_dev", # installed software (+ shared inventories)+ ".apps_dev_agents", # AI agents+ ".apps_dev_devenv", # dev environment+ ".browser_files", # browsers+ ".browser_files_comms", # comms and work+ ".browser_files_content", # files and content+ ".usage_gaming", # usage habits+ ".usage_gaming_games", # gaming, media+ ".usage_gaming_hardware", # hardware health+ ".derive", # L3 insights (persona, fresh-vs-old)+ ".linux_system", # Linux: host, identity, install_age, locale, shell_prefs, health, usage+ ".linux_system_security", # Linux: security, network+ ".linux_system_hardware", # Linux: hardware+ ".linux_apps", # Linux: apps, ai_agents+ ".linux_apps_dev", # Linux: dev+ ".linux_apps_browser", # Linux: browser, comms_work+ ".linux_apps_files", # Linux: files, gaming, media+ ".darwin_system", # macOS: host, identity, install_age, locale, shell_prefs,+ # security, network, hardware, health, usage+ ".darwin_apps", # macOS: apps, ai_agents+ ".darwin_apps_dev", # macOS: dev+ ".darwin_apps_browser", # macOS: browser, comms_work+ ".darwin_apps_files", # macOS: files, gaming, media]for m in _MODULES:try:- importlib.import_module(m)+ importlib.import_module(m, __name__)except ImportError:passdiff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/apps_dev.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/apps_dev.pyindex 452ba156eb8..d1b2547c862 100644--- a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/apps_dev.py+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/apps_dev.py@@ -1,4 +1,4 @@-"""Installed software (apps), AI agents (ai_agents) and dev environment (dev) probes.+"""Installed software (apps) probes, plus the helpers apps_dev_agents and apps_dev_devenv share.Registration only at import time. Shared reads (uninstall keys, appx repository, process snapshot,Claude/Codex/Hermes stores) are memoised per run so several probes can reuse one read.@@ -7,7 +7,6 @@ from __future__ import annotationsimport collectionsimport datetime as dt-import globimport jsonimport osimport re@@ -17,7 +16,7 @@ import sysimport threadingimport time-from userscan.registry import probe+from ..registry import probetry:import winreg # noqa: F401@@ -270,14 +269,14 @@ def _which(name):return None-def _spawn(args, timeout=8.0, env=None):- """(rc, stdout, ms). Never used with bash.exe or pwsh."""+def _spawn(h, args, timeout=8.0, env=None):+ """(rc, stdout, ms). Never used with bash.exe or pwsh. `env` defaults to h.child_env()."""exe = args[0]if exe.lower().endswith((".cmd", ".bat")):args = ["cmd.exe", "/d", "/c"] + argst = time.perf_counter()try:- r = subprocess.run(args, capture_output=True, timeout=timeout, env=env, creationflags=NOWIN,+ r = subprocess.run(args, capture_output=True, timeout=timeout, env=env or h.child_env(), creationflags=NOWIN,stdin=subprocess.DEVNULL)out = (r.stdout or b"") or (r.stderr or b"")txt = out.decode("utf-8", "replace")@@ -1108,7 +1107,7 @@ def apps_winget_cli(h, facts):exe = _which("winget")if not exe:return None- rc, txt, ms = _spawn([exe, "list", "--disable-interactivity", "--accept-source-agreements"], timeout=40)+ rc, txt, ms = _spawn(h, [exe, "list", "--disable-interactivity", "--accept-source-agreements"], timeout=40)lines = [l for l in txt.splitlines() if l.strip()]hdr = next((i for i, l in enumerate(lines) if l.startswith("Name") and "Id" in l), None)if hdr is None:@@ -1119,1577 +1118,3 @@ def apps_winget_cli(h, facts):s = l[col:].strip() if col > 0 and len(l) > col else ""by[s or "(none)"] += 1return {"present": True, "rows": sum(by.values()), "by_source": dict(by), "ms": ms}---# ================================================================== ai_agents--def _detect(paths):- return [p for p in paths if p and os.path.exists(p)]---@probe(id="ai.catalog_absent_checks", level="L1", family=AI, tier="T0", collect="core")-def ai_catalog_absent_checks(h, facts):- """Path stats for AI tools the user may lack (Cursor, Windsurf, Gemini CLI, opencode, aider, LM Studio...)."""- U, LA, RA = _U(h), _LA(h), _RA(h)- npm = os.path.join(RA, "npm", "node_modules")- cat = {- "cursor": [os.path.join(U, ".cursor"), os.path.join(RA, "Cursor"), os.path.join(LA, "Programs", "cursor")],- "windsurf": [os.path.join(U, ".codeium"), os.path.join(U, ".windsurf"), os.path.join(RA, "Windsurf"),- os.path.join(LA, "Programs", "Windsurf")],- "gemini_cli": [os.path.join(U, ".gemini"), os.path.join(npm, "@google", "gemini-cli")],- "opencode": [os.path.join(U, ".local", "share", "opencode"), os.path.join(U, ".config", "opencode"),- os.path.join(npm, "opencode-ai")],- "aider": [os.path.join(U, ".aider.conf.yml"), os.path.join(U, ".aider"), os.path.join(U, ".aider.chat.history.md")],- "continue": [os.path.join(U, ".continue")],- "cline": [os.path.join(U, ".cline"), os.path.join(U, "Documents", "Cline")],- "chatgpt_desktop": [os.path.join(LA, "Programs", "ChatGPT"), os.path.join(RA, "ChatGPT")],- "lm_studio": [os.path.join(U, ".lmstudio"), os.path.join(U, ".cache", "lm-studio"), os.path.join(RA, "LM Studio"),- os.path.join(LA, "Programs", "LM Studio")],- "jan": [os.path.join(RA, "Jan"), os.path.join(U, "jan")],- "gpt4all": [os.path.join(LA, "nomic.ai")],- "msty": [os.path.join(RA, "Msty")],- "anythingllm": [os.path.join(RA, "anythingllm-desktop")],- "hf_hub": [os.path.join(U, ".cache", "huggingface", "hub")],- }- found = {k: len(_detect(v)) > 0 for k, v in cat.items()}- if _appx_match(h, r"^OpenAI\.ChatGPT"):- found["chatgpt_desktop"] = True- hf = os.path.join(U, ".cache", "huggingface", "hub")- hf_models = sum(1 for n in (_ls(hf) or []) if n.startswith("models--"))- return {"present": True, "found": sorted(k for k, v in found.items() if v),- "absent": sorted(k for k, v in found.items() if not v), "hf_hub_models": hf_models}---@probe(id="browser.automation", level="L1", family=AI, tier="T0", collect="core")-def browser_automation(h, facts):- """Browser-automation runtimes on disk: Playwright, camoufox, agent-browser, puppeteer."""- U, LA, RA = _U(h), _LA(h), _RA(h)- out = {}- for label, p in [("playwright", os.path.join(LA, "ms-playwright")), ("playwright_cache", os.path.join(U, ".cache", "ms-playwright")),- ("puppeteer", os.path.join(U, ".cache", "puppeteer")), ("camoufox", os.path.join(LA, "camoufox")),- ("agent_browser_browsers", os.path.join(U, ".agent-browser", "browsers"))]:- names = _ls(p, 50)- if names is not None:- out[label] = {"entries": sorted(names)[:20], "mtime": _mtime(p)}- installs = []- for loc in ([os.path.join(LA, "hermes", "node", "node_modules", "agent-browser"),- os.path.join(RA, "npm", "node_modules", "agent-browser")]):- pj = _read_json(os.path.join(loc, "package.json"))- if isinstance(pj, dict):- installs.append({"where": "hermes_bundled" if "hermes" in loc.lower() else "npm_global",- "version": pj.get("version")})- if installs:- out["agent_browser"] = installs- return {"present": bool(out), **out}---@probe(id="browser_harness.present", level="L1", family=AI, tier="T0", collect="core")-def browser_harness_present(h, facts):- """browser-harness config dir and runtime session pid-file count."""- bh = os.path.join(_U(h), ".config", "browser-harness")- if not _isdir(bh):- return None- pids = glob.glob(os.path.join(bh, "runtime", "*.pid"))- return {"present": True, "runtime_sessions": len(pids[:500]), "mtime": _mtime(bh)}---# ---------------- Claude Code--def _claude_json(h):- """Whitelisted view of ~/.claude.json. Secret-bearing keys are reduced to booleans immediately."""- def build():- cj = _read_json(os.path.join(_U(h), ".claude.json"), maxb=20_000_000)- if not isinstance(cj, dict):- return None- projects = cj.get("projects") or {}- out = {"numStartups": cj.get("numStartups"), "installMethod": cj.get("installMethod"),- "firstStartTime": _iso(cj.get("firstStartTime")), "autoUpdates": cj.get("autoUpdates"),- "hasCompletedOnboarding": cj.get("hasCompletedOnboarding"),- "project_count": len(projects) if isinstance(projects, dict) else 0,- "global_mcp_servers": sorted((cj.get("mcpServers") or {}).keys()),- "project_mcp_servers": sorted({n for v in (projects.values() if isinstance(projects, dict) else [])- if isinstance(v, dict) for n in (v.get("mcpServers") or {}).keys()}),- "has_oauth_account": "oauthAccount" in cj, "has_primary_api_key": "primaryApiKey" in cj}- del cj- return out- return _memo(h, "claude_json", build)---@probe(id="claude_code.present", level="L1", family=AI, tier="T0", collect="core")-def claude_code_present(h, facts):- """Claude Code CLI: ~/.claude home and native claude.exe (with file version)."""- U = _U(h)- home = os.path.join(U, ".claude")- exe = os.path.join(U, ".local", "bin", "claude.exe")- npm = os.path.join(_RA(h), "npm", "node_modules", "@anthropic-ai", "claude-code")- if not (_isdir(home) or os.path.exists(exe) or _isdir(npm)):- return None- vers = _ls(os.path.join(U, ".local", "share", "claude", "versions")) or []- return {"present": True, "home": _isdir(home), "native_exe": os.path.exists(exe),- "exe_version": _file_version(exe), "npm_install": _isdir(npm), "installed_versions": len(vers),- "home_mtime": _mtime(home)}---@probe(id="claude_code.config", level="L2", family=AI, tier="T0", collect="core", gate="claude_code.present")-def claude_code_config(h, facts):- """Claude Code settings (whitelisted keys), permission rule counts, skills/commands/agents/plugins."""- home = os.path.join(_U(h), ".claude")- if not _isdir(home):- return None- s = _read_json(os.path.join(home, "settings.json")) or {}- sl = _read_json(os.path.join(home, "settings.local.json")) or {}- km = _read_json(os.path.join(home, "plugins", "known_marketplaces.json")) or {}- ip = _read_json(os.path.join(home, "plugins", "installed_plugins.json")) or {}- plugins = (ip.get("plugins") if isinstance(ip.get("plugins"), dict) else ip) if isinstance(ip, dict) else {}- return {"present": True, "settings_keys": sorted(s.keys()) if isinstance(s, dict) else [],- "settings": {k: s.get(k) for k in ("model", "autoUpdatesChannel", "theme", "outputStyle")- if isinstance(s, dict) and isinstance(s.get(k), (str, bool, int))},- "hooks_events": sorted((s.get("hooks") or {}).keys()) if isinstance(s, dict) else [],- "allow_rules": len(((s.get("permissions") or {}).get("allow") or [])) + len(((sl.get("permissions") or {}).get("allow") or [])),- "skills": len(glob.glob(os.path.join(home, "skills", "*", "SKILL.md"))),- "commands": len(glob.glob(os.path.join(home, "commands", "*.md"))),- "agents": len(glob.glob(os.path.join(home, "agents", "*.md"))),- "plugin_marketplaces": sorted(km.keys()) if isinstance(km, dict) else [],- "installed_plugins": sorted(plugins.keys())[:30] if isinstance(plugins, dict) else [],- "claude_md": os.path.exists(os.path.join(home, "CLAUDE.md"))}---@probe(id="claude_code.claude_json", level="L2", family=AI, tier="T1", collect="core", gate="claude_code.present")-def claude_code_claude_json(h, facts):- """~/.claude.json whitelist: numStartups, installMethod, firstStartTime, MCP names; secrets as booleans."""- cj = _claude_json(h)- if not cj:- return None- return {"present": True, **cj}---def _cc_scan(h):- def build():- pdir = os.path.join(_U(h), ".claude", "projects")- r = {"projects": 0, "sessions": 0, "sessions_30d": 0, "bytes": 0, "user_msgs": 0, "assistant_msgs": 0,- "skipped_large": 0}- cutoff = (dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=30)).strftime("%Y-%m-%d")- models, entry, versions, days = collections.Counter(), collections.Counter(), collections.Counter(), set()- first = last = None- titles = []- files_seen = 0- for pd in sorted(glob.glob(os.path.join(pdir, "*")))[:500]:- files = glob.glob(os.path.join(pd, "*.jsonl"))- if not files:- continue- r["projects"] += 1- for f in files:- files_seen += 1- if files_seen > 5000:- break- r["sessions"] += 1- try:- sz = os.path.getsize(f)- except OSError:- continue- r["bytes"] += sz- if sz > 60_000_000:- r["skipped_large"] += 1- continue- title = None- flast = None- with open(f, encoding="utf-8", errors="replace") as fh:- for n, line in enumerate(fh):- if n > 200_000:- break- try:- j = json.loads(line)- except ValueError:- continue- if not isinstance(j, dict):- continue- t = j.get("type")- ts = j.get("timestamp")- if isinstance(ts, str):- flast = ts if flast is None or ts > flast else flast- first = ts if first is None or ts < first else first- last = ts if last is None or ts > last else last- days.add(ts[:10])- if j.get("entrypoint"):- entry[j["entrypoint"]] += 1- if j.get("version"):- versions[j["version"]] += 1- if t == "user" and not j.get("isMeta") and not j.get("toolUseResult"):- r["user_msgs"] += 1- elif t == "assistant":- r["assistant_msgs"] += 1- m = (j.get("message") or {}).get("model") if isinstance(j.get("message"), dict) else None- if m:- models[m] += 1- elif t == "custom-title" and j.get("customTitle"):- title = j["customTitle"]- elif t == "ai-title" and j.get("aiTitle") and not title:- title = j["aiTitle"]- elif t == "summary" and j.get("summary") and not title:- title = j["summary"]- if flast and flast[:10] >= cutoff:- r["sessions_30d"] += 1- if title:- titles.append((os.path.getmtime(f), title))- hist = os.path.join(_U(h), ".claude", "history.jsonl")- hinfo = None- if os.path.exists(hist) and os.path.getsize(hist) < 50_000_000:- hts = []- with open(hist, encoding="utf-8", errors="replace") as fh:- for line in fh:- try:- v = json.loads(line).get("timestamp")- except (ValueError, AttributeError):- continue- if v:- hts.append(v)- hinfo = {"entries": len(hts), "first": _iso(min(hts)) if hts else None, "last": _iso(max(hts)) if hts else None}- r.update({"first": _iso(first), "last": _iso(last), "active_days": len(days), "models": _top(models),- "entrypoints": _top(entry), "cli_versions": _top(versions, 5), "prompt_history": hinfo})- return {"agg": r, "titles": [t for _, t in sorted(titles, reverse=True)]}- return _memo(h, "cc_scan", build)---@probe(id="claude_code.sessions", level="L2", family=AI, tier="T1", collect="extended", gate="claude_code.present",- timeout_ms=5000)-def claude_code_sessions(h, facts):- """Claude Code JSONL aggregates: session/message counts, date range, active days, models, entrypoints."""- if not _isdir(os.path.join(_U(h), ".claude", "projects")):- return None- agg = _cc_scan(h)["agg"]- return {"present": agg["sessions"] > 0, **agg}---@probe(id="claude_code.titles", level="L2", family=AI, tier="T2", collect="deep", gate="claude_code.present")-def claude_code_titles(h, facts):- """Most recent Claude Code session titles (redacted, truncated). T2 content, opt-in."""- if not _isdir(os.path.join(_U(h), ".claude", "projects")):- return None- t = _cc_scan(h)["titles"]- return {"present": bool(t), "count_with_title": len(t), "recent": [_redact(x) for x in t[:5]]}---@probe(id="claude_desktop.present", level="L1", family=AI, tier="T0", collect="core")-def claude_desktop_present(h, facts):- """Claude desktop app: installed now, or evidence of a past install (Claude-3p dir)."""- LA, RA = _LA(h), _RA(h)- uninst = [i["version"] for i in _uninst_match(h, r"^Claude\b")]- appx = _appx_match(h, r"Claude|Anthropic")- dirs = {"roaming_Claude": _isdir(os.path.join(RA, "Claude")),- "local_AnthropicClaude": _isdir(os.path.join(LA, "AnthropicClaude")),- "local_Claude-3p": _isdir(os.path.join(LA, "Claude-3p")),- "programdata_Claude": _isdir(os.path.join(_PD(), "Claude"))}- installed = bool(uninst or appx or dirs["local_AnthropicClaude"] or dirs["roaming_Claude"])- cfg = _read_json(os.path.join(RA, "Claude", "claude_desktop_config.json"))- mcp = sorted((cfg.get("mcpServers") or {}).keys()) if isinstance(cfg, dict) else []- past = dirs["local_Claude-3p"] or dirs["programdata_Claude"]- if not (installed or past):- return None- return {"present": True, "installed": installed, "past_install_evidence": bool(past and not installed),- "uninstall_versions": uninst, "appx": [f"{p['name']} {p['version']}" for p in appx],- "dirs": dirs, "mcp_servers": mcp, "claude_3p_mtime": _mtime(os.path.join(LA, "Claude-3p"))}---# ---------------- Codex--def _codex_home(h):- return os.environ.get("CODEX_HOME") or os.path.join(_U(h), ".codex")---@probe(id="codex.present", level="L1", family=AI, tier="T0", collect="core")-def codex_present(h, facts):- """OpenAI Codex: ~/.codex home and Codex Desktop MSIX (appx repository)."""- home = _codex_home(h)- appx = _appx_match(h, r"^OpenAI\.Codex")- bindir = os.path.join(_LA(h), "OpenAI", "Codex", "bin")- npm = _isdir(os.path.join(_RA(h), "npm", "node_modules", "@openai", "codex"))- if not (_isdir(home) or appx or npm):- return None- return {"present": True, "home": _isdir(home), "desktop_appx": [{"version": p["version"], "arch": p["arch"]} for p in appx],- "bundled_cli_builds": len(_ls(bindir) or []), "npm_cli": npm, "home_mtime": _mtime(home)}---@probe(id="codex.auth_presence", level="L1", family=AI, tier="T3", collect="core")-def codex_auth_presence(h, facts):- """Codex auth.json presence/size/mtime (never opened). Presence means signed in."""- return h.meta(os.path.join(_codex_home(h), "auth.json"))---@probe(id="codex.config", level="L2", family=AI, tier="T0", collect="core", gate="codex.present")-def codex_config(h, facts):- """Codex config.toml whitelist: model, provider, sandbox, MCP/plugin names. MCP env tables excluded."""- p = os.path.join(_codex_home(h), "config.toml")- if not os.path.exists(p) or tomllib is None:- return None- try:- with open(p, "rb") as f:- c = tomllib.load(f)- except Exception as e:- return {"present": True, "error": type(e).__name__}- return {"present": True, "model": c.get("model"), "model_provider": c.get("model_provider"),- "model_reasoning_effort": c.get("model_reasoning_effort"), "approval_policy": c.get("approval_policy"),- "sandbox_mode": c.get("sandbox_mode"), "windows_sandbox": (c.get("windows") or {}).get("sandbox"),- "profiles": sorted((c.get("profiles") or {}).keys()),- "model_providers": sorted((c.get("model_providers") or {}).keys()),- "mcp_servers": sorted((c.get("mcp_servers") or {}).keys()),- "plugins_enabled": sorted(k for k, v in (c.get("plugins") or {}).items() if isinstance(v, dict) and v.get("enabled")),- "trusted_projects": len(c.get("projects") or {})}---@probe(id="codex.usage", level="L2", family=AI, tier="T1", collect="extended", gate="codex.present", timeout_ms=5000)-def codex_usage(h, facts):- """Codex rollouts (count/bytes/date range/turn models) + state_*.sqlite thread counts + turn durations."""- home = _codex_home(h)- if not _isdir(home):- return None- files = sorted(glob.glob(os.path.join(home, "sessions", "*", "*", "*", "rollout-*.jsonl")) +- glob.glob(os.path.join(home, "archived_sessions", "*.jsonl")))[:3000]- models, efforts, orig, clis = (collections.Counter() for _ in range(4))- dates, b, turns = [], 0, 0- for f in files:- try:- b += os.path.getsize(f)- except OSError:- continue- m = re.search(r"rollout-(\d{4}-\d\d-\d\dT\d\d-\d\d-\d\d)", f)- if m:- dates.append(m.group(1))- if os.path.getsize(f) > 80_000_000:- continue- with open(f, encoding="utf-8", errors="replace") as fh:- for i, line in enumerate(fh):- head = line[:120]- if i == 0 and '"session_meta"' in head:- try:- p = json.loads(line)["payload"]- orig[p.get("originator")] += 1; clis[p.get("cli_version")] += 1- except Exception:- pass- elif '"turn_context"' in head:- turns += 1- try:- p = json.loads(line)["payload"]- models[p.get("model")] += 1- efforts[p.get("effort") or p.get("reasoning_effort")] += 1- except Exception:- pass- dates.sort()- cutoff = (dt.datetime.now() - dt.timedelta(days=30)).strftime("%Y-%m-%d")- out = {"present": True, "sessions_30d": sum(1 for d in dates if d[:10] >= cutoff),- "rollouts": {"files": len(files), "bytes": b, "first": dates[0] if dates else None,- "last": dates[-1] if dates else None, "turn_contexts": turns, "models": _top(models),- "efforts": _top(efforts), "originators": _top(orig), "cli_versions": _top(clis, 5)}}- sdb = sorted(glob.glob(os.path.join(home, "state_*.sqlite")), key=lambda p: int(re.search(r"(\d+)", os.path.basename(p)).group(1)))- if sdb:- dst = _copy_db(h, sdb[-1], "codex-state")- if dst:- try:- cs = _cols(dst, "threads")- by_src = collections.Counter()- for (s,) in _q(dst, "select source from threads"):- if isinstance(s, str) and s.startswith("{"):- try:- s = "subagent" if "subagent" in s.lower() else next(iter(json.loads(s)))- except Exception:- s = "object"- by_src[s] += 1- a, z = _q(dst, "select min(created_at), max(updated_at) from threads")[0]- out["threads"] = {"count": sum(by_src.values()), "first": _iso(a), "last": _iso(z), "by_source": dict(by_src),- "by_provider": dict(_q(dst, "select model_provider, count(*) from threads group by 1")) if "model_provider" in cs else None,- "by_model": dict(_q(dst, "select model, count(*) from threads group by 1")) if "model" in cs else None,- "tokens_used_total": _q(dst, "select sum(tokens_used) from threads")[0][0] if "tokens_used" in cs else None}- try:- out["threads"]["subagent_edges"] = _q(dst, "select count(*) from thread_spawn_edges")[0][0]- except Exception:- pass- except Exception as e:- out["threads"] = {"error": type(e).__name__}- finally:- _rmdb(dst)- th = sorted(glob.glob(os.path.join(home, "thread_history_*.sqlite")))- if th:- dst = _copy_db(h, th[-1], "codex-th")- if dst:- try:- out["turns"] = {"count": _q(dst, "select count(*) from thread_turns")[0][0],- "agent_minutes": round((_q(dst, "select sum(duration_ms) from thread_turns")[0][0] or 0) / 60000, 1),- "items": _q(dst, "select count(*) from thread_items")[0][0]}- except Exception as e:- out["turns"] = {"error": type(e).__name__}- finally:- _rmdb(dst)- return out---@probe(id="codex.extras", level="L2", family=AI, tier="T1", collect="extended", gate="codex.present")-def codex_extras(h, facts):- """Codex skill/plugin counts, dictation-session count, logs db row count and range."""- home = _codex_home(h)- if not _isdir(home):- return None- sk = os.path.join(home, "skills")- pc = os.path.join(home, "plugins", "cache")- out = {"present": True,- "skills_system": len(glob.glob(os.path.join(sk, ".system", "*", "SKILL.md"))),- "skills_user": len(glob.glob(os.path.join(sk, "*", "SKILL.md"))),- "plugin_cache": sum(len(_ls(m) or []) for m in glob.glob(os.path.join(pc, "*"))),- "dictation_sessions": len(_ls(os.path.join(home, "dictation-history"), 5000) or []),- "agents_md": os.path.exists(os.path.join(home, "AGENTS.md"))}- lg = sorted(glob.glob(os.path.join(home, "logs_*.sqlite")))- if lg:- dst = _copy_db(h, lg[-1], "codex-logs")- if dst:- try:- n, a, z = _q(dst, "select count(*), min(ts), max(ts) from logs")[0]- out["logs_db"] = {"rows": n, "first": _iso(a), "last": _iso(z)}- except Exception as e:- out["logs_db"] = {"error": type(e).__name__}- finally:- _rmdb(dst)- return out---@probe(id="codex.chatgpt_catalog", level="L2", family=AI, tier="T2", collect="deep", gate="codex.present")-def codex_chatgpt_catalog(h, facts):- """ChatGPT cloud conversations visible to Codex: count/date range by host kind + recent titles (T2)."""- dev = os.path.join(_codex_home(h), "sqlite", "codex-dev.db")- if not os.path.exists(dev):- return None- dst = _copy_db(h, dev, "codex-dev")- if not dst:- return None- try:- hosts = dict(_q(dst, "select host_id, host_kind from local_thread_catalog_hosts"))- rows = _q(dst, "select host_id, source_kind, count(*), min(source_created_at), max(source_created_at) from local_thread_catalog group by 1,2")- cat = [{"host_kind": hosts.get(hid, "?"), "source_kind": sk, "count": n, "first": _iso(a), "last": _iso(z)}- for hid, sk, n, a, z in rows]- titles = [_redact(t) for (t,) in _q(dst, "select display_title from local_thread_catalog where source_kind='chatgpt' order by source_updated_at desc limit 5")]- except Exception as e:- return {"present": True, "error": type(e).__name__}- finally:- _rmdb(dst)- return {"present": bool(cat), "catalog": cat, "recent_titles": titles}---@probe(id="consent.system_ai_models", level="L1", family=AI, tier="T1", collect="core")-def consent_system_ai_models(h, facts):- """CapabilityAccessManager systemAIModels consent: global value and apps that used on-device AI models."""- base = r"Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\systemAIModels"- out = {}- for label, hive in (("HKCU", winreg.HKEY_CURRENT_USER), ("HKLM", winreg.HKEY_LOCAL_MACHINE)):- k = _open(hive, base)- if k is None:- continue- apps = used = 0- for sk in list(_subkeys(k, 500)):- if sk == "NonPackaged":- nk = _open(hive, base + "\\NonPackaged")- subs = ["NonPackaged\\" + s for s in (list(_subkeys(nk, 500)) if nk else [])]- else:- subs = [sk]- for s in subs:- ak = _open(hive, base + "\\" + s)- if ak is None:- continue- apps += 1- if (_rv(ak, "LastUsedTimeStart") or 0) > 0:- used += 1- out[label] = {"value": _rv(k, "Value"), "apps": apps, "apps_used": used}- if not out:- return None- return {"present": True, **out}---@probe(id="copilot_cli.present", level="L1", family=AI, tier="T0", collect="core")-def copilot_cli_present(h, facts):- """GitHub Copilot CLI: ~/.copilot, firstLaunchAt, log/session counts, MCP server names."""- home = os.path.join(_U(h), ".copilot")- if not _isdir(home):- return None- c = _read_json(os.path.join(home, "config.json"), jsonc=True) or {}- mc = _read_json(os.path.join(home, "mcp-config.json"), jsonc=True) or {}- return {"present": True, "first_launch": _iso(c.get("firstLaunchAt")) if isinstance(c, dict) else None,- "logs": len(_ls(os.path.join(home, "logs")) or []),- "sessions": len(_ls(os.path.join(home, "session-state")) or []) + len(_ls(os.path.join(home, "history-session-state")) or []),- "mcp_servers": sorted((mc.get("mcpServers") or {}).keys()) if isinstance(mc, dict) else []}---@probe(id="copilot_m365.present", level="L1", family=AI, tier="T0", collect="core")-def copilot_m365_present(h, facts):- """Microsoft 365 Copilot (OfficeHub) and Windows Copilot appx + running process."""- m365 = _appx_match(h, r"^Microsoft\.MicrosoftOfficeHub$")- win = _appx_match(h, r"^Microsoft\.Copilot$")- run = _running(h, r"^m365copilot\.exe$|^copilot\.exe$")- if not (m365 or win):- return None- return {"present": True, "m365_version": m365[0]["version"] if m365 else None,- "windows_copilot_version": win[0]["version"] if win else None, "running": run}---@probe(id="cua_driver.present", level="L1", family=AI, tier="T0", collect="core")-def cua_driver_present(h, facts):- """cua-driver (computer-use): concrete release dirs (junctions fail over ssh), version check, running."""- home = os.path.join(_U(h), ".cua-driver")- if not _isdir(home) and not _isdir(os.path.join(_LA(h), "Programs", "Cua")):- return None- rel = sorted(_ls(os.path.join(home, "packages", "releases")) or [])- vc = _read_json(os.path.join(home, "version_check.json")) or {}- return {"present": True, "releases": rel[-5:], "releases_installed": sorted(_ls(os.path.join(home, ".release_installed")) or [])[-5:],- "first_install": _mtime(os.path.join(home, ".installation_recorded")),- "latest_available": vc.get("latest_version") if isinstance(vc, dict) else None,- "running": bool(_running(h, r"^cua-driver"))}---@probe(id="docker.model_runner", level="L1", family=AI, tier="T0", collect="core")-def docker_model_runner(h, facts):- """Docker Model Runner models.json model count."""- dm = _read_json(os.path.join(_U(h), ".docker", "models", "models.json"))- if dm is None:- return None- lst = dm.get("models", []) if isinstance(dm, dict) else dm- return {"present": True, "models": len(lst) if isinstance(lst, (list, dict)) else 0}---# ---------------- Hermes--def _hermes_homes(h):- def build():- env = h.l0.get("hermes_home") or os.environ.get("HERMES_HOME") or ""- LA, U = _LA(h), _U(h)- cands = []- for role, p in (("HERMES_HOME", env), ("localappdata", os.path.join(LA, "hermes")),- ("dot_hermes", os.path.join(U, ".hermes"))):- if p and _isdir(p) and all(os.path.normcase(p) != os.path.normcase(c["path"]) for c in cands):- cands.append({"role": role, "path": p, "has_state": os.path.exists(os.path.join(p, "state.db"))})- primary = next((c for c in cands if c["role"] == "HERMES_HOME"), None) or \- next((c for c in cands if c["has_state"]), None)- side = [p for p in glob.glob(os.path.join(LA, "hermes-*")) if _isdir(p)][:50]- return {"env_set": bool(env), "cands": cands, "primary": primary, "side": side}- return _memo(h, "hermes_homes", build)---@probe(id="hermes.present", level="L1", family=AI, tier="T0", collect="core")-def hermes_present(h, facts):- """Hermes Agent: HERMES_HOME/default homes, MSIX builds, desktop userData. Side homes flagged as operator."""- hh = _hermes_homes(h)- appx = _appx_match(h, r"^NousResearch\.|Hermes")- ud = glob.glob(os.path.join(_RA(h), "Hermes*"))- homes = []- for c in hh["cands"]:- p = c["path"]- im = None- try:- with open(os.path.join(p, ".install_method"), encoding="utf-8", errors="replace") as f:- im = f.read(40).strip()- except OSError:- pass- ver = None- pp = os.path.join(p, "hermes-agent", "pyproject.toml")- if tomllib and os.path.exists(pp):- try:- with open(pp, "rb") as f:- ver = tomllib.load(f).get("project", {}).get("version")- except Exception:- pass- homes.append({"role": c["role"], "primary": hh["primary"] is c, "state_db_bytes": (h.meta(os.path.join(p, "state.db")).get("bytes")),- "mtime": _mtime(p), "install_method": im, "agent_version": ver,- "git_checkout": _isdir(os.path.join(p, "hermes-agent", ".git"))})- if not (homes or appx or ud or hh["side"]):- return None- return {"present": True, "HERMES_HOME_set": hh["env_set"], "user_home": hh["primary"] is not None,- "homes": homes, "side_homes_operator": len(hh["side"]),- "appx": [{"name": p["name"], "version": p["version"], "arch": p["arch"]} for p in appx],- "desktop_userdata_dirs": len(ud), "running": sum(_running(h, r"^hermes").values())}---@probe(id="hermes.auth_presence", level="L1", family=AI, tier="T3", collect="core")-def hermes_auth_presence(h, facts):- """Primary Hermes home auth.json and .env presence/size (never opened)."""- p = _hermes_homes(h)["primary"]- if not p:- return None- a, e = h.meta(os.path.join(p["path"], "auth.json")), h.meta(os.path.join(p["path"], ".env"))- return {"present": a["present"] or e["present"], "auth_json": a, "env": e}---def _parse_hermes_yaml(p):- out = {"model": {}, "toolsets": [], "mcp_servers": [], "platform_toolsets": [], "top_level_keys": 0}- cur = None- with open(p, encoding="utf-8", errors="replace") as fh:- for n, raw in enumerate(fh):- if n > 5000:- break- line = raw.rstrip("\n")- if not line.strip() or line.lstrip().startswith("#"):- continue- ind = len(line) - len(line.lstrip(" "))- s = line.strip()- if ind == 0:- out["top_level_keys"] += 1- cur = s.split(":", 1)[0]- rest = s.split(":", 1)[1].strip() if ":" in s else ""- if cur == "model" and rest and rest != "{}":- out["model"]["default"] = rest.strip("'\"")- continue- if cur == "model" and ind == 2 and ":" in s:- k, v = s.split(":", 1)- v = v.strip().strip("'\"")- if k == "base_url":- m = re.match(r"https?://([^/:]+)", v)- host = m.group(1) if m else ""- v = "local" if re.match(r"^(127\.|localhost|0\.0\.0\.0|192\.168\.|10\.)", host) else host- if k in ("default", "provider", "base_url", "api_mode"):- out["model"][k] = v- elif cur == "toolsets" and s.startswith("- "):- out["toolsets"].append(s[2:].strip("'\""))- elif cur == "mcp_servers" and ind == 2 and s.endswith(":"):- out["mcp_servers"].append(s[:-1].strip("'\""))- elif cur == "platform_toolsets" and ind == 2 and ":" in s:- out["platform_toolsets"].append(s.split(":", 1)[0])- return out---@probe(id="hermes.config", level="L2", family=AI, tier="T0", collect="core", gate="hermes.present")-def hermes_config(h, facts):- """Primary Hermes config.yaml whitelist: model/provider, base_url host kind, toolsets, MCP names. .env never read."""- p = _hermes_homes(h)["primary"]- if not p or not os.path.exists(os.path.join(p["path"], "config.yaml")):- return None- try:- return {"present": True, **_parse_hermes_yaml(os.path.join(p["path"], "config.yaml"))}- except OSError:- return None---@probe(id="hermes.skills", level="L2", family=AI, tier="T1", collect="extended", gate="hermes.present")-def hermes_skills(h, facts):- """Primary Hermes skills: count, categories, archived; top-used names only if in the bundled catalog."""- p = _hermes_homes(h)["primary"]- if not p:- return None- sk = os.path.join(p["path"], "skills")- if not _isdir(sk):- return None- total, cats = 0, set()- for dp, dns, fns in os.walk(sk):- rel = os.path.relpath(dp, sk)- dns[:] = [d for d in dns if not d.startswith(".")] if rel.count(os.sep) < 4 else []- if "SKILL.md" in fns:- total += 1- if rel != ".":- cats.add(rel.split(os.sep)[0])- if total > 5000:- break- catalog = set()- for base in ("skills", "optional-skills"):- for f in glob.glob(os.path.join(p["path"], "hermes-agent", base, "**", "SKILL.md"), recursive=True)[:3000]:- catalog.add(os.path.basename(os.path.dirname(f)))- top, top_plugin, tracked, used = [], [], 0, 0- u = _read_json(os.path.join(sk, ".usage.json"))- if isinstance(u, dict):- items = u.get("skills", u) if isinstance(u.get("skills", u), dict) else {}- tracked = len(items)-- def score(v):- if isinstance(v, dict):- return v.get("use_count") or v.get("count") or v.get("uses") or 0- return v if isinstance(v, (int, float)) else 0- ranked = [k for k, v in sorted(items.items(), key=lambda kv: -score(kv[1])) if score(v) > 0]- top = [k for k in ranked if k in catalog][:5]- top_plugin = [k.split(":", 1)[1] for k in ranked if ":" in k][:5]- used = len(ranked)- cats = {d for d in (_ls(sk) or []) if not d.startswith(".") and _isdir(os.path.join(sk, d))}- return {"present": True, "skills": total, "categories": len(cats), "skills_used": used,- "top_used_plugin": top_plugin,- "archived": len(glob.glob(os.path.join(sk, ".archive", "*", "SKILL.md"))),- "usage_tracked": tracked, "top_used_catalog": top, "catalog_available": bool(catalog),- "plugins": len(_ls(os.path.join(p["path"], "plugins")) or [])}---def _hermes_db_summary(h, home, tag, titles=False):- st = os.path.join(home, "state.db")- if not os.path.exists(st):- return None- dst = _copy_db(h, st, tag)- if not dst:- return {"error": "copy_failed"}- try:- cs = _cols(dst, "sessions")- if titles:- if "title" not in cs:- return {"titles": []}- rows = _q(dst, "select title from sessions where title is not null and title != '' "- + ("and parent_session_id is null " if "parent_session_id" in cs else "")- + "order by started_at desc limit 5")- return {"titles": [_redact(t) for (t,) in rows]}- a, z = _q(dst, "select min(started_at), max(coalesce(ended_at, started_at)) from sessions")[0]- r = {"sessions": _q(dst, "select count(*) from sessions")[0][0],- "messages": _q(dst, "select count(*) from messages")[0][0],- "first": _iso(a), "last": _iso(z),- "by_source": dict(_q(dst, "select coalesce(source,'?'), count(*) from sessions group by 1")),- "by_month": dict(_q(dst, "select strftime('%Y-%m', started_at, 'unixepoch'), count(*) from sessions group by 1")),- "by_model": dict(_q(dst, "select coalesce(model,'?'), count(*) from sessions group by 1 order by 2 desc limit 10"))}- r["sessions_30d"] = _q(dst, "select count(*) from sessions where started_at >= ?", (time.time() - 30 * 86400,))[0][0]- if "parent_session_id" in cs:- r["subagent_sessions"] = _q(dst, "select count(*) from sessions where parent_session_id is not null")[0][0]- if "tool_call_count" in cs:- r["tool_calls"] = _q(dst, "select sum(tool_call_count) from sessions")[0][0]- if "estimated_cost_usd" in cs:- r["est_cost_usd"] = _q(dst, "select round(sum(estimated_cost_usd), 2) from sessions")[0][0]- try:- r["model_calls"] = [{"model": m, "provider": p, "calls": c} for m, p, c in- _q(dst, "select model, billing_provider, sum(api_call_count) from session_model_usage group by 1,2 order by 3 desc limit 10")]- except Exception:- pass- return r- except Exception as e:- return {"error": type(e).__name__}- finally:- _rmdb(dst)---@probe(id="hermes.usage", level="L2", family=AI, tier="T1", collect="extended", gate="hermes.present", timeout_ms=5000)-def hermes_usage(h, facts):- """Primary Hermes state.db (copied with -wal): session/message/tool-call counts, date range, sources, models."""- hh = _hermes_homes(h)- p = hh["primary"]- if not p:- return None- r = _hermes_db_summary(h, p["path"], "hermes-state")- if r is None:- return None- prof = []- for db in glob.glob(os.path.join(p["path"], "profiles", "*", "state.db"))[:20]:- s = _hermes_db_summary(h, os.path.dirname(db), "hermes-prof") or {}- prof.append({"sessions": s.get("sessions"), "first": s.get("first"), "last": s.get("last")})- others = []- for c in hh["cands"]:- if c is not p and c["has_state"]:- s = _hermes_db_summary(h, c["path"], "hermes-other") or {}- others.append({"role": c["role"], "sessions": s.get("sessions"), "last": s.get("last")})- return {"present": True, "home_role": p["role"], **r, "profiles": prof, "other_homes": others,- "side_homes_excluded": len(hh["side"])}---@probe(id="hermes.titles", level="L2", family=AI, tier="T2", collect="deep", gate="hermes.present")-def hermes_titles(h, facts):- """Most recent top-level Hermes session titles (redacted). T2 content, opt-in."""- p = _hermes_homes(h)["primary"]- if not p:- return None- r = _hermes_db_summary(h, p["path"], "hermes-titles", titles=True)- if not r or not r.get("titles"):- return None- return {"present": True, "recent": r["titles"]}---# ---------------- MCP inventory, NVIDIA, Ollama--BUNDLED_MCP = {"node_repl"}---@probe(id="l3.mcp_inventory", level="L2", family=AI, tier="T0", collect="core", gate="ai.catalog_absent_checks")-def l3_mcp_inventory(h, facts):- """Union of whitelisted MCP server names across agents; vendor-bundled servers separated."""- U, RA = _U(h), _RA(h)- by = {}- cj = _claude_json(h)- if cj:- by["claude_code"] = sorted(set(cj["global_mcp_servers"]) | set(cj["project_mcp_servers"]))- cp = os.path.join(_codex_home(h), "config.toml")- if tomllib and os.path.exists(cp):- try:- with open(cp, "rb") as f:- by["codex"] = sorted((tomllib.load(f).get("mcp_servers") or {}).keys())- except Exception:- pass- for label, path, keys in [("vscode", os.path.join(RA, "Code", "User", "mcp.json"), ("servers", "mcpServers")),- ("claude_desktop", os.path.join(RA, "Claude", "claude_desktop_config.json"), ("mcpServers",)),- ("cursor", os.path.join(U, ".cursor", "mcp.json"), ("mcpServers",)),- ("copilot_cli", os.path.join(U, ".copilot", "mcp-config.json"), ("mcpServers",)),- ("gemini_cli", os.path.join(U, ".gemini", "settings.json"), ("mcpServers",)),- ("windsurf", os.path.join(U, ".codeium", "windsurf", "mcp_config.json"), ("mcpServers",))]:- j = _read_json(path, jsonc=True)- if isinstance(j, dict):- for k in keys:- if isinstance(j.get(k), dict):- by[label] = sorted(j[k].keys()); break- p = _hermes_homes(h)["primary"]- if p and os.path.exists(os.path.join(p["path"], "config.yaml")):- try:- by["hermes"] = _parse_hermes_yaml(os.path.join(p["path"], "config.yaml"))["mcp_servers"]- except OSError:- pass- user = sorted({n for v in by.values() for n in v if n not in BUNDLED_MCP})- bundled = sorted({n for v in by.values() for n in v if n in BUNDLED_MCP})- nv = _isdir(os.path.join(_LA(h), "NVIDIA Corporation", "NVIDIA App", "McpServer"))- return {"present": True, "by_agent": {k: v for k, v in by.items() if v}, "user_configured": user,- "user_configured_total": len(user), "vendor_bundled": bundled + (["nvidia_app_mcp_server"] if nv else [])}---@probe(id="nvidia.app_mcp_server", level="L1", family=AI, tier="T0", collect="core")-def nvidia_app_mcp_server(h, facts):- """NVIDIA App McpServer dir + server.json key names and non-secret fields (token never emitted)."""- mcp = os.path.join(_LA(h), "NVIDIA Corporation", "NVIDIA App", "McpServer")- if not _isdir(mcp):- return None- sj = _read_json(os.path.join(mcp, "server.json"))- keys, info = [], {}- if isinstance(sj, dict):- keys = sorted(sj.keys())- info = {k: sj[k] for k in ("name", "title", "version") if isinstance(sj.get(k), str)}- del sj- return {"present": True, "mtime": _mtime(mcp), "files": len(_ls(mcp) or []), "server_json_keys": keys,- "has_token_key": "token" in keys, **info}---def _ollama_models_root(h):- return os.environ.get("OLLAMA_MODELS") or os.path.join(_U(h), ".ollama", "models")---@probe(id="ollama.present", level="L1", family=AI, tier="T0", collect="core")-def ollama_present(h, facts):- """Ollama install (per-user exe, uninstall version), models dir, running process."""- exe = os.path.join(_LA(h), "Programs", "Ollama", "ollama.exe")- mroot = _ollama_models_root(h)- if not (os.path.exists(exe) or _isdir(mroot) or _isdir(os.path.join(_U(h), ".ollama"))):- return None- un = _uninst_match(h, r"^Ollama")- return {"present": True, "exe": os.path.exists(exe), "version": un[0]["version"] if un else _file_version(exe),- "install_date": un[0]["install_date"] if un else None, "models_dir": _isdir(mroot),- "OLLAMA_MODELS_set": bool(os.environ.get("OLLAMA_MODELS")), "running": _running(h, r"^ollama")}---@probe(id="ollama.models", level="L2", family=AI, tier="T0", collect="core", gate="ollama.present")-def ollama_models(h, facts):- """Ollama model manifests (name, size, pulled date) and blob count."""- mroot = _ollama_models_root(h)- man = os.path.join(mroot, "manifests")- models = []- for f in glob.glob(os.path.join(man, "*", "*", "*", "*"))[:500]:- if not os.path.isfile(f):- continue- parts = f[len(man) + 1:].split(os.sep)- j = _read_json(f, maxb=1_000_000) or {}- size = sum(l.get("size", 0) for l in j.get("layers", []) if isinstance(l, dict)) + ((j.get("config") or {}).get("size", 0) or 0)- name = ("" if parts[1] == "library" else parts[1] + "/") + parts[2] + ":" + parts[3]- if parts[0] != "registry.ollama.ai":- name = parts[0] + "/" + name- models.append({"name": name, "gb": round(size / 1e9, 2), "pulled": _mtime(f)})- blobs = _ls(os.path.join(mroot, "blobs"), 20000)- return {"present": True, "count": len(models), "total_gb": round(sum(m["gb"] for m in models), 2),- "models": sorted(models, key=lambda m: -m["gb"])[:30], "blobs": len(blobs) if blobs is not None else None,- "manifests_mtime": _mtime(man)}---@probe(id="ollama.app_db", level="L2", family=AI, tier="T1", collect="extended", gate="ollama.present")-def ollama_app_db(h, facts):- """Ollama app db.sqlite: chat/message counts, signed-in flag (users row count only), first-run flags."""- db = os.path.join(_LA(h), "Ollama", "db.sqlite")- if not os.path.exists(db):- return None- dst = _copy_db(h, db, "ollama")- if not dst:- return None- try:- out = {"present": True}- for t in ("chats", "messages"):- try:- out[t] = _q(dst, f"select count(*) from {t}")[0][0]- except Exception:- out[t] = None- try:- out["signed_in"] = _q(dst, "select count(*) from users")[0][0] > 0- except Exception:- out["signed_in"] = None- cs = _cols(dst, "settings")- want = [c for c in ("has_completed_first_run", "claude_desktop_used", "codex_desktop_used", "turbo_enabled",- "websearch_enabled", "airplane_mode", "expose") if c in cs]- if want:- row = _q(dst, "select %s from settings limit 1" % ",".join(want))- out["settings"] = dict(zip(want, row[0])) if row else None- return out- except Exception as e:- return {"present": True, "error": type(e).__name__}- finally:- _rmdb(dst)---@probe(id="ollama.logs", level="L2", family=AI, tier="T1", collect="extended", gate="ollama.present")-def ollama_logs(h, facts):- """Ollama server/app logs: API call counts by path, active days, first/last; decides installed-but-unused."""- ld = os.path.join(_LA(h), "Ollama")- files = glob.glob(os.path.join(ld, "*.log"))[:20]- if not files:- return None- rx = re.compile(r'\[GIN\] (\d{4}/\d\d/\d\d) - (\d\d:\d\d:\d\d) \|.*\|\s+(GET|POST|HEAD|DELETE)\s+"([^"?]+)')- api, days, ver = collections.Counter(), set(), set()- first = last = None- for lf in files:- try:- with open(lf, encoding="utf-8", errors="replace") as fh:- for n, line in enumerate(fh):- if n > 500_000:- break- m = rx.search(line)- if m:- d = m.group(1) + " " + m.group(2)- days.add(m.group(1))- first = d if first is None or d < first else first- last = d if last is None or d > last else last- api[m.group(3) + " " + m.group(4)] += 1- v = re.search(r"version=(\d+\.\d+\.\d+)", line)- if v:- ver.add(v.group(1))- except OSError:- continue- infer = sum(v for k, v in api.items() if re.search(r"/api/(chat|generate|embed)|/v1/(chat|completions)", k))- return {"present": True, "files": len(files), "api_calls": _top(api, 12), "inference_calls": infer,- "first": first, "last": last, "active_days": len(days), "versions_logged": sorted(ver)}---# ================================================================== dev--@probe(id="apps.pkg_managers", level="L1", family=DEV, tier="T0", collect="core")-def apps_pkg_managers(h, facts):- """Package managers present: winget (alias + DesktopAppInstaller), scoop, choco, npm/uv/pipx on PATH."""- U, LA = _U(h), _LA(h)- dai = _appx_match(h, r"^Microsoft\.DesktopAppInstaller$")- out = {"winget": os.path.exists(os.path.join(LA, "Microsoft", "WindowsApps", "winget.exe")),- "winget_appinstaller_version": dai[0]["version"] if dai else None,- "scoop": _isdir(os.path.join(U, "scoop")) or _isdir(os.path.join(_PD(), "scoop")),- "choco": _isdir(os.path.join(_PD(), "chocolatey")),- "npm": bool(_which("npm")), "uv": bool(_which("uv")), "pipx": bool(_which("pipx")),- "pnpm": bool(_which("pnpm")), "bun": bool(_which("bun"))}- return {"present": True, **out}---@probe(id="dev.devmode_sudo_longpaths", level="L1", family=DEV, tier="T0", collect="core")-def dev_devmode_sudo_longpaths(h, facts):- """Developer Mode, Windows sudo and LongPathsEnabled registry toggles."""- dm = _open(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock")- fs = _open(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\FileSystem")- su = _open(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Sudo")- sudo_mode = {0: "disabled", 1: "forceNewWindow", 2: "disableInput", 3: "normal"}- sv = _rv(su, "Enabled") if su else None- return {"present": True, "developer_mode": _rv(dm, "AllowDevelopmentWithoutDevLicense") if dm else None,- "long_paths": _rv(fs, "LongPathsEnabled") if fs else None,- "sudo": sudo_mode.get(sv, sv) if sv is not None else None}---@probe(id="dev.docker", level="L1", family=DEV, tier="T0", collect="core")-def dev_docker(h, facts):- """Docker Desktop install + settings-store.json whitelisted keys (no docker spawn)."""- inst = os.path.join(_PF(), "Docker", "Docker")- un = _uninst_match(h, r"^Docker Desktop")- if not (_isdir(inst) or un):- return None- sel = {}- for p in (os.path.join(_RA(h), "Docker", "settings-store.json"), os.path.join(_RA(h), "Docker", "settings.json")):- j = _read_json(p)- if isinstance(j, dict):- sel = {k: j[k] for k in j if k in ("wslEngineEnabled", "WslEngineEnabled", "autoStart", "AutoStart",- "kubernetesEnabled", "KubernetesEnabled", "UseContainerdSnapshotter",- "useContainerdSnapshotter", "memoryMiB", "MemoryMiB", "cpus", "Cpus",- "EnableDockerAI", "EnableInference")- and isinstance(j[k], (bool, int, str))}- break- cli = os.path.join(inst, "resources", "bin", "docker.exe")- return {"present": True, "desktop_version": un[0]["version"] if un else None, "install_date": un[0]["install_date"] if un else None,- "cli_version": (lambda v: None if v in (None, "0.0.0.0") else v)(_file_version(cli)), "settings": sel,- "service_running": bool(_running(h, r"^com\.docker\.service|^docker desktop"))}---@probe(id="dev.docker_config_presence", level="L1", family=DEV, tier="T3", collect="core")-def dev_docker_config_presence(h, facts):- """~/.docker/config.json presence/size (may hold registry auths; never opened)."""- return h.meta(os.path.join(_U(h), ".docker", "config.json"))---@probe(id="dev.gh_auth_presence", level="L1", family=DEV, tier="T3", collect="core")-def dev_gh_auth_presence(h, facts):- """GitHub CLI hosts.yml presence/size (means gh logged in; never opened)."""- return h.meta(os.path.join(_RA(h), "GitHub CLI", "hosts.yml"))---@probe(id="dev.git", level="L1", family=DEV, tier="T0", collect="core")-def dev_git(h, facts):- """git on PATH + Git for Windows version from registry / file version (no spawn)."""- exe = _which("git")- k = _open(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\GitForWindows")- reg_ver = _rv(k, "CurrentVersion") if k else None- inst = _rv(k, "InstallPath") if k else None- if not (exe or reg_ver):- return None- base = inst or os.path.join(_PF(), "Git")- flavor = next((d for d in ("clangarm64", "mingw64", "mingw32") if _isdir(os.path.join(base, d))), None)- return {"present": True, "on_path": bool(exe), "git_for_windows_version": reg_ver,- "file_version": _file_version(os.path.join(base, "cmd", "git.exe")), "flavor": flavor}---@probe(id="dev.npm_globals", level="L2", family=DEV, tier="T1", collect="core", gate="apps.pkg_managers")-def dev_npm_globals(h, facts):- """Global npm packages from %APPDATA%\\npm\\node_modules listing (no `npm root -g` spawn)."""- root = os.path.join(_RA(h), "npm", "node_modules")- names = _ls(root, 500)- if names is None:- return {"present": False}- pk = []- for n in names:- if n.startswith("@"):- pk += [f"{n}/{s}" for s in (_ls(os.path.join(root, n), 100) or [])]- elif not n.startswith("."):- pk.append(n)- return {"present": True, "count": len(pk), "packages": sorted(pk)[:80]}---@probe(id="dev.npmrc_presence", level="L1", family=DEV, tier="T3", collect="core")-def dev_npmrc_presence(h, facts):- """~/.npmrc presence/size (may hold registry tokens; never opened)."""- return h.meta(os.path.join(_U(h), ".npmrc"))---_PATH_TOOLS = [("winget_links", r"\\WinGet\\Links"), ("winget_packages", r"\\WinGet\\Packages"),- ("windowsapps", r"\\WindowsApps$"), ("git", r"\\Git\\(cmd|bin)"), ("nodejs", r"\\nodejs"),- ("npm_global", r"\\npm$"), ("python", r"\\Python\d+"), ("uv_or_local_bin", r"\\\.local\\bin|\\uv\\"),- ("hermes", r"\\hermes\\bin"), ("cargo", r"\\\.cargo\\bin"), ("go", r"\\go\\bin|\\Go\\bin"),- ("vscode", r"Microsoft VS Code"), ("ollama", r"\\Ollama"), ("cua", r"\\Cua\\"),- ("docker", r"\\Docker\\"), ("powershell7", r"\\PowerShell\\7"), ("dotnet", r"\\dotnet"),- ("java", r"\\(jdk|Java|Adoptium)"), ("cuda", r"CUDA"), ("tailscale", r"Tailscale"),- ("nvidia", r"NVIDIA"), ("gh", r"GitHub CLI"), ("obs", r"obs-studio"), ("ffmpeg", r"ffmpeg")]---@probe(id="dev.path_entries", level="L1", family=DEV, tier="T0", collect="core")-def dev_path_entries(h, facts):- """User/machine PATH entry counts and known-tool matches (paths themselves not emitted)."""- uk = _open(winreg.HKEY_CURRENT_USER, "Environment")- mk = _open(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")- up = [x for x in ((_rv(uk, "Path") if uk else "") or "").split(";") if x]- mp = [x for x in ((_rv(mk, "Path") if mk else "") or "").split(";") if x]- tools = {"user": sorted({t for t, rx in _PATH_TOOLS for e in up if re.search(rx, e, re.I)}),- "machine": sorted({t for t, rx in _PATH_TOOLS for e in mp if re.search(rx, e, re.I)})}- return {"present": True, "user": len(up), "machine": len(mp), "tools": tools}---@probe(id="dev.pwsh7", level="L1", family=DEV, tier="T0", collect="core")-def dev_pwsh7(h, facts):- """PowerShell 7 presence and file version (never spawned)."""- exe = _which("pwsh")- cand = os.path.join(_PF(), "PowerShell", "7", "pwsh.exe")- path = exe if exe and "windowsapps" not in exe.lower() else (cand if os.path.exists(cand) else exe)- if not path:- return None- return {"present": True, "on_path": bool(exe), "version": _file_version(path) if os.path.exists(path) else None,- "store_alias": bool(exe and "windowsapps" in exe.lower())}---@probe(id="dev.ssh_config", level="L2", family=DEV, tier="T1", collect="core", gate="dev.path_entries")-def dev_ssh_config(h, facts):- """~/.ssh/config Host alias count and Include count (hostnames not emitted); known_hosts line count."""- d = os.path.join(_U(h), ".ssh")- if not _isdir(d):- return {"present": False}- cfg = os.path.join(d, "config")- aliases = includes = lines = 0- if os.path.exists(cfg):- with open(cfg, encoding="utf-8", errors="replace") as f:- for n, line in enumerate(f):- if n > 5000:- break- lines += 1- m = re.match(r"^\s*Host\s+(.+)$", line, re.I)- if m:- aliases += len([x for x in m.group(1).split() if x != "*"])- if re.match(r"^\s*Include\s", line, re.I):- includes += 1- kh = os.path.join(d, "known_hosts")- khl = None- if os.path.exists(kh):- with open(kh, "rb") as f:- khl = sum(1 for _ in zip(range(100000), f))- return {"present": True, "config": os.path.exists(cfg), "config_lines": lines, "host_aliases": aliases,- "includes": includes, "known_hosts_lines": khl}---_TOOLCHAIN = ["node", "npm", "pnpm", "yarn", "bun", "deno", "nvm", "fnm", "volta", "uv", "py", "pipx", "conda", "poetry",- "rustc", "cargo", "rustup", "go", "dotnet", "java", "javac", "mvn", "gradle", "cmake", "ninja", "clang",- "gcc", "zig", "nvcc", "gh", "pwsh", "docker", "kubectl", "terraform", "tailscale", "claude", "codex",- "hermes", "ollama", "code", "cursor", "windsurf", "zed", "nvim", "vim", "python", "python3"]---@probe(id="dev.toolchain_presence", level="L1", family=DEV, tier="T0", collect="core")-def dev_toolchain_presence(h, facts):- """which() for node/python/rust/go/java/native/AI CLIs + off-PATH install dirs. Git Bash by path only."""- found, stubs = [], []- for t in _TOOLCHAIN:- p = _which(t)- if not p:- continue- low = p.lower()- if "\\windowsapps\\" in low and os.path.basename(low) in ("python.exe", "python3.exe"):- try:- if os.path.getsize(p) == 0:- stubs.append(t); continue- except OSError:- pass- found.append(t)- U, LA, RA, PF = _U(h), _LA(h), _RA(h), _PF()- off = {k: _isdir(p) for k, p in [- ("cargo_home", os.path.join(U, ".cargo")), ("rustup", os.path.join(U, ".rustup")), ("go_root", os.path.join(PF, "Go")),- ("uv_pythons", os.path.join(RA, "uv", "python")), ("python_org", os.path.join(LA, "Programs", "Python")),- ("dotnet_sdk", os.path.join(PF, "dotnet", "sdk")), ("java_adoptium", os.path.join(PF, "Eclipse Adoptium")),- ("java_oracle", os.path.join(PF, "Java")), ("cuda", os.path.join(PF, "NVIDIA GPU Computing Toolkit", "CUDA")),- ("llvm", os.path.join(PF, "LLVM")), ("android_sdk", os.path.join(LA, "Android", "Sdk")),- ("miniconda", os.path.join(U, "miniconda3")), ("anaconda", os.path.join(U, "anaconda3")),- ("pyenv", os.path.join(U, ".pyenv")), ("nvm_windows", os.path.join(RA, "nvm")),- ("visual_studio", os.path.join(PF, "Microsoft Visual Studio")),- ("vs_installer", os.path.join(_PF86(), "Microsoft Visual Studio", "Installer"))]}- return {"present": True, "on_path": found, "store_stubs": stubs,- "git_bash": os.path.exists(os.path.join(PF, "Git", "bin", "bash.exe")),- "off_path": sorted(k for k, v in off.items() if v)}---@probe(id="dev.uv_tools", level="L2", family=DEV, tier="T1", collect="core", gate="dev.toolchain_presence")-def dev_uv_tools(h, facts):- """uv tools and uv-managed Pythons (dir listing), ~/.local/bin entries; no uv spawn."""- RA, U = _RA(h), _U(h)- tools = _ls(os.path.join(RA, "uv", "tools"), 200)- py = _ls(os.path.join(RA, "uv", "python"), 200)- lb = _ls(os.path.join(U, ".local", "bin"), 300)- if tools is None and py is None and lb is None:- return {"present": False}- return {"present": True, "tools": sorted(t for t in (tools or []) if not t.startswith("."))[:60],- "pythons": sorted(p for p in (py or []) if p.startswith(("cpython", "pypy")))[:30],- "local_bin_count": len(lb or []), "local_bin": sorted(lb or [])[:40]}---@probe(id="dev.wsl", level="L1", family=DEV, tier="T0", collect="core")-def dev_wsl(h, facts):- """WSL distros from the HKCU Lxss key (no wsl.exe), vhdx size, WSL package version, .wslconfig presence."""- base = r"Software\Microsoft\Windows\CurrentVersion\Lxss"- k = _open(winreg.HKEY_CURRENT_USER, base)- distros = []- if k is not None:- default = _rv(k, "DefaultDistribution")- for sub in _subkeys(k, 100):- dk = _open(winreg.HKEY_CURRENT_USER, base + "\\" + sub)- if dk is None:- continue- bp = (_rv(dk, "BasePath") or "").replace("\\\\?\\", "")- vhd = None- for fn in ("ext4.vhdx", "ext4.VHDX"):- try:- vhd = round(os.path.getsize(os.path.join(bp, fn)) / 2**30, 2); break- except OSError:- pass- distros.append({"name": _rv(dk, "DistributionName"), "version": _rv(dk, "Version"),- "default": sub == default, "vhdx_gib": vhd})- un = _uninst_match(h, r"^Windows Subsystem for Linux")- appx = _appx_match(h, r"^MicrosoftCorporationII\.WindowsSubsystemForLinux$")- pkg = (un[0]["version"] if un else None) or (appx[0]["version"] if appx else None) or \- _file_version(os.path.join(_PF(), "WSL", "wsl.exe"), kind="file")- inbox = os.path.exists(os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "wsl.exe"))- if not (distros or pkg or k is not None):- return {"present": False, "inbox_launcher": inbox}- return {"present": True, "distros": distros, "distro_count": len(distros), "wsl_package_version": pkg,- "inbox_launcher": inbox, "wslconfig": os.path.exists(os.path.join(_U(h), ".wslconfig"))}---@probe(id="dev.wt_profiles", level="L2", family=DEV, tier="T1", collect="core", gate="dev.toolchain_presence")-def dev_wt_profiles(h, facts):- """Windows Terminal settings.json: profile count, source kinds, default kind, customisation counts."""- LA = _LA(h)- out = {}- for label, p in [("stable", os.path.join(LA, "Packages", "Microsoft.WindowsTerminal_8wekyb3d8bbwe", "LocalState", "settings.json")),- ("preview", os.path.join(LA, "Packages", "Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe", "LocalState", "settings.json")),- ("unpackaged", os.path.join(LA, "Microsoft", "Windows Terminal", "settings.json"))]:- j = _read_json(p, jsonc=True)- if not isinstance(j, dict):- continue- profs = j.get("profiles", {})- plist = profs.get("list", []) if isinstance(profs, dict) else (profs or [])- dflt = j.get("defaultProfile")- kinds = collections.Counter()- dkind = None- for pr in plist:- if not isinstance(pr, dict):- continue- src = pr.get("source") or ""- if src:- kind = src.split(".")[-1]- else:- exe = os.path.basename((pr.get("commandline") or "").split(" ")[0]).lower()- kind = {"powershell.exe": "WindowsPowerShell", "cmd.exe": "CommandPrompt", "pwsh.exe": "PowerShell",- "wsl.exe": "WSL", "ssh.exe": "ssh"}.get(exe, "custom" if exe else "unknown")- kinds[kind] += 1- if pr.get("guid") == dflt:- dkind = kind- out[label] = {"profiles": len(plist), "visible": sum(1 for x in plist if isinstance(x, dict) and not x.get("hidden")),- "kinds": dict(kinds), "default_kind": dkind, "mtime": _mtime(p),- "actions": len(j.get("actions", []) or []) + len(j.get("keybindings", []) or []),- "schemes": len(j.get("schemes", []) or []), "theme_set": bool(j.get("theme"))}- return {"present": bool(out), **out}---_AI_EXT = re.compile(r"copilot|continue|cline|claude|anthropic|openai|chatgpt|codeium|windsurf|tabnine|amazonq|gemini|cody|sourcegraph|supermaven|roo|kilo|ollama|aider|hermes", re.I)---def _ext_ids(d):- j = _read_json(os.path.join(d, "extensions.json"))- ids = []- if isinstance(j, list):- ids = [((e.get("identifier") or {}).get("id") or "").lower() for e in j if isinstance(e, dict)]- if not any(ids):- ids = [m.group(1).lower() for x in (_ls(d) or []) for m in [re.match(r"^([\w\-]+\.[\w\-]+)-\d", x)] if m]- return sorted({i for i in ids if i})---@probe(id="editor.vscode", level="L2", family=DEV, tier="T2", collect="core", gate="dev.toolchain_presence")-def editor_vscode(h, facts):- """VS Code-family editors: install, extension ids (AI ones flagged), workspaces opened, MCP/chat state; other editors."""- U, LA, RA = _U(h), _LA(h), _RA(h)- eds = {"vscode": ([os.path.join(LA, "Programs", "Microsoft VS Code"), os.path.join(_PF(), "Microsoft VS Code")],- os.path.join(U, ".vscode", "extensions"), os.path.join(RA, "Code", "User")),- "vscode_insiders": ([os.path.join(LA, "Programs", "Microsoft VS Code Insiders")],- os.path.join(U, ".vscode-insiders", "extensions"), os.path.join(RA, "Code - Insiders", "User")),- "cursor": ([os.path.join(LA, "Programs", "cursor")], os.path.join(U, ".cursor", "extensions"), os.path.join(RA, "Cursor", "User")),- "windsurf": ([os.path.join(LA, "Programs", "Windsurf")], os.path.join(U, ".windsurf", "extensions"), os.path.join(RA, "Windsurf", "User")),- "vscodium": ([os.path.join(LA, "Programs", "VSCodium")], os.path.join(U, ".vscode-oss", "extensions"), os.path.join(RA, "VSCodium", "User")),- "kiro": ([os.path.join(LA, "Programs", "Kiro")], os.path.join(U, ".kiro", "extensions"), os.path.join(RA, "Kiro", "User"))}- out = {}- for name, (inst, extd, user) in eds.items():- installed = any(_isdir(p) for p in inst)- if not (installed or _isdir(extd) or _isdir(user)):- continue- ids = _ext_ids(extd) if _isdir(extd) else []- e = {"installed": installed, "extensions": len(ids), "extension_ids": ids[:80],- "ai_extensions": [i for i in ids if _AI_EXT.search(i)]}- if _isdir(user):- ws = _ls(os.path.join(user, "workspaceStorage"), 5000)- e["workspaces_opened"] = len(ws) if ws is not None else 0- e["settings_json"] = os.path.exists(os.path.join(user, "settings.json"))- e["keybindings_json"] = os.path.exists(os.path.join(user, "keybindings.json"))- e["profiles"] = len(_ls(os.path.join(user, "profiles")) or [])- mj = _read_json(os.path.join(user, "mcp.json"), jsonc=True)- e["mcp_servers"] = len((mj.get("servers") or mj.get("mcpServers") or {})) if isinstance(mj, dict) else 0- e["chat_sessions"] = len(glob.glob(os.path.join(user, "globalStorage", "emptyWindowChatSessions", "*"))[:5000]) + \- len(glob.glob(os.path.join(user, "workspaceStorage", "*", "chatSessions", "*"))[:5000])- e["user_mtime"] = _mtime(user)- out[name] = e- other = {"jetbrains": [x for x in (_ls(os.path.join(RA, "JetBrains")) or []) if re.match(r"^[A-Za-z]+\d{4}\.\d", x)],- "zed": _isdir(os.path.join(LA, "Zed")) or _isdir(os.path.join(RA, "Zed")),- "neovim_config": _isdir(os.path.join(LA, "nvim")),- "vimrc": os.path.exists(os.path.join(U, "_vimrc")) or os.path.exists(os.path.join(U, ".vimrc")),- "notepadpp": _isdir(os.path.join(_PF(), "Notepad++")),- "sublime": _isdir(os.path.join(_PF(), "Sublime Text")) or _isdir(os.path.join(RA, "Sublime Text")),- "visual_studio": [x for x in (_ls(os.path.join(_PF(), "Microsoft Visual Studio")) or []) if x[:2].isdigit()]}- other = {k: v for k, v in other.items() if v}- customised = any(e["extensions"] or e.get("settings_json") or e.get("keybindings_json") for e in out.values())- return {"present": bool(out or other), "extensions": sum(e["extensions"] for e in out.values()),- "customised": customised, "editors": out, "other": other}---@probe(id="dev.git_global_config", level="L2", family=DEV, tier="T0", collect="extended", gate="dev.git")-def dev_git_global_config(h, facts):- """~/.gitconfig parsed without spawn: booleans for identity/credential helper/editor + section counts only."""- p = os.path.join(_U(h), ".gitconfig")- if not os.path.exists(p):- return {"present": False}- sections, keys = collections.Counter(), set()- cred_kind = None- cur = None- with open(p, encoding="utf-8", errors="replace") as f:- for n, line in enumerate(f):- if n > 3000:- break- s = line.strip()- m = re.match(r"^\[\s*([A-Za-z0-9.\-]+)", s)- if m:- cur = m.group(1).lower(); sections[cur] += 1; continue- if "=" in s and cur and not s.startswith(("#", ";")):- k, v = s.split("=", 1)- k = k.strip().lower()- keys.add(f"{cur}.{k}")- if cur == "credential" and k == "helper" and v.strip():- lv = v.lower()- cred_kind = next((n for n, rx in (("gh", r"gh(\.exe)?['\"]?\s+auth"), ("manager", r"manager"),- ("wincred", r"wincred"), ("store", r"^\s*store"),- ("cache", r"^\s*cache")) if re.search(rx, lv)), "custom")- return {"present": True, "bytes": os.path.getsize(p),- "identity_set": "user.name" in keys and "user.email" in keys,- "identity_name_set": "user.name" in keys, "identity_email_set": "user.email" in keys,- "credential_helper": cred_kind, "editor_set": "core.editor" in keys,- "signing_set": "user.signingkey" in keys or "commit.gpgsign" in keys,- "sections": dict(sections)}---def _version_line(txt):- for l in txt.splitlines():- l = l.strip()- if l:- return _redact(l, 90)- return None---@probe(id="dev.toolchain_versions", level="L2", family=DEV, tier="T0", collect="extended", gate="dev.toolchain_presence",- timeout_ms=12000)-def dev_toolchain_versions(h, facts):- """--version spawns (parallel, gated on which): node, npm, uv, dotnet, gh, AI CLIs, infra CLIs. Never bash/pwsh."""- from concurrent.futures import ThreadPoolExecutor- specs = [("node", ["--version"]), ("npm", ["--version"]), ("uv", ["--version"]), ("gh", ["--version"]),- ("dotnet", ["--list-sdks"]), ("claude", ["--version"]), ("codex", ["--version"]),- ("hermes", ["--version"]), ("ollama", ["--version"]), ("docker", ["--version"]),- ("kubectl", ["version", "--client=true"]), ("tailscale", ["version"]), ("git", ["--version"]),- ("rustc", ["--version"]), ("go", ["version"]), ("java", ["-version"]), ("deno", ["--version"]),- ("bun", ["--version"]), ("pnpm", ["--version"])]- todo = []- for name, args in specs:- exe = _which(name)- if exe and "\\windowsapps\\" not in exe.lower() and os.path.basename(exe).lower() not in ("bash.exe", "pwsh.exe"):- todo.append((name, [exe] + args))- env = dict(os.environ, NO_COLOR="1", HERMES_NO_UPDATE_CHECK="1")-- def one(item):- name, args = item- rc, txt, ms = _spawn(args, timeout=8, env=env)- if name == "dotnet":- sdks = [l.split()[0] for l in txt.splitlines() if re.match(r"^\d", l.strip())]- rc2, txt2, ms2 = _spawn([args[0], "--list-runtimes"], timeout=8, env=env)- rts = sorted({" ".join(l.split()[:2]) for l in txt2.splitlines() if re.match(r"^Microsoft\.", l.strip())})- return name, {"sdks": sdks[:10], "runtimes": rts[:10], "rc": rc, "ms": round(ms + ms2, 1)}- return name, {"version": _version_line(txt) if rc == 0 or txt else None, "rc": rc, "ms": ms}- out = {}- with ThreadPoolExecutor(max_workers=6) as ex:- for name, r in ex.map(one, todo):- out[name] = r- return {"present": bool(out), "tools": out}---# ---------------- repos (deep)--_SKIP_DIRS = {"node_modules", "appdata", "$recycle.bin", "system volume information", "windows", "program files",- "program files (x86)", "programdata", "__pycache__", ".venv", "venv", "site-packages", ".cache",- "cache", "temp", "tmp", "msocache", "recovery", "perflogs", "onedrivetemp"}---def _is_reparse(e):- try:- return bool(e.stat(follow_symlinks=False).st_file_attributes & 0x400) or e.is_symlink()- except (OSError, AttributeError):- return e.is_symlink()---def _repos(h):- def build():- deadline = time.perf_counter() + 8.0- U, LA = _U(h), _LA(h)- hits, seen = [], set()- visited = [0]-- def walk(root, maxdepth, skip_appdata=True):- stack = [(root, 0)]- while stack and time.perf_counter() < deadline and visited[0] < 60000:- d, depth = stack.pop()- visited[0] += 1- try:- with os.scandir(d) as it:- ents = list(zip(range(3000), it))- except OSError:- continue- names = {e.name.lower() for _, e in ents}- if ".git" in names and os.path.exists(os.path.join(d, ".git", "HEAD")) or \- (".git" in names and os.path.isfile(os.path.join(d, ".git"))):- rp = os.path.normcase(os.path.realpath(d))- if rp not in seen:- seen.add(rp); hits.append(d)- continue- if depth >= maxdepth:- continue- for _, e in ents:- n = e.name.lower()- if n in _SKIP_DIRS and (skip_appdata or n != "appdata"):- continue- try:- if not e.is_dir(follow_symlinks=False) or _is_reparse(e):- continue- except OSError:- continue- stack.append((e.path, depth + 1))-- walk(U, 5)- walk(LA, 3, skip_appdata=False)- try:- with os.scandir("C:\\") as it:- tops = [e.path for e in it if e.is_dir(follow_symlinks=False) and e.name.lower() not in _SKIP_DIRS- and e.name.lower() != "users" and not _is_reparse(e)]- except OSError:- tops = []- for t in tops[:60]:- walk(t, 3)- repos = []- for d in hits[:200]:- if _is_operator_path(h, d):- cls = "operator"- else:- rel = os.path.relpath(d, U) if os.path.normcase(d).startswith(os.path.normcase(U)) else None- first = rel.split(os.sep, 1)[0] if rel else ""- if os.path.normcase(d).startswith(os.path.normcase(LA)) or first.lower() == "appdata" or first.startswith("."):- cls = "tool_managed"- else:- cls = "user_area"- gd = os.path.join(d, ".git")- remotes, branch, head_mtime, local_email = [], None, None, None- if os.path.isdir(gd):- try:- with open(os.path.join(gd, "HEAD"), encoding="utf-8", errors="replace") as f:- hd = f.read(200).strip()- branch = hd[16:] if hd.startswith("ref: refs/heads/") else "detached"- except OSError:- pass- head_mtime = _mtime(os.path.join(gd, "logs", "HEAD")) or _mtime(os.path.join(gd, "index"))- try:- with open(os.path.join(gd, "config"), encoding="utf-8", errors="replace") as f:- cfg = f.read(100_000)- remotes = re.findall(r"^\s*url\s*=\s*(\S+)", cfg, re.M)- m = re.search(r"^\s*email\s*=\s*(\S+)", cfg, re.M)- local_email = m.group(1).lower() if m else None- except OSError:- pass- markers = [m for m in ("package.json", "pyproject.toml", "uv.lock", "Cargo.toml", "go.mod", "pom.xml",- "build.gradle", "Dockerfile", "flake.nix", "AGENTS.md", "CLAUDE.md", ".mcp.json")- if os.path.exists(os.path.join(d, m))]- repos.append({"path": d, "class": cls, "branch": branch, "head_mtime": head_mtime, "remotes": remotes,- "local_email": local_email, "markers": markers})- return {"repos": repos, "visited_dirs": visited[0], "timed_out": time.perf_counter() >= deadline}- return _memo(h, "repos", build)---def _remote_parse(url):- m = re.match(r"^(?:\w+://)?(?:[^@/]+@)?([^/:]+)[:/]([^/]+)/([^/]+?)(?:\.git)?/?$", url)- return (m.group(1).lower(), m.group(2), m.group(3)) if m else (None, None, None)---@probe(id="dev.repos", level="L2", family=DEV, tier="T2", collect="deep", gate="dev.git", timeout_ms=15000)-def dev_repos(h, facts):- """Bounded repo walk (home d5, LOCALAPPDATA d3, C:\\ tops d3): class, markers, freshness. Repo names are T2."""- r = _repos(h)- repos = r["repos"]- by_cls = collections.Counter(x["class"] for x in repos)- listed = [{"name": os.path.basename(x["path"]), "class": x["class"], "branch": x["branch"],- "head_mtime": x["head_mtime"], "markers": x["markers"]} for x in repos if x["class"] != "operator"]- return {"present": bool(repos), "count": len(repos), "by_class": dict(by_cls), "repos": listed[:50],- "visited_dirs": r["visited_dirs"], "walk_timed_out": r["timed_out"]}---@probe(id="dev.repos.remotes", level="L2", family=DEV, tier="T2", collect="deep", gate="dev.git", timeout_ms=15000)-def dev_repos_remotes(h, facts):- """Remote hosts (counts) and org/repo names for non-operator repos (T2)."""- hosts, orgs = collections.Counter(), set()- for x in _repos(h)["repos"]:- if x["class"] == "operator":- continue- for u in x["remotes"]:- host, org, name = _remote_parse(u)- if host:- hosts[host] += 1- orgs.add(f"{host}/{org}/{name}")- return {"present": bool(hosts), "hosts": dict(hosts), "repos": sorted(orgs)[:50]}---def _commits(h):- def build():- git = _which("git")- if not git:- return None- ids = set()- env_ids = os.environ.get("UIL_GIT_IDENTITY", "")- ids |= {x.strip().lower() for x in env_ids.split(",") if x.strip()}- gc = os.path.join(_U(h), ".gitconfig")- try:- with open(gc, encoding="utf-8", errors="replace") as f:- ids |= {m.lower() for m in re.findall(r"^\s*email\s*=\s*(\S+)", f.read(100_000), re.M)}- except OSError:- pass- res = {"identity_sources": {"env": bool(env_ids), "global": False, "repo_local": 0}, "by_class": {},- "hours_local": collections.Counter(), "tz_offsets": collections.Counter(), "weekday": collections.Counter(),- "month": collections.Counter(), "repos_with_own": {}}- res["identity_sources"]["global"] = bool(ids - {x.strip().lower() for x in env_ids.split(",") if x.strip()})- deadline = time.perf_counter() + 10.0- for x in _repos(h)["repos"]:- if x["class"] == "operator" or time.perf_counter() > deadline:- continue- rid = set(ids)- if x["local_email"]:- rid.add(x["local_email"]); res["identity_sources"]["repo_local"] += 1- rc, txt, _ms = _spawn([git, "-C", x["path"], "log", "--all", "--no-merges", "--format=%ae%x09%an%x09%at%x09%ai",- "-n", "100000"], timeout=10)- if rc != 0:- continue- mine = total = 0- for line in txt.splitlines():- parts = line.split("\t")- if len(parts) < 4:- continue- total += 1- if parts[0].lower() in rid or parts[1].lower() in rid:- mine += 1- try:- t = dt.datetime.fromtimestamp(int(parts[2]))- res["hours_local"][t.hour] += 1- res["weekday"][t.strftime("%a")] += 1- res["month"][t.strftime("%Y-%m")] += 1- except (ValueError, OSError):- pass- res["tz_offsets"][parts[3].strip()[-5:]] += 1- c = res["by_class"].setdefault(x["class"], [0, 0])- c[0] += mine; c[1] += total- if mine:- res["repos_with_own"][x["class"]] = res["repos_with_own"].get(x["class"], 0) + 1- return res- return _memo(h, "commits", build)---@probe(id="dev.repos.my_commits", level="L2", family=DEV, tier="T1", collect="deep", gate="dev.git", timeout_ms=20000)-def dev_repos_my_commits(h, facts):- """Authored-commit counts [mine, all] by repo class, matched on-host to an identity set (never emitted)."""- c = _commits(h)- if not c:- return None- return {"present": bool(c["by_class"]), "by_class_mine_all": c["by_class"], "identity_sources": c["identity_sources"],- "repos_with_own_commits": c["repos_with_own"].get("user_area", 0),- "repos_with_own_commits_by_class": c["repos_with_own"],- "note": "clone history includes upstream; tool_managed counts are not work on this box"}---@probe(id="dev.repos.commit_hours", level="L2", family=DEV, tier="T1", collect="deep", gate="dev.git", timeout_ms=20000)-def dev_repos_commit_hours(h, facts):- """Host-timezone hour histogram, bands, weekday, month and author-TZ offsets of the user's commits."""- c = _commits(h)- if not c or not c["hours_local"]:- return None- hrs = c["hours_local"]- bands = {f"{a:02d}-{a + 5:02d}": sum(hrs.get(x, 0) for x in range(a, a + 6)) for a in (0, 6, 12, 18)}- return {"present": True, "commits": sum(hrs.values()), "hours": {str(k): v for k, v in sorted(hrs.items())},- "bands": bands, "top_hours": [k for k, _ in hrs.most_common(4)], "weekday": dict(c["weekday"]),- "month": dict(sorted(c["month"].items())), "tz_offsets": dict(c["tz_offsets"].most_common(6))}---@probe(id="dev.shell_history", level="L2", family=DEV, tier="T1", collect="deep", gate="dev.path_entries")-def dev_shell_history(h, facts):- """Shell history files: line count and last-write only (text never emitted)."""- out = {}- psr = os.path.join(_RA(h), "Microsoft", "Windows", "PowerShell", "PSReadLine")- files = [("psreadline:" + f, os.path.join(psr, f)) for f in (_ls(psr) or []) if f.lower().endswith(".txt")]- files += [(f, os.path.join(_U(h), f)) for f in (".bash_history", ".zsh_history", ".python_history", ".node_repl_history")]- for label, p in files:- try:- st = os.stat(p)- if st.st_size > 50_000_000:- out[label] = {"bytes": st.st_size, "lines": None, "mtime": _day(st.st_mtime)}- continue- with open(p, "rb") as f:- n = sum(1 for l in f if l.strip())- out[label] = {"lines": n, "bytes": st.st_size, "mtime": _day(st.st_mtime)}- except OSError:- continue- return {"present": bool(out), **out}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/apps_dev_agents.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/apps_dev_agents.pynew file mode 100644index 00000000000..d11766eaef8--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/apps_dev_agents.py@@ -0,0 +1,944 @@+"""AI agent probes (ai_agents family, Windows): Claude Code, Codex, Hermes, MCP inventory, NVIDIA, Ollama.++Registration only at import time. Shared helpers and memoised reads live in apps_dev.+"""+from __future__ import annotations++import collections+import datetime as dt+import glob+import json+import os+import re+import time++from ..registry import probe+from .apps_dev import (AI, _LA, _PD, _RA, _U, _appx_match, _cols, _copy_db, _file_version,+ _isdir, _iso, _ls, _memo, _mtime, _open, _q, _read_json, _redact, _rmdb, _running, _rv, _subkeys, _top,+ _uninst_match, tomllib, winreg)++# ================================================================== ai_agents++def _detect(paths):+ return [p for p in paths if p and os.path.exists(p)]+++@probe(id="ai.catalog_absent_checks", level="L1", family=AI, tier="T0", collect="core")+def ai_catalog_absent_checks(h, facts):+ """Path stats for AI tools the user may lack (Cursor, Windsurf, Gemini CLI, opencode, aider, LM Studio...)."""+ U, LA, RA = _U(h), _LA(h), _RA(h)+ npm = os.path.join(RA, "npm", "node_modules")+ cat = {+ "cursor": [os.path.join(U, ".cursor"), os.path.join(RA, "Cursor"), os.path.join(LA, "Programs", "cursor")],+ "windsurf": [os.path.join(U, ".codeium"), os.path.join(U, ".windsurf"), os.path.join(RA, "Windsurf"),+ os.path.join(LA, "Programs", "Windsurf")],+ "gemini_cli": [os.path.join(U, ".gemini"), os.path.join(npm, "@google", "gemini-cli")],+ "opencode": [os.path.join(U, ".local", "share", "opencode"), os.path.join(U, ".config", "opencode"),+ os.path.join(npm, "opencode-ai")],+ "aider": [os.path.join(U, ".aider.conf.yml"), os.path.join(U, ".aider"), os.path.join(U, ".aider.chat.history.md")],+ "continue": [os.path.join(U, ".continue")],+ "cline": [os.path.join(U, ".cline"), os.path.join(U, "Documents", "Cline")],+ "chatgpt_desktop": [os.path.join(LA, "Programs", "ChatGPT"), os.path.join(RA, "ChatGPT")],+ "lm_studio": [os.path.join(U, ".lmstudio"), os.path.join(U, ".cache", "lm-studio"), os.path.join(RA, "LM Studio"),+ os.path.join(LA, "Programs", "LM Studio")],+ "jan": [os.path.join(RA, "Jan"), os.path.join(U, "jan")],+ "gpt4all": [os.path.join(LA, "nomic.ai")],+ "msty": [os.path.join(RA, "Msty")],+ "anythingllm": [os.path.join(RA, "anythingllm-desktop")],+ "hf_hub": [os.path.join(U, ".cache", "huggingface", "hub")],+ }+ found = {k: len(_detect(v)) > 0 for k, v in cat.items()}+ if _appx_match(h, r"^OpenAI\.ChatGPT"):+ found["chatgpt_desktop"] = True+ hf = os.path.join(U, ".cache", "huggingface", "hub")+ hf_models = sum(1 for n in (_ls(hf) or []) if n.startswith("models--"))+ return {"present": True, "found": sorted(k for k, v in found.items() if v),+ "absent": sorted(k for k, v in found.items() if not v), "hf_hub_models": hf_models}+++@probe(id="browser.automation", level="L1", family=AI, tier="T0", collect="core")+def browser_automation(h, facts):+ """Browser-automation runtimes on disk: Playwright, camoufox, agent-browser, puppeteer."""+ U, LA, RA = _U(h), _LA(h), _RA(h)+ out = {}+ for label, p in [("playwright", os.path.join(LA, "ms-playwright")), ("playwright_cache", os.path.join(U, ".cache", "ms-playwright")),+ ("puppeteer", os.path.join(U, ".cache", "puppeteer")), ("camoufox", os.path.join(LA, "camoufox")),+ ("agent_browser_browsers", os.path.join(U, ".agent-browser", "browsers"))]:+ names = _ls(p, 50)+ if names is not None:+ out[label] = {"entries": sorted(names)[:20], "mtime": _mtime(p)}+ installs = []+ for loc in ([os.path.join(LA, "hermes", "node", "node_modules", "agent-browser"),+ os.path.join(RA, "npm", "node_modules", "agent-browser")]):+ pj = _read_json(os.path.join(loc, "package.json"))+ if isinstance(pj, dict):+ installs.append({"where": "hermes_bundled" if "hermes" in loc.lower() else "npm_global",+ "version": pj.get("version")})+ if installs:+ out["agent_browser"] = installs+ return {"present": bool(out), **out}+++@probe(id="browser_harness.present", level="L1", family=AI, tier="T0", collect="core")+def browser_harness_present(h, facts):+ """browser-harness config dir and runtime session pid-file count."""+ bh = os.path.join(_U(h), ".config", "browser-harness")+ if not _isdir(bh):+ return None+ pids = glob.glob(os.path.join(bh, "runtime", "*.pid"))+ return {"present": True, "runtime_sessions": len(pids[:500]), "mtime": _mtime(bh)}+++# ---------------- Claude Code++def _claude_json(h):+ """Whitelisted view of ~/.claude.json. Secret-bearing keys are reduced to booleans immediately."""+ def build():+ cj = _read_json(os.path.join(_U(h), ".claude.json"), maxb=20_000_000)+ if not isinstance(cj, dict):+ return None+ projects = cj.get("projects") or {}+ out = {"numStartups": cj.get("numStartups"), "installMethod": cj.get("installMethod"),+ "firstStartTime": _iso(cj.get("firstStartTime")), "autoUpdates": cj.get("autoUpdates"),+ "hasCompletedOnboarding": cj.get("hasCompletedOnboarding"),+ "project_count": len(projects) if isinstance(projects, dict) else 0,+ "global_mcp_servers": sorted((cj.get("mcpServers") or {}).keys()),+ "project_mcp_servers": sorted({n for v in (projects.values() if isinstance(projects, dict) else [])+ if isinstance(v, dict) for n in (v.get("mcpServers") or {}).keys()}),+ "has_oauth_account": "oauthAccount" in cj, "has_primary_api_key": "primaryApiKey" in cj}+ del cj+ return out+ return _memo(h, "claude_json", build)+++@probe(id="claude_code.present", level="L1", family=AI, tier="T0", collect="core")+def claude_code_present(h, facts):+ """Claude Code CLI: ~/.claude home and native claude.exe (with file version)."""+ U = _U(h)+ home = os.path.join(U, ".claude")+ exe = os.path.join(U, ".local", "bin", "claude.exe")+ npm = os.path.join(_RA(h), "npm", "node_modules", "@anthropic-ai", "claude-code")+ if not (_isdir(home) or os.path.exists(exe) or _isdir(npm)):+ return None+ vers = _ls(os.path.join(U, ".local", "share", "claude", "versions")) or []+ return {"present": True, "home": _isdir(home), "native_exe": os.path.exists(exe),+ "exe_version": _file_version(exe), "npm_install": _isdir(npm), "installed_versions": len(vers),+ "home_mtime": _mtime(home)}+++@probe(id="claude_code.config", level="L2", family=AI, tier="T0", collect="core", gate="claude_code.present")+def claude_code_config(h, facts):+ """Claude Code settings (whitelisted keys), permission rule counts, skills/commands/agents/plugins."""+ home = os.path.join(_U(h), ".claude")+ if not _isdir(home):+ return None+ s = _read_json(os.path.join(home, "settings.json")) or {}+ sl = _read_json(os.path.join(home, "settings.local.json")) or {}+ km = _read_json(os.path.join(home, "plugins", "known_marketplaces.json")) or {}+ ip = _read_json(os.path.join(home, "plugins", "installed_plugins.json")) or {}+ plugins = (ip.get("plugins") if isinstance(ip.get("plugins"), dict) else ip) if isinstance(ip, dict) else {}+ return {"present": True, "settings_keys": sorted(s.keys()) if isinstance(s, dict) else [],+ "settings": {k: s.get(k) for k in ("model", "autoUpdatesChannel", "theme", "outputStyle")+ if isinstance(s, dict) and isinstance(s.get(k), (str, bool, int))},+ "hooks_events": sorted((s.get("hooks") or {}).keys()) if isinstance(s, dict) else [],+ "allow_rules": len(((s.get("permissions") or {}).get("allow") or [])) + len(((sl.get("permissions") or {}).get("allow") or [])),+ "skills": len(glob.glob(os.path.join(home, "skills", "*", "SKILL.md"))),+ "commands": len(glob.glob(os.path.join(home, "commands", "*.md"))),+ "agents": len(glob.glob(os.path.join(home, "agents", "*.md"))),+ "plugin_marketplaces": sorted(km.keys()) if isinstance(km, dict) else [],+ "installed_plugins": sorted(plugins.keys())[:30] if isinstance(plugins, dict) else [],+ "claude_md": os.path.exists(os.path.join(home, "CLAUDE.md"))}+++@probe(id="claude_code.claude_json", level="L2", family=AI, tier="T1", collect="core", gate="claude_code.present")+def claude_code_claude_json(h, facts):+ """~/.claude.json whitelist: numStartups, installMethod, firstStartTime, MCP names; secrets as booleans."""+ cj = _claude_json(h)+ if not cj:+ return None+ return {"present": True, **cj}+++def _cc_scan(h):+ def build():+ pdir = os.path.join(_U(h), ".claude", "projects")+ r = {"projects": 0, "sessions": 0, "sessions_30d": 0, "bytes": 0, "user_msgs": 0, "assistant_msgs": 0,+ "skipped_large": 0}+ cutoff = (dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=30)).strftime("%Y-%m-%d")+ models, entry, versions, days = collections.Counter(), collections.Counter(), collections.Counter(), set()+ first = last = None+ titles = []+ files_seen = 0+ for pd in sorted(glob.glob(os.path.join(pdir, "*")))[:500]:+ files = glob.glob(os.path.join(pd, "*.jsonl"))+ if not files:+ continue+ r["projects"] += 1+ for f in files:+ files_seen += 1+ if files_seen > 5000:+ break+ r["sessions"] += 1+ try:+ sz = os.path.getsize(f)+ except OSError:+ continue+ r["bytes"] += sz+ if sz > 60_000_000:+ r["skipped_large"] += 1+ continue+ title = None+ flast = None+ with open(f, encoding="utf-8", errors="replace") as fh:+ for n, line in enumerate(fh):+ if n > 200_000:+ break+ try:+ j = json.loads(line)+ except ValueError:+ continue+ if not isinstance(j, dict):+ continue+ t = j.get("type")+ ts = j.get("timestamp")+ if isinstance(ts, str):+ flast = ts if flast is None or ts > flast else flast+ first = ts if first is None or ts < first else first+ last = ts if last is None or ts > last else last+ days.add(ts[:10])+ if j.get("entrypoint"):+ entry[j["entrypoint"]] += 1+ if j.get("version"):+ versions[j["version"]] += 1+ if t == "user" and not j.get("isMeta") and not j.get("toolUseResult"):+ r["user_msgs"] += 1+ elif t == "assistant":+ r["assistant_msgs"] += 1+ m = (j.get("message") or {}).get("model") if isinstance(j.get("message"), dict) else None+ if m:+ models[m] += 1+ elif t == "custom-title" and j.get("customTitle"):+ title = j["customTitle"]+ elif t == "ai-title" and j.get("aiTitle") and not title:+ title = j["aiTitle"]+ elif t == "summary" and j.get("summary") and not title:+ title = j["summary"]+ if flast and flast[:10] >= cutoff:+ r["sessions_30d"] += 1+ if title:+ titles.append((os.path.getmtime(f), title))+ hist = os.path.join(_U(h), ".claude", "history.jsonl")+ hinfo = None+ if os.path.exists(hist) and os.path.getsize(hist) < 50_000_000:+ hts = []+ with open(hist, encoding="utf-8", errors="replace") as fh:+ for line in fh:+ try:+ v = json.loads(line).get("timestamp")+ except (ValueError, AttributeError):+ continue+ if v:+ hts.append(v)+ hinfo = {"entries": len(hts), "first": _iso(min(hts)) if hts else None, "last": _iso(max(hts)) if hts else None}+ r.update({"first": _iso(first), "last": _iso(last), "active_days": len(days), "models": _top(models),+ "entrypoints": _top(entry), "cli_versions": _top(versions, 5), "prompt_history": hinfo})+ return {"agg": r, "titles": [t for _, t in sorted(titles, reverse=True)]}+ return _memo(h, "cc_scan", build)+++@probe(id="claude_code.sessions", level="L2", family=AI, tier="T1", collect="extended", gate="claude_code.present",+ timeout_ms=5000)+def claude_code_sessions(h, facts):+ """Claude Code JSONL aggregates: session/message counts, date range, active days, models, entrypoints."""+ if not _isdir(os.path.join(_U(h), ".claude", "projects")):+ return None+ agg = _cc_scan(h)["agg"]+ return {"present": agg["sessions"] > 0, **agg}+++@probe(id="claude_code.titles", level="L2", family=AI, tier="T2", collect="deep", gate="claude_code.present")+def claude_code_titles(h, facts):+ """Most recent Claude Code session titles (redacted, truncated). T2 content, opt-in."""+ if not _isdir(os.path.join(_U(h), ".claude", "projects")):+ return None+ t = _cc_scan(h)["titles"]+ return {"present": bool(t), "count_with_title": len(t), "recent": [_redact(x) for x in t[:5]]}+++@probe(id="claude_desktop.present", level="L1", family=AI, tier="T0", collect="core")+def claude_desktop_present(h, facts):+ """Claude desktop app: installed now, or evidence of a past install (Claude-3p dir)."""+ LA, RA = _LA(h), _RA(h)+ uninst = [i["version"] for i in _uninst_match(h, r"^Claude\b")]+ appx = _appx_match(h, r"Claude|Anthropic")+ dirs = {"roaming_Claude": _isdir(os.path.join(RA, "Claude")),+ "local_AnthropicClaude": _isdir(os.path.join(LA, "AnthropicClaude")),+ "local_Claude-3p": _isdir(os.path.join(LA, "Claude-3p")),+ "programdata_Claude": _isdir(os.path.join(_PD(), "Claude"))}+ installed = bool(uninst or appx or dirs["local_AnthropicClaude"] or dirs["roaming_Claude"])+ cfg = _read_json(os.path.join(RA, "Claude", "claude_desktop_config.json"))+ mcp = sorted((cfg.get("mcpServers") or {}).keys()) if isinstance(cfg, dict) else []+ past = dirs["local_Claude-3p"] or dirs["programdata_Claude"]+ if not (installed or past):+ return None+ return {"present": True, "installed": installed, "past_install_evidence": bool(past and not installed),+ "uninstall_versions": uninst, "appx": [f"{p['name']} {p['version']}" for p in appx],+ "dirs": dirs, "mcp_servers": mcp, "claude_3p_mtime": _mtime(os.path.join(LA, "Claude-3p"))}+++# ---------------- Codex++def _codex_home(h):+ return os.environ.get("CODEX_HOME") or os.path.join(_U(h), ".codex")+++@probe(id="codex.present", level="L1", family=AI, tier="T0", collect="core")+def codex_present(h, facts):+ """OpenAI Codex: ~/.codex home and Codex Desktop MSIX (appx repository)."""+ home = _codex_home(h)+ appx = _appx_match(h, r"^OpenAI\.Codex")+ bindir = os.path.join(_LA(h), "OpenAI", "Codex", "bin")+ npm = _isdir(os.path.join(_RA(h), "npm", "node_modules", "@openai", "codex"))+ if not (_isdir(home) or appx or npm):+ return None+ return {"present": True, "home": _isdir(home), "desktop_appx": [{"version": p["version"], "arch": p["arch"]} for p in appx],+ "bundled_cli_builds": len(_ls(bindir) or []), "npm_cli": npm, "home_mtime": _mtime(home)}+++@probe(id="codex.auth_presence", level="L1", family=AI, tier="T3", collect="core")+def codex_auth_presence(h, facts):+ """Codex auth.json presence/size/mtime (never opened). Presence means signed in."""+ return h.meta(os.path.join(_codex_home(h), "auth.json"))+++@probe(id="codex.config", level="L2", family=AI, tier="T0", collect="core", gate="codex.present")+def codex_config(h, facts):+ """Codex config.toml whitelist: model, provider, sandbox, MCP/plugin names. MCP env tables excluded."""+ p = os.path.join(_codex_home(h), "config.toml")+ if not os.path.exists(p) or tomllib is None:+ return None+ try:+ with open(p, "rb") as f:+ c = tomllib.load(f)+ except Exception as e:+ return {"present": True, "error": type(e).__name__}+ return {"present": True, "model": c.get("model"), "model_provider": c.get("model_provider"),+ "model_reasoning_effort": c.get("model_reasoning_effort"), "approval_policy": c.get("approval_policy"),+ "sandbox_mode": c.get("sandbox_mode"), "windows_sandbox": (c.get("windows") or {}).get("sandbox"),+ "profiles": sorted((c.get("profiles") or {}).keys()),+ "model_providers": sorted((c.get("model_providers") or {}).keys()),+ "mcp_servers": sorted((c.get("mcp_servers") or {}).keys()),+ "plugins_enabled": sorted(k for k, v in (c.get("plugins") or {}).items() if isinstance(v, dict) and v.get("enabled")),+ "trusted_projects": len(c.get("projects") or {})}+++@probe(id="codex.usage", level="L2", family=AI, tier="T1", collect="extended", gate="codex.present", timeout_ms=5000)+def codex_usage(h, facts):+ """Codex rollouts (count/bytes/date range/turn models) + state_*.sqlite thread counts + turn durations."""+ home = _codex_home(h)+ if not _isdir(home):+ return None+ files = sorted(glob.glob(os.path.join(home, "sessions", "*", "*", "*", "rollout-*.jsonl")) ++ glob.glob(os.path.join(home, "archived_sessions", "*.jsonl")))[:3000]+ models, efforts, orig, clis = (collections.Counter() for _ in range(4))+ dates, b, turns = [], 0, 0+ for f in files:+ try:+ b += os.path.getsize(f)+ except OSError:+ continue+ m = re.search(r"rollout-(\d{4}-\d\d-\d\dT\d\d-\d\d-\d\d)", f)+ if m:+ dates.append(m.group(1))+ if os.path.getsize(f) > 80_000_000:+ continue+ with open(f, encoding="utf-8", errors="replace") as fh:+ for i, line in enumerate(fh):+ head = line[:120]+ if i == 0 and '"session_meta"' in head:+ try:+ p = json.loads(line)["payload"]+ orig[p.get("originator")] += 1; clis[p.get("cli_version")] += 1+ except Exception:+ pass+ elif '"turn_context"' in head:+ turns += 1+ try:+ p = json.loads(line)["payload"]+ models[p.get("model")] += 1+ efforts[p.get("effort") or p.get("reasoning_effort")] += 1+ except Exception:+ pass+ dates.sort()+ cutoff = (dt.datetime.now() - dt.timedelta(days=30)).strftime("%Y-%m-%d")+ out = {"present": True, "sessions_30d": sum(1 for d in dates if d[:10] >= cutoff),+ "rollouts": {"files": len(files), "bytes": b, "first": dates[0] if dates else None,+ "last": dates[-1] if dates else None, "turn_contexts": turns, "models": _top(models),+ "efforts": _top(efforts), "originators": _top(orig), "cli_versions": _top(clis, 5)}}+ sdb = sorted(glob.glob(os.path.join(home, "state_*.sqlite")), key=lambda p: int(re.search(r"(\d+)", os.path.basename(p)).group(1)))+ if sdb:+ dst = _copy_db(h, sdb[-1], "codex-state")+ if dst:+ try:+ cs = _cols(dst, "threads")+ by_src = collections.Counter()+ for (s,) in _q(dst, "select source from threads"):+ if isinstance(s, str) and s.startswith("{"):+ try:+ s = "subagent" if "subagent" in s.lower() else next(iter(json.loads(s)))+ except Exception:+ s = "object"+ by_src[s] += 1+ a, z = _q(dst, "select min(created_at), max(updated_at) from threads")[0]+ out["threads"] = {"count": sum(by_src.values()), "first": _iso(a), "last": _iso(z), "by_source": dict(by_src),+ "by_provider": dict(_q(dst, "select model_provider, count(*) from threads group by 1")) if "model_provider" in cs else None,+ "by_model": dict(_q(dst, "select model, count(*) from threads group by 1")) if "model" in cs else None,+ "tokens_used_total": _q(dst, "select sum(tokens_used) from threads")[0][0] if "tokens_used" in cs else None}+ try:+ out["threads"]["subagent_edges"] = _q(dst, "select count(*) from thread_spawn_edges")[0][0]+ except Exception:+ pass+ except Exception as e:+ out["threads"] = {"error": type(e).__name__}+ finally:+ _rmdb(dst)+ th = sorted(glob.glob(os.path.join(home, "thread_history_*.sqlite")))+ if th:+ dst = _copy_db(h, th[-1], "codex-th")+ if dst:+ try:+ out["turns"] = {"count": _q(dst, "select count(*) from thread_turns")[0][0],+ "agent_minutes": round((_q(dst, "select sum(duration_ms) from thread_turns")[0][0] or 0) / 60000, 1),+ "items": _q(dst, "select count(*) from thread_items")[0][0]}+ except Exception as e:+ out["turns"] = {"error": type(e).__name__}+ finally:+ _rmdb(dst)+ return out+++@probe(id="codex.extras", level="L2", family=AI, tier="T1", collect="extended", gate="codex.present")+def codex_extras(h, facts):+ """Codex skill/plugin counts, dictation-session count, logs db row count and range."""+ home = _codex_home(h)+ if not _isdir(home):+ return None+ sk = os.path.join(home, "skills")+ pc = os.path.join(home, "plugins", "cache")+ out = {"present": True,+ "skills_system": len(glob.glob(os.path.join(sk, ".system", "*", "SKILL.md"))),+ "skills_user": len(glob.glob(os.path.join(sk, "*", "SKILL.md"))),+ "plugin_cache": sum(len(_ls(m) or []) for m in glob.glob(os.path.join(pc, "*"))),+ "dictation_sessions": len(_ls(os.path.join(home, "dictation-history"), 5000) or []),+ "agents_md": os.path.exists(os.path.join(home, "AGENTS.md"))}+ lg = sorted(glob.glob(os.path.join(home, "logs_*.sqlite")))+ if lg:+ dst = _copy_db(h, lg[-1], "codex-logs")+ if dst:+ try:+ n, a, z = _q(dst, "select count(*), min(ts), max(ts) from logs")[0]+ out["logs_db"] = {"rows": n, "first": _iso(a), "last": _iso(z)}+ except Exception as e:+ out["logs_db"] = {"error": type(e).__name__}+ finally:+ _rmdb(dst)+ return out+++@probe(id="codex.chatgpt_catalog", level="L2", family=AI, tier="T2", collect="deep", gate="codex.present")+def codex_chatgpt_catalog(h, facts):+ """ChatGPT cloud conversations visible to Codex: count/date range by host kind + recent titles (T2)."""+ dev = os.path.join(_codex_home(h), "sqlite", "codex-dev.db")+ if not os.path.exists(dev):+ return None+ dst = _copy_db(h, dev, "codex-dev")+ if not dst:+ return None+ try:+ hosts = dict(_q(dst, "select host_id, host_kind from local_thread_catalog_hosts"))+ rows = _q(dst, "select host_id, source_kind, count(*), min(source_created_at), max(source_created_at) from local_thread_catalog group by 1,2")+ cat = [{"host_kind": hosts.get(hid, "?"), "source_kind": sk, "count": n, "first": _iso(a), "last": _iso(z)}+ for hid, sk, n, a, z in rows]+ titles = [_redact(t) for (t,) in _q(dst, "select display_title from local_thread_catalog where source_kind='chatgpt' order by source_updated_at desc limit 5")]+ except Exception as e:+ return {"present": True, "error": type(e).__name__}+ finally:+ _rmdb(dst)+ return {"present": bool(cat), "catalog": cat, "recent_titles": titles}+++@probe(id="consent.system_ai_models", level="L1", family=AI, tier="T1", collect="core")+def consent_system_ai_models(h, facts):+ """CapabilityAccessManager systemAIModels consent: global value and apps that used on-device AI models."""+ base = r"Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\systemAIModels"+ out = {}+ for label, hive in (("HKCU", winreg.HKEY_CURRENT_USER), ("HKLM", winreg.HKEY_LOCAL_MACHINE)):+ k = _open(hive, base)+ if k is None:+ continue+ apps = used = 0+ for sk in list(_subkeys(k, 500)):+ if sk == "NonPackaged":+ nk = _open(hive, base + "\\NonPackaged")+ subs = ["NonPackaged\\" + s for s in (list(_subkeys(nk, 500)) if nk else [])]+ else:+ subs = [sk]+ for s in subs:+ ak = _open(hive, base + "\\" + s)+ if ak is None:+ continue+ apps += 1+ if (_rv(ak, "LastUsedTimeStart") or 0) > 0:+ used += 1+ out[label] = {"value": _rv(k, "Value"), "apps": apps, "apps_used": used}+ if not out:+ return None+ return {"present": True, **out}+++@probe(id="copilot_cli.present", level="L1", family=AI, tier="T0", collect="core")+def copilot_cli_present(h, facts):+ """GitHub Copilot CLI: ~/.copilot, firstLaunchAt, log/session counts, MCP server names."""+ home = os.path.join(_U(h), ".copilot")+ if not _isdir(home):+ return None+ c = _read_json(os.path.join(home, "config.json"), jsonc=True) or {}+ mc = _read_json(os.path.join(home, "mcp-config.json"), jsonc=True) or {}+ return {"present": True, "first_launch": _iso(c.get("firstLaunchAt")) if isinstance(c, dict) else None,+ "logs": len(_ls(os.path.join(home, "logs")) or []),+ "sessions": len(_ls(os.path.join(home, "session-state")) or []) + len(_ls(os.path.join(home, "history-session-state")) or []),+ "mcp_servers": sorted((mc.get("mcpServers") or {}).keys()) if isinstance(mc, dict) else []}+++@probe(id="copilot_m365.present", level="L1", family=AI, tier="T0", collect="core")+def copilot_m365_present(h, facts):+ """Microsoft 365 Copilot (OfficeHub) and Windows Copilot appx + running process."""+ m365 = _appx_match(h, r"^Microsoft\.MicrosoftOfficeHub$")+ win = _appx_match(h, r"^Microsoft\.Copilot$")+ run = _running(h, r"^m365copilot\.exe$|^copilot\.exe$")+ if not (m365 or win):+ return None+ return {"present": True, "m365_version": m365[0]["version"] if m365 else None,+ "windows_copilot_version": win[0]["version"] if win else None, "running": run}+++@probe(id="cua_driver.present", level="L1", family=AI, tier="T0", collect="core")+def cua_driver_present(h, facts):+ """cua-driver (computer-use): concrete release dirs (junctions fail over ssh), version check, running."""+ home = os.path.join(_U(h), ".cua-driver")+ if not _isdir(home) and not _isdir(os.path.join(_LA(h), "Programs", "Cua")):+ return None+ rel = sorted(_ls(os.path.join(home, "packages", "releases")) or [])+ vc = _read_json(os.path.join(home, "version_check.json")) or {}+ return {"present": True, "releases": rel[-5:], "releases_installed": sorted(_ls(os.path.join(home, ".release_installed")) or [])[-5:],+ "first_install": _mtime(os.path.join(home, ".installation_recorded")),+ "latest_available": vc.get("latest_version") if isinstance(vc, dict) else None,+ "running": bool(_running(h, r"^cua-driver"))}+++@probe(id="docker.model_runner", level="L1", family=AI, tier="T0", collect="core")+def docker_model_runner(h, facts):+ """Docker Model Runner models.json model count."""+ dm = _read_json(os.path.join(_U(h), ".docker", "models", "models.json"))+ if dm is None:+ return None+ lst = dm.get("models", []) if isinstance(dm, dict) else dm+ return {"present": True, "models": len(lst) if isinstance(lst, (list, dict)) else 0}+++# ---------------- Hermes++def _hermes_homes(h):+ def build():+ env = h.l0.get("hermes_home") or os.environ.get("HERMES_HOME") or ""+ LA, U = _LA(h), _U(h)+ cands = []+ for role, p in (("HERMES_HOME", env), ("localappdata", os.path.join(LA, "hermes")),+ ("dot_hermes", os.path.join(U, ".hermes"))):+ if p and _isdir(p) and all(os.path.normcase(p) != os.path.normcase(c["path"]) for c in cands):+ cands.append({"role": role, "path": p, "has_state": os.path.exists(os.path.join(p, "state.db"))})+ primary = next((c for c in cands if c["role"] == "HERMES_HOME"), None) or \+ next((c for c in cands if c["has_state"]), None)+ side = [p for p in glob.glob(os.path.join(LA, "hermes-*")) if _isdir(p)][:50]+ return {"env_set": bool(env), "cands": cands, "primary": primary, "side": side}+ return _memo(h, "hermes_homes", build)+++@probe(id="hermes.present", level="L1", family=AI, tier="T0", collect="core")+def hermes_present(h, facts):+ """Hermes Agent: HERMES_HOME/default homes, MSIX builds, desktop userData. Side homes flagged as operator."""+ hh = _hermes_homes(h)+ appx = _appx_match(h, r"^NousResearch\.|Hermes")+ ud = glob.glob(os.path.join(_RA(h), "Hermes*"))+ homes = []+ for c in hh["cands"]:+ p = c["path"]+ im = None+ try:+ with open(os.path.join(p, ".install_method"), encoding="utf-8", errors="replace") as f:+ im = f.read(40).strip()+ except OSError:+ pass+ ver = None+ pp = os.path.join(p, "hermes-agent", "pyproject.toml")+ if tomllib and os.path.exists(pp):+ try:+ with open(pp, "rb") as f:+ ver = tomllib.load(f).get("project", {}).get("version")+ except Exception:+ pass+ homes.append({"role": c["role"], "primary": hh["primary"] is c, "state_db_bytes": (h.meta(os.path.join(p, "state.db")).get("bytes")),+ "mtime": _mtime(p), "install_method": im, "agent_version": ver,+ "git_checkout": _isdir(os.path.join(p, "hermes-agent", ".git"))})+ if not (homes or appx or ud or hh["side"]):+ return None+ return {"present": True, "HERMES_HOME_set": hh["env_set"], "user_home": hh["primary"] is not None,+ "homes": homes, "side_homes_operator": len(hh["side"]),+ "appx": [{"name": p["name"], "version": p["version"], "arch": p["arch"]} for p in appx],+ "desktop_userdata_dirs": len(ud), "running": sum(_running(h, r"^hermes").values())}+++@probe(id="hermes.auth_presence", level="L1", family=AI, tier="T3", collect="core")+def hermes_auth_presence(h, facts):+ """Primary Hermes home auth.json and .env presence/size (never opened)."""+ p = _hermes_homes(h)["primary"]+ if not p:+ return None+ a, e = h.meta(os.path.join(p["path"], "auth.json")), h.meta(os.path.join(p["path"], ".env"))+ return {"present": a["present"] or e["present"], "auth_json": a, "env": e}+++def _parse_hermes_yaml(p):+ out = {"model": {}, "toolsets": [], "mcp_servers": [], "platform_toolsets": [], "top_level_keys": 0}+ cur = None+ with open(p, encoding="utf-8", errors="replace") as fh:+ for n, raw in enumerate(fh):+ if n > 5000:+ break+ line = raw.rstrip("\n")+ if not line.strip() or line.lstrip().startswith("#"):+ continue+ ind = len(line) - len(line.lstrip(" "))+ s = line.strip()+ if ind == 0:+ out["top_level_keys"] += 1+ cur = s.split(":", 1)[0]+ rest = s.split(":", 1)[1].strip() if ":" in s else ""+ if cur == "model" and rest and rest != "{}":+ out["model"]["default"] = rest.strip("'\"")+ continue+ if cur == "model" and ind == 2 and ":" in s:+ k, v = s.split(":", 1)+ v = v.strip().strip("'\"")+ if k == "base_url":+ m = re.match(r"https?://([^/:]+)", v)+ host = m.group(1) if m else ""+ v = "local" if re.match(r"^(127\.|localhost|0\.0\.0\.0|192\.168\.|10\.)", host) else host+ if k in ("default", "provider", "base_url", "api_mode"):+ out["model"][k] = v+ elif cur == "toolsets" and s.startswith("- "):+ out["toolsets"].append(s[2:].strip("'\""))+ elif cur == "mcp_servers" and ind == 2 and s.endswith(":"):+ out["mcp_servers"].append(s[:-1].strip("'\""))+ elif cur == "platform_toolsets" and ind == 2 and ":" in s:+ out["platform_toolsets"].append(s.split(":", 1)[0])+ return out+++@probe(id="hermes.config", level="L2", family=AI, tier="T0", collect="core", gate="hermes.present")+def hermes_config(h, facts):+ """Primary Hermes config.yaml whitelist: model/provider, base_url host kind, toolsets, MCP names. .env never read."""+ p = _hermes_homes(h)["primary"]+ if not p or not os.path.exists(os.path.join(p["path"], "config.yaml")):+ return None+ try:+ return {"present": True, **_parse_hermes_yaml(os.path.join(p["path"], "config.yaml"))}+ except OSError:+ return None+++@probe(id="hermes.skills", level="L2", family=AI, tier="T1", collect="extended", gate="hermes.present")+def hermes_skills(h, facts):+ """Primary Hermes skills: count, categories, archived; top-used names only if in the bundled catalog."""+ p = _hermes_homes(h)["primary"]+ if not p:+ return None+ sk = os.path.join(p["path"], "skills")+ if not _isdir(sk):+ return None+ total, cats = 0, set()+ for dp, dns, fns in os.walk(sk):+ rel = os.path.relpath(dp, sk)+ dns[:] = [d for d in dns if not d.startswith(".")] if rel.count(os.sep) < 4 else []+ if "SKILL.md" in fns:+ total += 1+ if rel != ".":+ cats.add(rel.split(os.sep)[0])+ if total > 5000:+ break+ catalog = set()+ for base in ("skills", "optional-skills"):+ for f in glob.glob(os.path.join(p["path"], "hermes-agent", base, "**", "SKILL.md"), recursive=True)[:3000]:+ catalog.add(os.path.basename(os.path.dirname(f)))+ top, top_plugin, tracked, used = [], [], 0, 0+ u = _read_json(os.path.join(sk, ".usage.json"))+ if isinstance(u, dict):+ items = u.get("skills", u) if isinstance(u.get("skills", u), dict) else {}+ tracked = len(items)++ def score(v):+ if isinstance(v, dict):+ return v.get("use_count") or v.get("count") or v.get("uses") or 0+ return v if isinstance(v, (int, float)) else 0+ ranked = [k for k, v in sorted(items.items(), key=lambda kv: -score(kv[1])) if score(v) > 0]+ top = [k for k in ranked if k in catalog][:5]+ top_plugin = [k.split(":", 1)[1] for k in ranked if ":" in k][:5]+ used = len(ranked)+ cats = {d for d in (_ls(sk) or []) if not d.startswith(".") and _isdir(os.path.join(sk, d))}+ return {"present": True, "skills": total, "categories": len(cats), "skills_used": used,+ "top_used_plugin": top_plugin,+ "archived": len(glob.glob(os.path.join(sk, ".archive", "*", "SKILL.md"))),+ "usage_tracked": tracked, "top_used_catalog": top, "catalog_available": bool(catalog),+ "plugins": len(_ls(os.path.join(p["path"], "plugins")) or [])}+++def _hermes_db_summary(h, home, tag, titles=False):+ st = os.path.join(home, "state.db")+ if not os.path.exists(st):+ return None+ dst = _copy_db(h, st, tag)+ if not dst:+ return {"error": "copy_failed"}+ try:+ cs = _cols(dst, "sessions")+ if titles:+ if "title" not in cs:+ return {"titles": []}+ rows = _q(dst, "select title from sessions where title is not null and title != '' "+ + ("and parent_session_id is null " if "parent_session_id" in cs else "")+ + "order by started_at desc limit 5")+ return {"titles": [_redact(t) for (t,) in rows]}+ a, z = _q(dst, "select min(started_at), max(coalesce(ended_at, started_at)) from sessions")[0]+ r = {"sessions": _q(dst, "select count(*) from sessions")[0][0],+ "messages": _q(dst, "select count(*) from messages")[0][0],+ "first": _iso(a), "last": _iso(z),+ "by_source": dict(_q(dst, "select coalesce(source,'?'), count(*) from sessions group by 1")),+ "by_month": dict(_q(dst, "select strftime('%Y-%m', started_at, 'unixepoch'), count(*) from sessions group by 1")),+ "by_model": dict(_q(dst, "select coalesce(model,'?'), count(*) from sessions group by 1 order by 2 desc limit 10"))}+ r["sessions_30d"] = _q(dst, "select count(*) from sessions where started_at >= ?", (time.time() - 30 * 86400,))[0][0]+ if "parent_session_id" in cs:+ r["subagent_sessions"] = _q(dst, "select count(*) from sessions where parent_session_id is not null")[0][0]+ if "tool_call_count" in cs:+ r["tool_calls"] = _q(dst, "select sum(tool_call_count) from sessions")[0][0]+ if "estimated_cost_usd" in cs:+ r["est_cost_usd"] = _q(dst, "select round(sum(estimated_cost_usd), 2) from sessions")[0][0]+ try:+ r["model_calls"] = [{"model": m, "provider": p, "calls": c} for m, p, c in+ _q(dst, "select model, billing_provider, sum(api_call_count) from session_model_usage group by 1,2 order by 3 desc limit 10")]+ except Exception:+ pass+ return r+ except Exception as e:+ return {"error": type(e).__name__}+ finally:+ _rmdb(dst)+++@probe(id="hermes.usage", level="L2", family=AI, tier="T1", collect="extended", gate="hermes.present", timeout_ms=5000)+def hermes_usage(h, facts):+ """Primary Hermes state.db (copied with -wal): session/message/tool-call counts, date range, sources, models."""+ hh = _hermes_homes(h)+ p = hh["primary"]+ if not p:+ return None+ r = _hermes_db_summary(h, p["path"], "hermes-state")+ if r is None:+ return None+ prof = []+ for db in glob.glob(os.path.join(p["path"], "profiles", "*", "state.db"))[:20]:+ s = _hermes_db_summary(h, os.path.dirname(db), "hermes-prof") or {}+ prof.append({"sessions": s.get("sessions"), "first": s.get("first"), "last": s.get("last")})+ others = []+ for c in hh["cands"]:+ if c is not p and c["has_state"]:+ s = _hermes_db_summary(h, c["path"], "hermes-other") or {}+ others.append({"role": c["role"], "sessions": s.get("sessions"), "last": s.get("last")})+ return {"present": True, "home_role": p["role"], **r, "profiles": prof, "other_homes": others,+ "side_homes_excluded": len(hh["side"])}+++@probe(id="hermes.titles", level="L2", family=AI, tier="T2", collect="deep", gate="hermes.present")+def hermes_titles(h, facts):+ """Most recent top-level Hermes session titles (redacted). T2 content, opt-in."""+ p = _hermes_homes(h)["primary"]+ if not p:+ return None+ r = _hermes_db_summary(h, p["path"], "hermes-titles", titles=True)+ if not r or not r.get("titles"):+ return None+ return {"present": True, "recent": r["titles"]}+++# ---------------- MCP inventory, NVIDIA, Ollama++BUNDLED_MCP = {"node_repl"}+++@probe(id="l3.mcp_inventory", level="L2", family=AI, tier="T0", collect="core", gate="ai.catalog_absent_checks")+def l3_mcp_inventory(h, facts):+ """Union of whitelisted MCP server names across agents; vendor-bundled servers separated."""+ U, RA = _U(h), _RA(h)+ by = {}+ cj = _claude_json(h)+ if cj:+ by["claude_code"] = sorted(set(cj["global_mcp_servers"]) | set(cj["project_mcp_servers"]))+ cp = os.path.join(_codex_home(h), "config.toml")+ if tomllib and os.path.exists(cp):+ try:+ with open(cp, "rb") as f:+ by["codex"] = sorted((tomllib.load(f).get("mcp_servers") or {}).keys())+ except Exception:+ pass+ for label, path, keys in [("vscode", os.path.join(RA, "Code", "User", "mcp.json"), ("servers", "mcpServers")),+ ("claude_desktop", os.path.join(RA, "Claude", "claude_desktop_config.json"), ("mcpServers",)),+ ("cursor", os.path.join(U, ".cursor", "mcp.json"), ("mcpServers",)),+ ("copilot_cli", os.path.join(U, ".copilot", "mcp-config.json"), ("mcpServers",)),+ ("gemini_cli", os.path.join(U, ".gemini", "settings.json"), ("mcpServers",)),+ ("windsurf", os.path.join(U, ".codeium", "windsurf", "mcp_config.json"), ("mcpServers",))]:+ j = _read_json(path, jsonc=True)+ if isinstance(j, dict):+ for k in keys:+ if isinstance(j.get(k), dict):+ by[label] = sorted(j[k].keys()); break+ p = _hermes_homes(h)["primary"]+ if p and os.path.exists(os.path.join(p["path"], "config.yaml")):+ try:+ by["hermes"] = _parse_hermes_yaml(os.path.join(p["path"], "config.yaml"))["mcp_servers"]+ except OSError:+ pass+ user = sorted({n for v in by.values() for n in v if n not in BUNDLED_MCP})+ bundled = sorted({n for v in by.values() for n in v if n in BUNDLED_MCP})+ nv = _isdir(os.path.join(_LA(h), "NVIDIA Corporation", "NVIDIA App", "McpServer"))+ return {"present": True, "by_agent": {k: v for k, v in by.items() if v}, "user_configured": user,+ "user_configured_total": len(user), "vendor_bundled": bundled + (["nvidia_app_mcp_server"] if nv else [])}+++@probe(id="nvidia.app_mcp_server", level="L1", family=AI, tier="T0", collect="core")+def nvidia_app_mcp_server(h, facts):+ """NVIDIA App McpServer dir + server.json key names and non-secret fields (token never emitted)."""+ mcp = os.path.join(_LA(h), "NVIDIA Corporation", "NVIDIA App", "McpServer")+ if not _isdir(mcp):+ return None+ sj = _read_json(os.path.join(mcp, "server.json"))+ keys, info = [], {}+ if isinstance(sj, dict):+ keys = sorted(sj.keys())+ info = {k: sj[k] for k in ("name", "title", "version") if isinstance(sj.get(k), str)}+ del sj+ return {"present": True, "mtime": _mtime(mcp), "files": len(_ls(mcp) or []), "server_json_keys": keys,+ "has_token_key": "token" in keys, **info}+++def _ollama_models_root(h):+ return os.environ.get("OLLAMA_MODELS") or os.path.join(_U(h), ".ollama", "models")+++@probe(id="ollama.present", level="L1", family=AI, tier="T0", collect="core")+def ollama_present(h, facts):+ """Ollama install (per-user exe, uninstall version), models dir, running process."""+ exe = os.path.join(_LA(h), "Programs", "Ollama", "ollama.exe")+ mroot = _ollama_models_root(h)+ if not (os.path.exists(exe) or _isdir(mroot) or _isdir(os.path.join(_U(h), ".ollama"))):+ return None+ un = _uninst_match(h, r"^Ollama")+ return {"present": True, "exe": os.path.exists(exe), "version": un[0]["version"] if un else _file_version(exe),+ "install_date": un[0]["install_date"] if un else None, "models_dir": _isdir(mroot),+ "OLLAMA_MODELS_set": bool(os.environ.get("OLLAMA_MODELS")), "running": _running(h, r"^ollama")}+++@probe(id="ollama.models", level="L2", family=AI, tier="T0", collect="core", gate="ollama.present")+def ollama_models(h, facts):+ """Ollama model manifests (name, size, pulled date) and blob count."""+ mroot = _ollama_models_root(h)+ man = os.path.join(mroot, "manifests")+ models = []+ for f in glob.glob(os.path.join(man, "*", "*", "*", "*"))[:500]:+ if not os.path.isfile(f):+ continue+ parts = f[len(man) + 1:].split(os.sep)+ j = _read_json(f, maxb=1_000_000) or {}+ size = sum(l.get("size", 0) for l in j.get("layers", []) if isinstance(l, dict)) + ((j.get("config") or {}).get("size", 0) or 0)+ name = ("" if parts[1] == "library" else parts[1] + "/") + parts[2] + ":" + parts[3]+ if parts[0] != "registry.ollama.ai":+ name = parts[0] + "/" + name+ models.append({"name": name, "gb": round(size / 1e9, 2), "pulled": _mtime(f)})+ blobs = _ls(os.path.join(mroot, "blobs"), 20000)+ return {"present": True, "count": len(models), "total_gb": round(sum(m["gb"] for m in models), 2),+ "models": sorted(models, key=lambda m: -m["gb"])[:30], "blobs": len(blobs) if blobs is not None else None,+ "manifests_mtime": _mtime(man)}+++@probe(id="ollama.app_db", level="L2", family=AI, tier="T1", collect="extended", gate="ollama.present")+def ollama_app_db(h, facts):+ """Ollama app db.sqlite: chat/message counts, signed-in flag (users row count only), first-run flags."""+ db = os.path.join(_LA(h), "Ollama", "db.sqlite")+ if not os.path.exists(db):+ return None+ dst = _copy_db(h, db, "ollama")+ if not dst:+ return None+ try:+ out = {"present": True}+ for t in ("chats", "messages"):+ try:+ out[t] = _q(dst, f"select count(*) from {t}")[0][0]+ except Exception:+ out[t] = None+ try:+ out["signed_in"] = _q(dst, "select count(*) from users")[0][0] > 0+ except Exception:+ out["signed_in"] = None+ cs = _cols(dst, "settings")+ want = [c for c in ("has_completed_first_run", "claude_desktop_used", "codex_desktop_used", "turbo_enabled",+ "websearch_enabled", "airplane_mode", "expose") if c in cs]+ if want:+ row = _q(dst, "select %s from settings limit 1" % ",".join(want))+ out["settings"] = dict(zip(want, row[0])) if row else None+ return out+ except Exception as e:+ return {"present": True, "error": type(e).__name__}+ finally:+ _rmdb(dst)+++@probe(id="ollama.logs", level="L2", family=AI, tier="T1", collect="extended", gate="ollama.present")+def ollama_logs(h, facts):+ """Ollama server/app logs: API call counts by path, active days, first/last; decides installed-but-unused."""+ ld = os.path.join(_LA(h), "Ollama")+ files = glob.glob(os.path.join(ld, "*.log"))[:20]+ if not files:+ return None+ rx = re.compile(r'\[GIN\] (\d{4}/\d\d/\d\d) - (\d\d:\d\d:\d\d) \|.*\|\s+(GET|POST|HEAD|DELETE)\s+"([^"?]+)')+ api, days, ver = collections.Counter(), set(), set()+ first = last = None+ for lf in files:+ try:+ with open(lf, encoding="utf-8", errors="replace") as fh:+ for n, line in enumerate(fh):+ if n > 500_000:+ break+ m = rx.search(line)+ if m:+ d = m.group(1) + " " + m.group(2)+ days.add(m.group(1))+ first = d if first is None or d < first else first+ last = d if last is None or d > last else last+ api[m.group(3) + " " + m.group(4)] += 1+ v = re.search(r"version=(\d+\.\d+\.\d+)", line)+ if v:+ ver.add(v.group(1))+ except OSError:+ continue+ infer = sum(v for k, v in api.items() if re.search(r"/api/(chat|generate|embed)|/v1/(chat|completions)", k))+ return {"present": True, "files": len(files), "api_calls": _top(api, 12), "inference_calls": infer,+ "first": first, "last": last, "active_days": len(days), "versions_logged": sorted(ver)}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/apps_dev_devenv.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/apps_dev_devenv.pynew file mode 100644index 00000000000..1bc59cf67f9--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/apps_dev_devenv.py@@ -0,0 +1,663 @@+"""Dev environment probes (dev family, Windows): toolchains, editors, repos.++Registration only at import time. Shared helpers and memoised reads live in apps_dev.+"""+from __future__ import annotations++import collections+import datetime as dt+import glob+import os+import re+import time++from ..registry import probe+from .apps_dev import (DEV, _LA, _PD, _PF, _PF86, _RA, _U, _appx_match, _day, _file_version,+ _is_operator_path, _isdir, _ls, _memo, _mtime, _open, _read_json, _redact, _running, _rv, _spawn,+ _subkeys, _uninst_match, _which, winreg)++# ================================================================== dev++@probe(id="apps.pkg_managers", level="L1", family=DEV, tier="T0", collect="core")+def apps_pkg_managers(h, facts):+ """Package managers present: winget (alias + DesktopAppInstaller), scoop, choco, npm/uv/pipx on PATH."""+ U, LA = _U(h), _LA(h)+ dai = _appx_match(h, r"^Microsoft\.DesktopAppInstaller$")+ out = {"winget": os.path.exists(os.path.join(LA, "Microsoft", "WindowsApps", "winget.exe")),+ "winget_appinstaller_version": dai[0]["version"] if dai else None,+ "scoop": _isdir(os.path.join(U, "scoop")) or _isdir(os.path.join(_PD(), "scoop")),+ "choco": _isdir(os.path.join(_PD(), "chocolatey")),+ "npm": bool(_which("npm")), "uv": bool(_which("uv")), "pipx": bool(_which("pipx")),+ "pnpm": bool(_which("pnpm")), "bun": bool(_which("bun"))}+ return {"present": True, **out}+++@probe(id="dev.devmode_sudo_longpaths", level="L1", family=DEV, tier="T0", collect="core")+def dev_devmode_sudo_longpaths(h, facts):+ """Developer Mode, Windows sudo and LongPathsEnabled registry toggles."""+ dm = _open(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock")+ fs = _open(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\FileSystem")+ su = _open(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Sudo")+ sudo_mode = {0: "disabled", 1: "forceNewWindow", 2: "disableInput", 3: "normal"}+ sv = _rv(su, "Enabled") if su else None+ return {"present": True, "developer_mode": _rv(dm, "AllowDevelopmentWithoutDevLicense") if dm else None,+ "long_paths": _rv(fs, "LongPathsEnabled") if fs else None,+ "sudo": sudo_mode.get(sv, sv) if sv is not None else None}+++@probe(id="dev.docker", level="L1", family=DEV, tier="T0", collect="core")+def dev_docker(h, facts):+ """Docker Desktop install + settings-store.json whitelisted keys (no docker spawn)."""+ inst = os.path.join(_PF(), "Docker", "Docker")+ un = _uninst_match(h, r"^Docker Desktop")+ if not (_isdir(inst) or un):+ return None+ sel = {}+ for p in (os.path.join(_RA(h), "Docker", "settings-store.json"), os.path.join(_RA(h), "Docker", "settings.json")):+ j = _read_json(p)+ if isinstance(j, dict):+ sel = {k: j[k] for k in j if k in ("wslEngineEnabled", "WslEngineEnabled", "autoStart", "AutoStart",+ "kubernetesEnabled", "KubernetesEnabled", "UseContainerdSnapshotter",+ "useContainerdSnapshotter", "memoryMiB", "MemoryMiB", "cpus", "Cpus",+ "EnableDockerAI", "EnableInference")+ and isinstance(j[k], (bool, int, str))}+ break+ cli = os.path.join(inst, "resources", "bin", "docker.exe")+ return {"present": True, "desktop_version": un[0]["version"] if un else None, "install_date": un[0]["install_date"] if un else None,+ "cli_version": (lambda v: None if v in (None, "0.0.0.0") else v)(_file_version(cli)), "settings": sel,+ "service_running": bool(_running(h, r"^com\.docker\.service|^docker desktop"))}+++@probe(id="dev.docker_config_presence", level="L1", family=DEV, tier="T3", collect="core")+def dev_docker_config_presence(h, facts):+ """~/.docker/config.json presence/size (may hold registry auths; never opened)."""+ return h.meta(os.path.join(_U(h), ".docker", "config.json"))+++@probe(id="dev.gh_auth_presence", level="L1", family=DEV, tier="T3", collect="core")+def dev_gh_auth_presence(h, facts):+ """GitHub CLI hosts.yml presence/size (means gh logged in; never opened)."""+ return h.meta(os.path.join(_RA(h), "GitHub CLI", "hosts.yml"))+++@probe(id="dev.git", level="L1", family=DEV, tier="T0", collect="core")+def dev_git(h, facts):+ """git on PATH + Git for Windows version from registry / file version (no spawn)."""+ exe = _which("git")+ k = _open(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\GitForWindows")+ reg_ver = _rv(k, "CurrentVersion") if k else None+ inst = _rv(k, "InstallPath") if k else None+ if not (exe or reg_ver):+ return None+ base = inst or os.path.join(_PF(), "Git")+ flavor = next((d for d in ("clangarm64", "mingw64", "mingw32") if _isdir(os.path.join(base, d))), None)+ return {"present": True, "on_path": bool(exe), "git_for_windows_version": reg_ver,+ "file_version": _file_version(os.path.join(base, "cmd", "git.exe")), "flavor": flavor}+++@probe(id="dev.npm_globals", level="L2", family=DEV, tier="T1", collect="core", gate="apps.pkg_managers")+def dev_npm_globals(h, facts):+ """Global npm packages from %APPDATA%\\npm\\node_modules listing (no `npm root -g` spawn)."""+ root = os.path.join(_RA(h), "npm", "node_modules")+ names = _ls(root, 500)+ if names is None:+ return {"present": False}+ pk = []+ for n in names:+ if n.startswith("@"):+ pk += [f"{n}/{s}" for s in (_ls(os.path.join(root, n), 100) or [])]+ elif not n.startswith("."):+ pk.append(n)+ return {"present": True, "count": len(pk), "packages": sorted(pk)[:80]}+++@probe(id="dev.npmrc_presence", level="L1", family=DEV, tier="T3", collect="core")+def dev_npmrc_presence(h, facts):+ """~/.npmrc presence/size (may hold registry tokens; never opened)."""+ return h.meta(os.path.join(_U(h), ".npmrc"))+++_PATH_TOOLS = [("winget_links", r"\\WinGet\\Links"), ("winget_packages", r"\\WinGet\\Packages"),+ ("windowsapps", r"\\WindowsApps$"), ("git", r"\\Git\\(cmd|bin)"), ("nodejs", r"\\nodejs"),+ ("npm_global", r"\\npm$"), ("python", r"\\Python\d+"), ("uv_or_local_bin", r"\\\.local\\bin|\\uv\\"),+ ("hermes", r"\\hermes\\bin"), ("cargo", r"\\\.cargo\\bin"), ("go", r"\\go\\bin|\\Go\\bin"),+ ("vscode", r"Microsoft VS Code"), ("ollama", r"\\Ollama"), ("cua", r"\\Cua\\"),+ ("docker", r"\\Docker\\"), ("powershell7", r"\\PowerShell\\7"), ("dotnet", r"\\dotnet"),+ ("java", r"\\(jdk|Java|Adoptium)"), ("cuda", r"CUDA"), ("tailscale", r"Tailscale"),+ ("nvidia", r"NVIDIA"), ("gh", r"GitHub CLI"), ("obs", r"obs-studio"), ("ffmpeg", r"ffmpeg")]+++@probe(id="dev.path_entries", level="L1", family=DEV, tier="T0", collect="core")+def dev_path_entries(h, facts):+ """User/machine PATH entry counts and known-tool matches (paths themselves not emitted)."""+ uk = _open(winreg.HKEY_CURRENT_USER, "Environment")+ mk = _open(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")+ up = [x for x in ((_rv(uk, "Path") if uk else "") or "").split(";") if x]+ mp = [x for x in ((_rv(mk, "Path") if mk else "") or "").split(";") if x]+ tools = {"user": sorted({t for t, rx in _PATH_TOOLS for e in up if re.search(rx, e, re.I)}),+ "machine": sorted({t for t, rx in _PATH_TOOLS for e in mp if re.search(rx, e, re.I)})}+ return {"present": True, "user": len(up), "machine": len(mp), "tools": tools}+++@probe(id="dev.pwsh7", level="L1", family=DEV, tier="T0", collect="core")+def dev_pwsh7(h, facts):+ """PowerShell 7 presence and file version (never spawned)."""+ exe = _which("pwsh")+ cand = os.path.join(_PF(), "PowerShell", "7", "pwsh.exe")+ path = exe if exe and "windowsapps" not in exe.lower() else (cand if os.path.exists(cand) else exe)+ if not path:+ return None+ return {"present": True, "on_path": bool(exe), "version": _file_version(path) if os.path.exists(path) else None,+ "store_alias": bool(exe and "windowsapps" in exe.lower())}+++@probe(id="dev.ssh_config", level="L2", family=DEV, tier="T1", collect="core", gate="dev.path_entries")+def dev_ssh_config(h, facts):+ """~/.ssh/config Host alias count and Include count (hostnames not emitted); known_hosts line count."""+ d = os.path.join(_U(h), ".ssh")+ if not _isdir(d):+ return {"present": False}+ cfg = os.path.join(d, "config")+ aliases = includes = lines = 0+ if os.path.exists(cfg):+ with open(cfg, encoding="utf-8", errors="replace") as f:+ for n, line in enumerate(f):+ if n > 5000:+ break+ lines += 1+ m = re.match(r"^\s*Host\s+(.+)$", line, re.I)+ if m:+ aliases += len([x for x in m.group(1).split() if x != "*"])+ if re.match(r"^\s*Include\s", line, re.I):+ includes += 1+ kh = os.path.join(d, "known_hosts")+ khl = None+ if os.path.exists(kh):+ with open(kh, "rb") as f:+ khl = sum(1 for _ in zip(range(100000), f))+ return {"present": True, "config": os.path.exists(cfg), "config_lines": lines, "host_aliases": aliases,+ "includes": includes, "known_hosts_lines": khl}+++_TOOLCHAIN = ["node", "npm", "pnpm", "yarn", "bun", "deno", "nvm", "fnm", "volta", "uv", "py", "pipx", "conda", "poetry",+ "rustc", "cargo", "rustup", "go", "dotnet", "java", "javac", "mvn", "gradle", "cmake", "ninja", "clang",+ "gcc", "zig", "nvcc", "gh", "pwsh", "docker", "kubectl", "terraform", "tailscale", "claude", "codex",+ "hermes", "ollama", "code", "cursor", "windsurf", "zed", "nvim", "vim", "python", "python3"]+++@probe(id="dev.toolchain_presence", level="L1", family=DEV, tier="T0", collect="core")+def dev_toolchain_presence(h, facts):+ """which() for node/python/rust/go/java/native/AI CLIs + off-PATH install dirs. Git Bash by path only."""+ found, stubs = [], []+ for t in _TOOLCHAIN:+ p = _which(t)+ if not p:+ continue+ low = p.lower()+ if "\\windowsapps\\" in low and os.path.basename(low) in ("python.exe", "python3.exe"):+ try:+ if os.path.getsize(p) == 0:+ stubs.append(t); continue+ except OSError:+ pass+ found.append(t)+ U, LA, RA, PF = _U(h), _LA(h), _RA(h), _PF()+ off = {k: _isdir(p) for k, p in [+ ("cargo_home", os.path.join(U, ".cargo")), ("rustup", os.path.join(U, ".rustup")), ("go_root", os.path.join(PF, "Go")),+ ("uv_pythons", os.path.join(RA, "uv", "python")), ("python_org", os.path.join(LA, "Programs", "Python")),+ ("dotnet_sdk", os.path.join(PF, "dotnet", "sdk")), ("java_adoptium", os.path.join(PF, "Eclipse Adoptium")),+ ("java_oracle", os.path.join(PF, "Java")), ("cuda", os.path.join(PF, "NVIDIA GPU Computing Toolkit", "CUDA")),+ ("llvm", os.path.join(PF, "LLVM")), ("android_sdk", os.path.join(LA, "Android", "Sdk")),+ ("miniconda", os.path.join(U, "miniconda3")), ("anaconda", os.path.join(U, "anaconda3")),+ ("pyenv", os.path.join(U, ".pyenv")), ("nvm_windows", os.path.join(RA, "nvm")),+ ("visual_studio", os.path.join(PF, "Microsoft Visual Studio")),+ ("vs_installer", os.path.join(_PF86(), "Microsoft Visual Studio", "Installer"))]}+ return {"present": True, "on_path": found, "store_stubs": stubs,+ "git_bash": os.path.exists(os.path.join(PF, "Git", "bin", "bash.exe")),+ "off_path": sorted(k for k, v in off.items() if v)}+++@probe(id="dev.uv_tools", level="L2", family=DEV, tier="T1", collect="core", gate="dev.toolchain_presence")+def dev_uv_tools(h, facts):+ """uv tools and uv-managed Pythons (dir listing), ~/.local/bin entries; no uv spawn."""+ RA, U = _RA(h), _U(h)+ tools = _ls(os.path.join(RA, "uv", "tools"), 200)+ py = _ls(os.path.join(RA, "uv", "python"), 200)+ lb = _ls(os.path.join(U, ".local", "bin"), 300)+ if tools is None and py is None and lb is None:+ return {"present": False}+ return {"present": True, "tools": sorted(t for t in (tools or []) if not t.startswith("."))[:60],+ "pythons": sorted(p for p in (py or []) if p.startswith(("cpython", "pypy")))[:30],+ "local_bin_count": len(lb or []), "local_bin": sorted(lb or [])[:40]}+++@probe(id="dev.wsl", level="L1", family=DEV, tier="T0", collect="core")+def dev_wsl(h, facts):+ """WSL distros from the HKCU Lxss key (no wsl.exe), vhdx size, WSL package version, .wslconfig presence."""+ base = r"Software\Microsoft\Windows\CurrentVersion\Lxss"+ k = _open(winreg.HKEY_CURRENT_USER, base)+ distros = []+ if k is not None:+ default = _rv(k, "DefaultDistribution")+ for sub in _subkeys(k, 100):+ dk = _open(winreg.HKEY_CURRENT_USER, base + "\\" + sub)+ if dk is None:+ continue+ bp = (_rv(dk, "BasePath") or "").replace("\\\\?\\", "")+ vhd = None+ for fn in ("ext4.vhdx", "ext4.VHDX"):+ try:+ vhd = round(os.path.getsize(os.path.join(bp, fn)) / 2**30, 2); break+ except OSError:+ pass+ distros.append({"name": _rv(dk, "DistributionName"), "version": _rv(dk, "Version"),+ "default": sub == default, "vhdx_gib": vhd})+ un = _uninst_match(h, r"^Windows Subsystem for Linux")+ appx = _appx_match(h, r"^MicrosoftCorporationII\.WindowsSubsystemForLinux$")+ pkg = (un[0]["version"] if un else None) or (appx[0]["version"] if appx else None) or \+ _file_version(os.path.join(_PF(), "WSL", "wsl.exe"), kind="file")+ inbox = os.path.exists(os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "wsl.exe"))+ if not (distros or pkg or k is not None):+ return {"present": False, "inbox_launcher": inbox}+ return {"present": True, "distros": distros, "distro_count": len(distros), "wsl_package_version": pkg,+ "inbox_launcher": inbox, "wslconfig": os.path.exists(os.path.join(_U(h), ".wslconfig"))}+++@probe(id="dev.wt_profiles", level="L2", family=DEV, tier="T1", collect="core", gate="dev.toolchain_presence")+def dev_wt_profiles(h, facts):+ """Windows Terminal settings.json: profile count, source kinds, default kind, customisation counts."""+ LA = _LA(h)+ out = {}+ for label, p in [("stable", os.path.join(LA, "Packages", "Microsoft.WindowsTerminal_8wekyb3d8bbwe", "LocalState", "settings.json")),+ ("preview", os.path.join(LA, "Packages", "Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe", "LocalState", "settings.json")),+ ("unpackaged", os.path.join(LA, "Microsoft", "Windows Terminal", "settings.json"))]:+ j = _read_json(p, jsonc=True)+ if not isinstance(j, dict):+ continue+ profs = j.get("profiles", {})+ plist = profs.get("list", []) if isinstance(profs, dict) else (profs or [])+ dflt = j.get("defaultProfile")+ kinds = collections.Counter()+ dkind = None+ for pr in plist:+ if not isinstance(pr, dict):+ continue+ src = pr.get("source") or ""+ if src:+ kind = src.split(".")[-1]+ else:+ exe = os.path.basename((pr.get("commandline") or "").split(" ")[0]).lower()+ kind = {"powershell.exe": "WindowsPowerShell", "cmd.exe": "CommandPrompt", "pwsh.exe": "PowerShell",+ "wsl.exe": "WSL", "ssh.exe": "ssh"}.get(exe, "custom" if exe else "unknown")+ kinds[kind] += 1+ if pr.get("guid") == dflt:+ dkind = kind+ out[label] = {"profiles": len(plist), "visible": sum(1 for x in plist if isinstance(x, dict) and not x.get("hidden")),+ "kinds": dict(kinds), "default_kind": dkind, "mtime": _mtime(p),+ "actions": len(j.get("actions", []) or []) + len(j.get("keybindings", []) or []),+ "schemes": len(j.get("schemes", []) or []), "theme_set": bool(j.get("theme"))}+ return {"present": bool(out), **out}+++_AI_EXT = re.compile(r"copilot|continue|cline|claude|anthropic|openai|chatgpt|codeium|windsurf|tabnine|amazonq|gemini|cody|sourcegraph|supermaven|roo|kilo|ollama|aider|hermes", re.I)+++def _ext_ids(d):+ j = _read_json(os.path.join(d, "extensions.json"))+ ids = []+ if isinstance(j, list):+ ids = [((e.get("identifier") or {}).get("id") or "").lower() for e in j if isinstance(e, dict)]+ if not any(ids):+ ids = [m.group(1).lower() for x in (_ls(d) or []) for m in [re.match(r"^([\w\-]+\.[\w\-]+)-\d", x)] if m]+ return sorted({i for i in ids if i})+++@probe(id="editor.vscode", level="L2", family=DEV, tier="T2", collect="core", gate="dev.toolchain_presence")+def editor_vscode(h, facts):+ """VS Code-family editors: install, extension ids (AI ones flagged), workspaces opened, MCP/chat state; other editors."""+ U, LA, RA = _U(h), _LA(h), _RA(h)+ eds = {"vscode": ([os.path.join(LA, "Programs", "Microsoft VS Code"), os.path.join(_PF(), "Microsoft VS Code")],+ os.path.join(U, ".vscode", "extensions"), os.path.join(RA, "Code", "User")),+ "vscode_insiders": ([os.path.join(LA, "Programs", "Microsoft VS Code Insiders")],+ os.path.join(U, ".vscode-insiders", "extensions"), os.path.join(RA, "Code - Insiders", "User")),+ "cursor": ([os.path.join(LA, "Programs", "cursor")], os.path.join(U, ".cursor", "extensions"), os.path.join(RA, "Cursor", "User")),+ "windsurf": ([os.path.join(LA, "Programs", "Windsurf")], os.path.join(U, ".windsurf", "extensions"), os.path.join(RA, "Windsurf", "User")),+ "vscodium": ([os.path.join(LA, "Programs", "VSCodium")], os.path.join(U, ".vscode-oss", "extensions"), os.path.join(RA, "VSCodium", "User")),+ "kiro": ([os.path.join(LA, "Programs", "Kiro")], os.path.join(U, ".kiro", "extensions"), os.path.join(RA, "Kiro", "User"))}+ out = {}+ for name, (inst, extd, user) in eds.items():+ installed = any(_isdir(p) for p in inst)+ if not (installed or _isdir(extd) or _isdir(user)):+ continue+ ids = _ext_ids(extd) if _isdir(extd) else []+ e = {"installed": installed, "extensions": len(ids), "extension_ids": ids[:80],+ "ai_extensions": [i for i in ids if _AI_EXT.search(i)]}+ if _isdir(user):+ ws = _ls(os.path.join(user, "workspaceStorage"), 5000)+ e["workspaces_opened"] = len(ws) if ws is not None else 0+ e["settings_json"] = os.path.exists(os.path.join(user, "settings.json"))+ e["keybindings_json"] = os.path.exists(os.path.join(user, "keybindings.json"))+ e["profiles"] = len(_ls(os.path.join(user, "profiles")) or [])+ mj = _read_json(os.path.join(user, "mcp.json"), jsonc=True)+ e["mcp_servers"] = len((mj.get("servers") or mj.get("mcpServers") or {})) if isinstance(mj, dict) else 0+ e["chat_sessions"] = len(glob.glob(os.path.join(user, "globalStorage", "emptyWindowChatSessions", "*"))[:5000]) + \+ len(glob.glob(os.path.join(user, "workspaceStorage", "*", "chatSessions", "*"))[:5000])+ e["user_mtime"] = _mtime(user)+ out[name] = e+ other = {"jetbrains": [x for x in (_ls(os.path.join(RA, "JetBrains")) or []) if re.match(r"^[A-Za-z]+\d{4}\.\d", x)],+ "zed": _isdir(os.path.join(LA, "Zed")) or _isdir(os.path.join(RA, "Zed")),+ "neovim_config": _isdir(os.path.join(LA, "nvim")),+ "vimrc": os.path.exists(os.path.join(U, "_vimrc")) or os.path.exists(os.path.join(U, ".vimrc")),+ "notepadpp": _isdir(os.path.join(_PF(), "Notepad++")),+ "sublime": _isdir(os.path.join(_PF(), "Sublime Text")) or _isdir(os.path.join(RA, "Sublime Text")),+ "visual_studio": [x for x in (_ls(os.path.join(_PF(), "Microsoft Visual Studio")) or []) if x[:2].isdigit()]}+ other = {k: v for k, v in other.items() if v}+ customised = any(e["extensions"] or e.get("settings_json") or e.get("keybindings_json") for e in out.values())+ return {"present": bool(out or other), "extensions": sum(e["extensions"] for e in out.values()),+ "customised": customised, "editors": out, "other": other}+++@probe(id="dev.git_global_config", level="L2", family=DEV, tier="T0", collect="extended", gate="dev.git")+def dev_git_global_config(h, facts):+ """~/.gitconfig parsed without spawn: booleans for identity/credential helper/editor + section counts only."""+ p = os.path.join(_U(h), ".gitconfig")+ if not os.path.exists(p):+ return {"present": False}+ sections, keys = collections.Counter(), set()+ cred_kind = None+ cur = None+ with open(p, encoding="utf-8", errors="replace") as f:+ for n, line in enumerate(f):+ if n > 3000:+ break+ s = line.strip()+ m = re.match(r"^\[\s*([A-Za-z0-9.\-]+)", s)+ if m:+ cur = m.group(1).lower(); sections[cur] += 1; continue+ if "=" in s and cur and not s.startswith(("#", ";")):+ k, v = s.split("=", 1)+ k = k.strip().lower()+ keys.add(f"{cur}.{k}")+ if cur == "credential" and k == "helper" and v.strip():+ lv = v.lower()+ cred_kind = next((n for n, rx in (("gh", r"gh(\.exe)?['\"]?\s+auth"), ("manager", r"manager"),+ ("wincred", r"wincred"), ("store", r"^\s*store"),+ ("cache", r"^\s*cache")) if re.search(rx, lv)), "custom")+ return {"present": True, "bytes": os.path.getsize(p),+ "identity_set": "user.name" in keys and "user.email" in keys,+ "identity_name_set": "user.name" in keys, "identity_email_set": "user.email" in keys,+ "credential_helper": cred_kind, "editor_set": "core.editor" in keys,+ "signing_set": "user.signingkey" in keys or "commit.gpgsign" in keys,+ "sections": dict(sections)}+++def _version_line(txt):+ for l in txt.splitlines():+ l = l.strip()+ if l:+ return _redact(l, 90)+ return None+++@probe(id="dev.toolchain_versions", level="L2", family=DEV, tier="T0", collect="extended", gate="dev.toolchain_presence",+ timeout_ms=12000)+def dev_toolchain_versions(h, facts):+ """--version spawns (parallel, gated on which): node, npm, uv, dotnet, gh, AI CLIs, infra CLIs. Never bash/pwsh."""+ from concurrent.futures import ThreadPoolExecutor+ specs = [("node", ["--version"]), ("npm", ["--version"]), ("uv", ["--version"]), ("gh", ["--version"]),+ ("dotnet", ["--list-sdks"]), ("claude", ["--version"]), ("codex", ["--version"]),+ ("hermes", ["--version"]), ("ollama", ["--version"]), ("docker", ["--version"]),+ ("kubectl", ["version", "--client=true"]), ("tailscale", ["version"]), ("git", ["--version"]),+ ("rustc", ["--version"]), ("go", ["version"]), ("java", ["-version"]), ("deno", ["--version"]),+ ("bun", ["--version"]), ("pnpm", ["--version"])]+ todo = []+ for name, args in specs:+ exe = _which(name)+ if exe and "\\windowsapps\\" not in exe.lower() and os.path.basename(exe).lower() not in ("bash.exe", "pwsh.exe"):+ todo.append((name, [exe] + args))+ env = h.child_env(NO_COLOR="1", HERMES_NO_UPDATE_CHECK="1")++ def one(item):+ name, args = item+ rc, txt, ms = _spawn(h, args, timeout=8, env=env)+ if name == "dotnet":+ sdks = [l.split()[0] for l in txt.splitlines() if re.match(r"^\d", l.strip())]+ rc2, txt2, ms2 = _spawn(h, [args[0], "--list-runtimes"], timeout=8, env=env)+ rts = sorted({" ".join(l.split()[:2]) for l in txt2.splitlines() if re.match(r"^Microsoft\.", l.strip())})+ return name, {"sdks": sdks[:10], "runtimes": rts[:10], "rc": rc, "ms": round(ms + ms2, 1)}+ return name, {"version": _version_line(txt) if rc == 0 or txt else None, "rc": rc, "ms": ms}+ out = {}+ with ThreadPoolExecutor(max_workers=6) as ex:+ for name, r in ex.map(one, todo):+ out[name] = r+ return {"present": bool(out), "tools": out}+++# ---------------- repos (deep)++_SKIP_DIRS = {"node_modules", "appdata", "$recycle.bin", "system volume information", "windows", "program files",+ "program files (x86)", "programdata", "__pycache__", ".venv", "venv", "site-packages", ".cache",+ "cache", "temp", "tmp", "msocache", "recovery", "perflogs", "onedrivetemp"}+++def _is_reparse(e):+ try:+ return bool(e.stat(follow_symlinks=False).st_file_attributes & 0x400) or e.is_symlink()+ except (OSError, AttributeError):+ return e.is_symlink()+++def _repos(h):+ def build():+ deadline = time.perf_counter() + 8.0+ U, LA = _U(h), _LA(h)+ hits, seen = [], set()+ visited = [0]++ def walk(root, maxdepth, skip_appdata=True):+ stack = [(root, 0)]+ while stack and time.perf_counter() < deadline and visited[0] < 60000:+ d, depth = stack.pop()+ visited[0] += 1+ try:+ with os.scandir(d) as it:+ ents = list(zip(range(3000), it))+ except OSError:+ continue+ names = {e.name.lower() for _, e in ents}+ if ".git" in names and os.path.exists(os.path.join(d, ".git", "HEAD")) or \+ (".git" in names and os.path.isfile(os.path.join(d, ".git"))):+ rp = os.path.normcase(os.path.realpath(d))+ if rp not in seen:+ seen.add(rp); hits.append(d)+ continue+ if depth >= maxdepth:+ continue+ for _, e in ents:+ n = e.name.lower()+ if n in _SKIP_DIRS and (skip_appdata or n != "appdata"):+ continue+ try:+ if not e.is_dir(follow_symlinks=False) or _is_reparse(e):+ continue+ except OSError:+ continue+ stack.append((e.path, depth + 1))++ walk(U, 5)+ walk(LA, 3, skip_appdata=False)+ try:+ with os.scandir("C:\\") as it:+ tops = [e.path for e in it if e.is_dir(follow_symlinks=False) and e.name.lower() not in _SKIP_DIRS+ and e.name.lower() != "users" and not _is_reparse(e)]+ except OSError:+ tops = []+ for t in tops[:60]:+ walk(t, 3)+ repos = []+ for d in hits[:200]:+ if _is_operator_path(h, d):+ cls = "operator"+ else:+ rel = os.path.relpath(d, U) if os.path.normcase(d).startswith(os.path.normcase(U)) else None+ first = rel.split(os.sep, 1)[0] if rel else ""+ if os.path.normcase(d).startswith(os.path.normcase(LA)) or first.lower() == "appdata" or first.startswith("."):+ cls = "tool_managed"+ else:+ cls = "user_area"+ gd = os.path.join(d, ".git")+ remotes, branch, head_mtime, local_email = [], None, None, None+ if os.path.isdir(gd):+ try:+ with open(os.path.join(gd, "HEAD"), encoding="utf-8", errors="replace") as f:+ hd = f.read(200).strip()+ branch = hd[16:] if hd.startswith("ref: refs/heads/") else "detached"+ except OSError:+ pass+ head_mtime = _mtime(os.path.join(gd, "logs", "HEAD")) or _mtime(os.path.join(gd, "index"))+ try:+ with open(os.path.join(gd, "config"), encoding="utf-8", errors="replace") as f:+ cfg = f.read(100_000)+ remotes = re.findall(r"^\s*url\s*=\s*(\S+)", cfg, re.M)+ m = re.search(r"^\s*email\s*=\s*(\S+)", cfg, re.M)+ local_email = m.group(1).lower() if m else None+ except OSError:+ pass+ markers = [m for m in ("package.json", "pyproject.toml", "uv.lock", "Cargo.toml", "go.mod", "pom.xml",+ "build.gradle", "Dockerfile", "flake.nix", "AGENTS.md", "CLAUDE.md", ".mcp.json")+ if os.path.exists(os.path.join(d, m))]+ repos.append({"path": d, "class": cls, "branch": branch, "head_mtime": head_mtime, "remotes": remotes,+ "local_email": local_email, "markers": markers})+ return {"repos": repos, "visited_dirs": visited[0], "timed_out": time.perf_counter() >= deadline}+ return _memo(h, "repos", build)+++def _remote_parse(url):+ m = re.match(r"^(?:\w+://)?(?:[^@/]+@)?([^/:]+)[:/]([^/]+)/([^/]+?)(?:\.git)?/?$", url)+ return (m.group(1).lower(), m.group(2), m.group(3)) if m else (None, None, None)+++@probe(id="dev.repos", level="L2", family=DEV, tier="T2", collect="deep", gate="dev.git", timeout_ms=15000)+def dev_repos(h, facts):+ """Bounded repo walk (home d5, LOCALAPPDATA d3, C:\\ tops d3): class, markers, freshness. Repo names are T2."""+ r = _repos(h)+ repos = r["repos"]+ by_cls = collections.Counter(x["class"] for x in repos)+ listed = [{"name": os.path.basename(x["path"]), "class": x["class"], "branch": x["branch"],+ "head_mtime": x["head_mtime"], "markers": x["markers"]} for x in repos if x["class"] != "operator"]+ return {"present": bool(repos), "count": len(repos), "by_class": dict(by_cls), "repos": listed[:50],+ "visited_dirs": r["visited_dirs"], "walk_timed_out": r["timed_out"]}+++@probe(id="dev.repos.remotes", level="L2", family=DEV, tier="T2", collect="deep", gate="dev.git", timeout_ms=15000)+def dev_repos_remotes(h, facts):+ """Remote hosts (counts) and org/repo names for non-operator repos (T2)."""+ hosts, orgs = collections.Counter(), set()+ for x in _repos(h)["repos"]:+ if x["class"] == "operator":+ continue+ for u in x["remotes"]:+ host, org, name = _remote_parse(u)+ if host:+ hosts[host] += 1+ orgs.add(f"{host}/{org}/{name}")+ return {"present": bool(hosts), "hosts": dict(hosts), "repos": sorted(orgs)[:50]}+++def _commits(h):+ def build():+ git = _which("git")+ if not git:+ return None+ ids = set()+ env_ids = os.environ.get("UIL_GIT_IDENTITY", "")+ ids |= {x.strip().lower() for x in env_ids.split(",") if x.strip()}+ gc = os.path.join(_U(h), ".gitconfig")+ try:+ with open(gc, encoding="utf-8", errors="replace") as f:+ ids |= {m.lower() for m in re.findall(r"^\s*email\s*=\s*(\S+)", f.read(100_000), re.M)}+ except OSError:+ pass+ res = {"identity_sources": {"env": bool(env_ids), "global": False, "repo_local": 0}, "by_class": {},+ "hours_local": collections.Counter(), "tz_offsets": collections.Counter(), "weekday": collections.Counter(),+ "month": collections.Counter(), "repos_with_own": {}}+ res["identity_sources"]["global"] = bool(ids - {x.strip().lower() for x in env_ids.split(",") if x.strip()})+ deadline = time.perf_counter() + 10.0+ for x in _repos(h)["repos"]:+ if x["class"] == "operator" or time.perf_counter() > deadline:+ continue+ rid = set(ids)+ if x["local_email"]:+ rid.add(x["local_email"]); res["identity_sources"]["repo_local"] += 1+ rc, txt, _ms = _spawn(h, [git, "-C", x["path"], "log", "--all", "--no-merges", "--format=%ae%x09%an%x09%at%x09%ai",+ "-n", "100000"], timeout=10)+ if rc != 0:+ continue+ mine = total = 0+ for line in txt.splitlines():+ parts = line.split("\t")+ if len(parts) < 4:+ continue+ total += 1+ if parts[0].lower() in rid or parts[1].lower() in rid:+ mine += 1+ try:+ t = dt.datetime.fromtimestamp(int(parts[2]))+ res["hours_local"][t.hour] += 1+ res["weekday"][t.strftime("%a")] += 1+ res["month"][t.strftime("%Y-%m")] += 1+ except (ValueError, OSError):+ pass+ res["tz_offsets"][parts[3].strip()[-5:]] += 1+ c = res["by_class"].setdefault(x["class"], [0, 0])+ c[0] += mine; c[1] += total+ if mine:+ res["repos_with_own"][x["class"]] = res["repos_with_own"].get(x["class"], 0) + 1+ return res+ return _memo(h, "commits", build)+++@probe(id="dev.repos.my_commits", level="L2", family=DEV, tier="T1", collect="deep", gate="dev.git", timeout_ms=20000)+def dev_repos_my_commits(h, facts):+ """Authored-commit counts [mine, all] by repo class, matched on-host to an identity set (never emitted)."""+ c = _commits(h)+ if not c:+ return None+ return {"present": bool(c["by_class"]), "by_class_mine_all": c["by_class"], "identity_sources": c["identity_sources"],+ "repos_with_own_commits": c["repos_with_own"].get("user_area", 0),+ "repos_with_own_commits_by_class": c["repos_with_own"],+ "note": "clone history includes upstream; tool_managed counts are not work on this box"}+++@probe(id="dev.repos.commit_hours", level="L2", family=DEV, tier="T1", collect="deep", gate="dev.git", timeout_ms=20000)+def dev_repos_commit_hours(h, facts):+ """Host-timezone hour histogram, bands, weekday, month and author-TZ offsets of the user's commits."""+ c = _commits(h)+ if not c or not c["hours_local"]:+ return None+ hrs = c["hours_local"]+ bands = {f"{a:02d}-{a + 5:02d}": sum(hrs.get(x, 0) for x in range(a, a + 6)) for a in (0, 6, 12, 18)}+ return {"present": True, "commits": sum(hrs.values()), "hours": {str(k): v for k, v in sorted(hrs.items())},+ "bands": bands, "top_hours": [k for k, _ in hrs.most_common(4)], "weekday": dict(c["weekday"]),+ "month": dict(sorted(c["month"].items())), "tz_offsets": dict(c["tz_offsets"].most_common(6))}+++@probe(id="dev.shell_history", level="L2", family=DEV, tier="T1", collect="deep", gate="dev.path_entries")+def dev_shell_history(h, facts):+ """Shell history files: line count and last-write only (text never emitted)."""+ out = {}+ psr = os.path.join(_RA(h), "Microsoft", "Windows", "PowerShell", "PSReadLine")+ files = [("psreadline:" + f, os.path.join(psr, f)) for f in (_ls(psr) or []) if f.lower().endswith(".txt")]+ files += [(f, os.path.join(_U(h), f)) for f in (".bash_history", ".zsh_history", ".python_history", ".node_repl_history")]+ for label, p in files:+ try:+ st = os.stat(p)+ if st.st_size > 50_000_000:+ out[label] = {"bytes": st.st_size, "lines": None, "mtime": _day(st.st_mtime)}+ continue+ with open(p, "rb") as f:+ n = sum(1 for l in f if l.strip())+ out[label] = {"lines": n, "bytes": st.st_size, "mtime": _day(st.st_mtime)}+ except OSError:+ continue+ return {"present": bool(out), **out}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/browser_files.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/browser_files.pyindex 01e07562d63..12629b54818 100644--- a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/browser_files.py+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/browser_files.py@@ -1,4 +1,4 @@-"""Browser, comms/work and files probes (families: browser, comms_work, files).+"""Browser probes (family: browser); comms_work and files live in browser_files_comms and browser_files_content.Ids follow reports/14-triage.json. Sources are the user's own browser profiles, Explorer registry keysand known folders. Output is counts, histograms and category totals; content-derived values (search@@ -19,12 +19,11 @@ import osimport reimport shutilimport sqlite3-import statisticsimport threadingimport timeimport urllib.parse-from userscan.registry import REGISTRY, probe+from ..registry import REGISTRY, probeWEBKIT_OFFSET = 11644473600FT_OFFSET = 116444736000000000@@ -1225,902 +1224,3 @@ def l3_browser_persona_hints(h, facts):return {"present": True, "developer": dev >= 0.20, "dev_ai_share": round(dev, 3),"gamer": gam >= 0.05, "gaming_share": round(gam, 3),"note": "gaming share is weak evidence; gaming shows up in search themes more than domains"}---# ================================================================ family: comms_work--def _appx(h):- out = {}- for k in h.reg(r"HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel"- r"\Repository\Packages") or []:- parts = k.split("_")- if len(parts) >= 2:- out[parts[0]] = parts[1]- return out---def _prefetch(h):- out = {}- try:- with os.scandir(r"C:\Windows\Prefetch") as it:- for i, e in enumerate(it):- if i > 5000:- break- if e.name.endswith(".pf"):- exe = e.name.rsplit("-", 1)[0].upper()- try:- out[exe] = max(out.get(exe, 0), e.stat().st_mtime)- except OSError:- pass- except OSError:- return {}- return out---def _run_keys(h):- names = []- for p in (r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", r"HKLM\Software\Microsoft\Windows\CurrentVersion\Run"):- names.extend((_reg_values(p) or {}).keys())- return names---def _app_rows(h, table):- L, R = _env("LOCALAPPDATA"), _env("APPDATA")- appx = _cached(h, "appx", _appx)- pf = _cached(h, "prefetch", _prefetch)- run = _cached(h, "runkeys", _run_keys)- out = {}- for aid, (paths, pfs, pkgs, launched_paths) in table.items():- hit = [p for p in paths if os.path.exists(p.format(L=L, R=R))]- ax = {a: appx[a] for a in pkgs if a in appx}- if not hit and not ax:- continue- last = max((pf[e] for e in pfs if e in pf), default=None)- launched = None- if launched_paths:- launched = any(os.path.exists(p.format(L=L, R=R)) and bool(os.listdir(p.format(L=L, R=R)))- for p in launched_paths if _isdir(p.format(L=L, R=R)))- row = {"installed": True, "appx_version": next(iter(ax.values()), None), "prefetch_last": _iso(last),- "autostart": any(re.search(aid.split("_")[0], r, re.I) for r in run)}- if launched is not None:- row["launched"] = launched- row["recent_use"] = bool(last and time.time() - last < 30 * 86400) or bool(launched)- out[aid] = row- return out---COMMS_APPS = {- # id: (install paths, prefetch exes, appx package families, dirs that are non-empty only after first launch)- "slack": ([r"{L}\slack", r"{R}\Slack"], ["SLACK.EXE"], ["91750D7E.Slack"], []),- "teams_new": ([r"{L}\Packages\MSTeams_8wekyb3d8bbwe"], ["MS-TEAMS.EXE", "MSTEAMS.EXE"], ["MSTeams"],- [r"{L}\Packages\MSTeams_8wekyb3d8bbwe\LocalCache\Microsoft\MSTeams"]),- "teams_classic": ([r"{L}\Microsoft\Teams", r"{R}\Microsoft\Teams"], ["TEAMS.EXE"], [], []),- "zoom": ([r"{R}\Zoom", r"{L}\Zoom"], ["ZOOM.EXE"], ["ZoomVideoCommunications"], []),- "telegram": ([r"{R}\Telegram Desktop"], ["TELEGRAM.EXE"], ["TelegramMessengerLLP.TelegramDesktop"], []),- "whatsapp": ([r"{L}\Packages\5319275A.WhatsAppDesktop_cv1g1gvanyjgm", r"{L}\WhatsApp"], ["WHATSAPP.EXE"],- ["5319275A.WhatsAppDesktop"], []),- "signal": ([r"{R}\Signal", r"{L}\Programs\signal-desktop"], ["SIGNAL.EXE"], [], []),- "skype": ([r"{R}\Microsoft\Skype for Desktop"], ["SKYPE.EXE"], ["Microsoft.SkypeApp"], []),- "webex": ([r"{L}\CiscoSpark", r"{L}\WebEx"], ["CISCOCOLLABHOST.EXE", "WEBEX.EXE"], [], []),- "element": ([r"{R}\Element"], ["ELEMENT.EXE"], [], []),- "thunderbird": ([r"{R}\Thunderbird"], ["THUNDERBIRD.EXE"], [], []),- "outlook_classic": ([r"{L}\Microsoft\Outlook"], ["OUTLOOK.EXE"], [], []),- "outlook_new": ([r"{L}\Packages\Microsoft.OutlookForWindows_8wekyb3d8bbwe"], ["OLK.EXE"],- ["Microsoft.OutlookForWindows"], [r"{L}\Microsoft\Olk"]),- "mail_calendar_legacy": ([r"{L}\Packages\microsoft.windowscommunicationsapps_8wekyb3d8bbwe"],- ["HXOUTLOOK.EXE"], ["microsoft.windowscommunicationsapps"], []),-}--NOTES_APPS = {- "notion": ([r"{R}\Notion", r"{L}\Programs\Notion"], ["NOTION.EXE"], [], []),- "notion_calendar": ([r"{R}\Notion Calendar", r"{L}\Programs\cron-web"], ["NOTION CALENDAR.EXE"], [], []),- "obsidian": ([r"{R}\obsidian\obsidian.json", r"{L}\Programs\obsidian"], ["OBSIDIAN.EXE"], [], []),- "onenote": ([r"{L}\Microsoft\OneNote"], ["ONENOTE.EXE"], ["Microsoft.Office.OneNote"], []),-}---@_probe(id="comms.native_apps", level="L1", family="comms_work", tier="T0", collect="core")-def comms_native_apps(h, facts):- """Native comms/mail apps installed (paths, appx) with prefetch last run and first-launch evidence."""- rows = _app_rows(h, COMMS_APPS)- if not rows:- return {"present": False}- return rows---@_probe(id="discord.present", level="L1", family="comms_work", tier="T0", collect="core")-def discord_present(h, facts):- """Discord desktop installed; version from app-* dir; autostart."""- roam, local = h.expand(r"%APPDATA%\discord"), h.expand(r"%LOCALAPPDATA%\Discord")- if not (_isdir(roam) or _isdir(local)):- return {"present": False}- vers = sorted(d[4:] for d in h.list_dir(local, 100) if d.startswith("app-"))- run = _cached(h, "runkeys", _run_keys)- return {"present": True, "version": vers[-1] if vers else None, "autostart": any("discord" in r.lower() for r in run)}---@_probe(id="office.c2r", level="L1", family="comms_work", tier="T0", collect="core")-def office_c2r(h, facts):- """Click-to-Run Office: product ids, version, platform, consumer vs business licence."""- c = _reg_values(r"HKLM\SOFTWARE\Microsoft\Office\ClickToRun\Configuration") or {}- pids = c.get("ProductReleaseIds")- if not pids:- return {"present": False}- kind = ("consumer" if re.search(r"HomePrem|Personal|HomeStudent|Professional2", pids) else- "business" if re.search(r"O365Business|ProPlus|Enterprise", pids) else "other")- return {"present": True, "products": pids, "version": c.get("VersionToReport"), "platform": c.get("Platform"),- "license_kind": kind}---@_probe(id="onedrive.accounts", level="L1", family="comms_work", tier="T0", collect="core")-def onedrive_accounts(h, facts):- """OneDrive client and account slots; signed in only when UserEmail/cid/ConfiguredTenantId is set."""- base = r"HKCU\SOFTWARE\Microsoft\OneDrive"- exe = (h.exists(r"%LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe") or- h.exists(r"C:\Program Files\Microsoft OneDrive\OneDrive.exe"))- keys = [k for k in (h.reg(base + r"\Accounts") or []) if k != "FileCoAuth"]- if not exe and not keys:- return {"present": False}- signed = business = 0- results = []- for k in keys:- v = _reg_values(base + r"\Accounts" + "\\" + k) or {}- is_signed = bool(v.get("UserEmail") or v.get("cid") or v.get("ConfiguredTenantId"))- signed += is_signed- business += bool(is_signed and v.get("ConfiguredTenantId"))- if isinstance(v.get("LastSignInResult"), int):- results.append(hex(v["LastSignInResult"] & 0xFFFFFFFF))- return {"present": True, "client_installed": bool(exe), "version": h.reg(base, "Version"),- "account_slots": len(keys), "signed_in": signed, "business": business,- "last_sign_in_results": sorted(set(results))}---@_probe(id="productivity.notes_apps", level="L1", family="comms_work", tier="T0", collect="core")-def notes_apps(h, facts):- """Notes apps installed: Notion, Notion Calendar, Obsidian, OneNote."""- rows = _app_rows(h, NOTES_APPS)- return {"present": bool(rows), "apps": sorted(rows), "detail": rows}---@_probe(id="work.accounts", level="L1", family="comms_work", tier="T3", collect="core")-def work_accounts(h, facts):- """Counts only: WAM token cache files, AAD broker accounts, MSA-linked logon marker. Files never opened."""- tb = h.count_dir(r"%LOCALAPPDATA%\Microsoft\TokenBroker\Cache", 5000)- aad = h.count_dir(r"%LOCALAPPDATA%\Packages\Microsoft.AAD.BrokerPlugin_cw5n1h2txyewy\AC\TokenBroker\Accounts", 5000)- msa = h.reg(r"HKCU\SOFTWARE\Microsoft\IdentityCRL\UserExtendedProperties")- aad_storage = h.reg(r"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\AAD\Storage") or []- return {"present": True, "tokenbroker_cache_files": max(tb, 0), "aad_broker_accounts": max(aad, 0),- "aad_storage_keys": len(aad_storage), "windows_logon_msa_linked": bool(msa)}---@_probe(id="work.edition_org", level="L1", family="comms_work", tier="T0", collect="core")-def work_edition_org(h, facts):- """Windows edition and whether RegisteredOrganization is set (the org name itself is not emitted)."""- cv = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion"- ed = h.reg(cv, "EditionID")- org = (h.reg(cv, "RegisteredOrganization") or "").strip()- return {"present": bool(ed), "edition": ed, "registered_org_set": bool(org)}---@_probe(id="work.mdm", level="L1", family="comms_work", tier="T0", collect="core")-def work_mdm(h, facts):- """Real MDM enrollments only (UPN, ProviderID MS DM Server, or DiscoveryServiceFullURL)."""- base = r"HKLM\SOFTWARE\Microsoft\Enrollments"- keys = h.reg(base) or []- real = []- for g in keys[:500]:- v = _reg_values(base + "\\" + g) or {}- if v.get("UPN") or v.get("ProviderID") in ("MS DM Server", "WMI_Bridge_Server") or v.get("DiscoveryServiceFullURL"):- real.append({"type": v.get("EnrollmentType"), "provider": v.get("ProviderID")})- omadm = h.reg(r"HKLM\SOFTWARE\Microsoft\Provisioning\OMADM\Accounts") or []- return {"present": True, "real_enrollments": len(real), "enrollments": real[:5], "enrollment_keys_total": len(keys),- "omadm_accounts": len(omadm),- "intune_ime": h.exists(r"C:\Program Files (x86)\Microsoft Intune Management Extension")}---@_probe(id="work.mdm_policy_areas", level="L1", family="comms_work", tier="T0", collect="core")-def work_mdm_policy_areas(h, facts):- """PolicyManager device areas and providers (corroborates MDM; built-in areas exist on every box)."""- areas = h.reg(r"HKLM\SOFTWARE\Microsoft\PolicyManager\current\device") or []- prov = h.reg(r"HKLM\SOFTWARE\Microsoft\PolicyManager\providers") or []- return {"present": True, "device_areas": len(areas), "providers": len(prov), "areas": sorted(areas)[:40]}---@_probe(id="work.policies", level="L1", family="comms_work", tier="T0", collect="core")-def work_policies(h, facts):- """Group-policy keys for browsers/Office/OneDrive/Teams/Slack/Zoom (HKLM+HKCU), value counts only."""- out, apps = {}, {}- for hive in ("HKLM", "HKCU"):- out[hive + "_vendors"] = sorted(h.reg(hive + r"\SOFTWARE\Policies") or [])- for b in (r"Google\Chrome", r"BraveSoftware\Brave", r"Microsoft\Edge", r"Mozilla\Firefox", r"Microsoft\Office",- r"Microsoft\OneDrive", r"Microsoft\Teams", "Slack", "Zoom"):- p = hive + r"\SOFTWARE\Policies" + "\\" + b- v, sk = _reg_values(p), h.reg(p)- if v is not None or sk is not None:- apps[f"{hive}:{b}"] = {"values": len(v or {}), "subkeys": len(sk or [])}- for area in ("TenantRestrictions", "WorkplaceJoin"):- v = _reg_values(hive + r"\SOFTWARE\Policies\Microsoft\Windows" + "\\" + area)- if v:- out.setdefault("windows_area_value_names", {})[f"{hive}:{area}"] = sorted(v)[:10]- configured = {k: v for k, v in apps.items() if v["values"] or v["subkeys"]}- return {"present": True, "app_policies": configured, "app_policy_count": len(configured), **out}---AGENT_RX = re.compile(r"^(IntuneManagementExtension|CSFalcon\w*|ZSATunnel|ZSAService|PanGPS|vpnagent|csc_\w*|Netskope\w*|"- r"stAgent\w*|SentinelAgent|Tanium\w*|CylanceSvc|CcmExec|jamf\w*|Kandji\w*|FortiClient\w*|"- r"NinjaRMM\w*|ManageEngine\w*|LTService|DattoRMM|CiscoAMP|OktaVerify\w*|DuoAuth\w*|Sense|"- r"GlobalProtect\w*|CarbonBlack|CbDefense|elastic-agent|WinCollect|Qualys\w*|Rapid7\w*|"- r"TaniumClient|TrendMicro\w*|SophosMCS\w*|Sophos\w*)$", re.I)---@_probe(id="work.security_agents", level="L1", family="comms_work", tier="T0", collect="core")-def work_security_agents(h, facts):- """EDR/ZTNA/RMM agents from the Services registry (not sc query). Sense (Defender) is reported separately."""- svcs = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Services") or []- hits = sorted(s for s in svcs if AGENT_RX.match(s))- onboard = h.reg(r"HKLM\SOFTWARE\Microsoft\Windows Advanced Threat Protection\Status", "OnboardingState")- return {"present": True, "agents": [s for s in hits if s.lower() != "sense"], "sense_present": "Sense" in hits,- "defender_atp_onboarded": bool(onboard), "services_scanned": len(svcs)}---@_probe(id="work.join_state", level="L2", family="comms_work", tier="T0", collect="extended", gate="work.edition_org",- timeout_ms=5000)-def work_join_state(h, facts):- """Entra/AD/workplace join from dsregcmd /status, with the CloudDomainJoin registry as a cheap cross-check."""- join_info = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\CloudDomainJoin\JoinInfo") or []- domain = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters", "Domain") or ""- txt = h.run(["dsregcmd", "/status"], timeout_ms=5000, text=False) or ""- got = {}- for k in ("AzureAdJoined", "EnterpriseJoined", "DomainJoined", "WorkplaceJoined", "AzureAdPrt"):- m = re.search(rf"^\s*{k}\s*:\s*(\w+)", txt, re.M)- if m:- got[k] = m.group(1).upper() == "YES"- joined = got.get("AzureAdJoined") or got.get("DomainJoined") or got.get("EnterpriseJoined")- return {"present": True, "source": "dsregcmd" if got else "registry",- "azure_ad_joined": got.get("AzureAdJoined", bool(join_info)), "domain_joined": got.get("DomainJoined"),- "enterprise_joined": got.get("EnterpriseJoined"), "workplace_joined": got.get("WorkplaceJoined"),- "azure_ad_prt": got.get("AzureAdPrt"), "cloud_join_info_keys": len(join_info),- "tcpip_domain_set": bool(domain), "state": "joined" if joined else "workgroup"}---@_probe(id="comms.teams_launched", level="L2", family="comms_work", tier="T0", collect="core",- gate="comms.native_apps")-def comms_teams_launched(h, facts):- """New Teams actually started: LocalCache\\Microsoft\\MSTeams exists; tfw = work, tfl = personal profiles."""- b = h.expand(r"%LOCALAPPDATA%\Packages\MSTeams_8wekyb3d8bbwe\LocalCache\Microsoft\MSTeams")- if not _isdir(b):- return {"present": False}- prof = h.list_dir(os.path.join(b, "EBWebView"), 100)- work = sum(1 for p in prof if "tfw" in p.lower())- return {"present": True, "work_profile": work > 0, "work_profiles": work,- "personal_profiles": sum(1 for p in prof if "tfl" in p.lower()),- "log_files": max(h.count_dir(os.path.join(b, "Logs"), 5000), 0)}---def _userassist(h, pattern):- rx = re.compile(pattern, re.I)- base = HKCU_EXPLORER + r"\UserAssist"- rot = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",- "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm")- focus, last = 0, None- for g in h.reg(base) or []:- for n, v in (_reg_values(base + "\\" + g + r"\Count") or {}).items():- if isinstance(v, bytes) and len(v) >= 68 and rx.search(n.translate(rot)):- focus += int.from_bytes(v[12:16], "little") // 1000- t = _ft_iso(int.from_bytes(v[60:68], "little"))- last = max(filter(None, (last, t)), default=None)- return focus, last---@_probe(id="discord.usage", level="L2", family="comms_work", tier="T1", collect="extended", gate="discord.present",- timeout_ms=3000)-def discord_usage(h, facts):- """Signed-in and voice days from renderer_js.log line tags; absent when the app never got past login."""- log = h.expand(r"%APPDATA%\discord\logs\renderer_js.log")- pf = _cached(h, "prefetch", _prefetch).get("DISCORD.EXE")- focus_s, ua_last = _userassist(h, r"discord")- days, gw, rtc = set(), set(), set()- last_gw = last_auth = None- size = 0- if os.path.isfile(log):- size = os.path.getsize(log)- rx = re.compile(r"^\[(\d{4}-\d\d-\d\d) ([\d:.]+)\] \[\w+\]\s+\[?([A-Za-z_]+)")- with open(log, encoding="utf-8", errors="replace") as fh:- if size > 16_000_000:- fh.seek(size - 16_000_000)- for line in fh:- m = rx.match(line)- if not m:- continue- d, tm, tag = m.groups()- days.add(d)- if tag == "GatewaySocket":- gw.add(d)- last_gw = d + "T" + tm[:8]- elif tag.startswith("RTC"):- rtc.add(d)- elif tag == "useAuthWebsocket":- last_auth = d + "T" + tm[:8]- used = bool(gw or rtc)- return {"present": used, "log_days": len(days), "first_day": min(days) if days else None,- "last_day": max(days) if days else None, "gateway_days": len(gw), "rtc_days": len(rtc),- "logged_in_last_session": bool(last_gw and (not last_auth or last_gw > last_auth)),- "on_login_screen": bool(last_auth and (not last_gw or last_auth > last_gw)),- "prefetch_last": _iso(pf), "userassist_focus_s": focus_s, "userassist_last": ua_last,- "log_bytes": size}---@_probe(id="office.usage", level="L2", family="comms_work", tier="T1", collect="core", gate="office.c2r")-def office_usage(h, facts):- """Office identity count, File/Place MRU item counts per app, Office exe prefetch dates (no names or paths)."""- base = r"HKCU\SOFTWARE\Microsoft\Office"- ids = h.reg(base + r"\16.0\Common\Identity\Identities") or []- mru = {}- for app in ("Word", "Excel", "PowerPoint", "OneNote", "Access", "Visio", "Publisher"):- n = 0- for sub in ("File MRU", "Place MRU"):- n += sum(1 for k in (_reg_values(rf"{base}\16.0\{app}\{sub}") or {}) if k.lower().startswith("item"))- for u in h.reg(rf"{base}\16.0\{app}\User MRU") or []:- n += sum(1 for k in (_reg_values(rf"{base}\16.0\{app}\User MRU\{u}\{sub}") or {})- if k.lower().startswith("item"))- if n:- mru[app] = n- pf = _cached(h, "prefetch", _prefetch)- runs = {e: _iso(pf[e]) for e in ("WINWORD.EXE", "EXCEL.EXE", "POWERPNT.EXE", "OUTLOOK.EXE", "ONENOTE.EXE") if e in pf}- return {"present": True, "identities": len(ids), "mru_items": sum(mru.values()), "mru_by_app": mru,- "prefetch_last": runs, "used": bool(mru or runs)}---@_probe(id="obsidian.vaults", level="L2", family="comms_work", tier="T1", collect="extended",- gate="productivity.notes_apps")-def obsidian_vaults(h, facts):- """Obsidian vault count and note counts (vault names and paths are not emitted)."""- j = _load_json(h.expand(r"%APPDATA%\obsidian\obsidian.json"))- vs = (j or {}).get("vaults") or {} if isinstance(j, dict) else {}- if not vs:- return {"present": False}- notes, files, newest = 0, 0, 0-- def on_file(e, s, depth):- nonlocal notes, newest- if e.name.lower().endswith(".md"):- notes += 1- newest = max(newest, s.st_mtime)- for v in list(vs.values())[:10]:- p = v.get("path") if isinstance(v, dict) else None- if p and _isdir(p):- st = _walk(p, max_depth=6, max_entries=30000, budget_s=1.5, on_file=on_file,- skip_dir=lambda n, _p: n in (".obsidian", ".git", ".trash", "node_modules"))- files += st["files"]- return {"present": True, "vaults": len(vs), "open": sum(1 for v in vs.values() if isinstance(v, dict) and v.get("open")),- "notes_md": notes, "files": files, "newest_note": _iso(newest)}---def _history_ids(h):- tot = collections.Counter()- for r in _hist_rows(h):- tot.update(r.get("_ids") or {})- return tot---@_probe(id="browser.history.workspaces", level="L2", family="comms_work", tier="T2", collect="extended",- gate="browser.catalog")-def history_workspaces(h, facts):- """Distinct Discord guild / Slack workspace / Gmail slot / Linear workspace ids seen in history (counts only)."""- rows = _hist_rows(h)- if not rows:- return {"present": False}- ids = _history_ids(h)- return {"discord": ids["discord_guilds"], "slack": ids["slack_workspaces"], "gmail": ids["gmail_slots"],- "linear": ids["linear_workspaces"]}---@_probe(id="browser.history.work_hosts", level="L2", family="comms_work", tier="T2", collect="extended",- gate="browser.catalog")-def history_work_hosts(h, facts):- """Top hostnames for Slack, nousresearch.com, Discord, Notion and Linear (default profiles)."""- hosts = {}- for r in _hist_rows(h):- if not r["is_default_profile"]:- continue- for k, c in (r.get("_work_hosts") or {}).items():- hosts.setdefault(k, collections.Counter()).update(c)- if not hosts:- return {"present": False}- return {"present": True, "hosts": {k: [x for x, _ in v.most_common(5)] for k, v in hosts.items()}}---# ================================================================ family: files--KF_GUIDS = {- "Desktop": "{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}", "Documents": "{FDD39AD0-238F-46AF-ADB4-6C85480369C7}",- "Downloads": "{374DE290-123F-4565-9164-39C4925E467B}", "Pictures": "{33E28130-4E1E-4676-835A-98395C3BC3BB}",- "Videos": "{18989B1D-99B5-455B-841C-AB7C74E4DDFC}", "Music": "{4BD8D571-6D19-48D3-BE97-422220080E43}",- "Screenshots": "{B7BEDE81-DF94-4682-A7D8-57A52620B86F}", "Captures": "{EDC0FE71-98D8-4F4A-B920-C8DC133CB165}",- "CameraRoll": "{AB5FB87B-7CE2-4F83-915D-550846C9537B}",-}---def _known_folders(h):- import ctypes-- class GUID(ctypes.Structure):- _fields_ = [("Data1", ctypes.c_ulong), ("Data2", ctypes.c_ushort), ("Data3", ctypes.c_ushort),- ("Data4", ctypes.c_ubyte * 8)]- out = {}- for name, g in KF_GUIDS.items():- guid = GUID()- ctypes.oledll.ole32.CLSIDFromString(ctypes.c_wchar_p(g), ctypes.byref(guid))- p = ctypes.c_wchar_p()- try:- ctypes.windll.shell32.SHGetKnownFolderPath(ctypes.byref(guid), 0x4000, None, ctypes.byref(p)) # DONT_VERIFY- out[name] = p.value- except OSError:- out[name] = None- finally:- if p:- ctypes.windll.ole32.CoTaskMemFree(p)- return out---def _kf(h, name):- try:- p = _cached(h, "kf", _known_folders).get(name)- except RuntimeError:- p = None- return p or os.path.join(_home(), name)---@_probe(id="files.known_folders", level="L1", family="files", tier="T0", collect="core")-def files_known_folders(h, facts):- """Known-folder paths (SHGetKnownFolderPath, DONT_VERIFY): exists, under profile, under OneDrive."""- kf = _cached(h, "kf", _known_folders)- home = _home().lower()- rows = {n: {"path": _redact(p), "exists": bool(p and _isdir(p)),- "under_profile": bool(p and p.lower().startswith(home)),- "under_onedrive": bool(p and "onedrive" in p.lower())} for n, p in kf.items()}- return {"present": any(r["exists"] for r in rows.values()), "folders": rows}---@_probe(id="sync.other", level="L1", family="files", tier="T0", collect="core")-def sync_other(h, facts):- """Other sync clients: Dropbox, Google Drive, iCloud, Box, MEGA, Proton Drive, pCloud, Syncthing."""- cands = {"dropbox": r"%LOCALAPPDATA%\Dropbox\info.json", "google_drive": r"%LOCALAPPDATA%\Google\DriveFS",- "icloud": r"%LOCALAPPDATA%\Apple Inc\iCloud", "box": r"%LOCALAPPDATA%\Box",- "mega": r"%LOCALAPPDATA%\MEGAsync", "proton_drive": r"%LOCALAPPDATA%\Proton\Proton Drive",- "pcloud": r"%APPDATA%\pCloud", "syncthing": r"%LOCALAPPDATA%\Syncthing"}- found = [k for k, p in cands.items() if h.exists(p)]- roots = h.reg(r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\SyncRootManager") or []- providers = sorted({r.split("!")[0] for r in roots if not r.lower().startswith("onedrive")})- return {"present": bool(found), "clients": found, "sync_root_providers_non_onedrive": providers[:10]}---@_probe(id="jumplists.counts", level="L1", family="files", tier="T0", collect="core")-def jumplists_counts(h, facts):- """Jump-list file counts and sizes (Automatic/CustomDestinations); entries never parsed."""- base = h.expand(r"%APPDATA%\Microsoft\Windows\Recent")- out = {}- for sub in ("AutomaticDestinations", "CustomDestinations"):- n = b = 0- try:- with os.scandir(os.path.join(base, sub)) as it:- for i, e in enumerate(it):- if i >= 5000:- break- if e.is_file():- n += 1- b += e.stat().st_size- except OSError:- continue- out[sub] = {"files": n, "bytes": b}- return {"present": bool(out), **out}---@_probe(id="onedrive.kfm", level="L1", family="files", tier="T0", collect="core", gate="onedrive.accounts")-def onedrive_kfm(h, facts):- """Known-folder move: Desktop/Documents/Pictures redirected into OneDrive (User Shell Folders)."""- usf = _reg_values(HKCU_EXPLORER + r"\User Shell Folders") or {}- red = [k for k in ("Desktop", "Personal", "My Pictures", "My Video", "My Music") if "onedrive" in str(usf.get(k, "")).lower()]- return {"present": True, "redirected": bool(red), "folders": red}---@_probe(id="onedrive.root_size", level="L2", family="files", tier="T0", collect="core", gate="onedrive.accounts")-def onedrive_root_size(h, facts):- """Bounded size of %USERPROFILE%\\OneDrive* without hydrating placeholders."""- home = _home()- roots = {}- for name in h.list_dir(home, 500):- if name.lower().startswith("onedrive") and _isdir(os.path.join(home, name)):- st = _walk(os.path.join(home, name), max_depth=6, max_entries=50000, budget_s=2.0)- roots[name] = {k: st[k] for k in ("files", "bytes", "cloud_placeholders", "truncated")}- if not roots:- return {"present": False}- return {"present": True, "roots": roots, "files": sum(r["files"] for r in roots.values()),- "bytes": sum(r["bytes"] for r in roots.values())}---def _recent(h):- rec = h.expand(r"%APPDATA%\Microsoft\Windows\Recent")- now = time.time()- ext, ages, mts = collections.Counter(), collections.Counter(), []- operator = 0- try:- it = os.scandir(rec)- except OSError:- return None- with it:- for i, e in enumerate(it):- if i >= 20000:- break- if not e.name.lower().endswith(".lnk") or not e.is_file():- continue- if OPERATOR_DEEP_RX.search(e.name) or OPERATOR_RX.match(e.name[:-4]):- operator += 1- continue- try:- s = e.stat()- except OSError:- continue- mts.append(s.st_mtime)- ages[_age_bucket(now - s.st_mtime)] += 1- x = os.path.splitext(e.name[:-4])[1].lower()- ext[x if re.fullmatch(r"\.[a-z0-9]{1,5}", x or "") else "(folder_or_none)"] += 1- return {"count": len(mts), "operator_filtered": operator, "ext": ext, "ages": ages, "mts": mts}---@_probe(id="files.recent_lnk", level="L2", family="files", tier="T1", collect="core", gate="files.known_folders")-def files_recent_lnk(h, facts):- """Recent .lnk count, date range, folder vs file split, target extension counts (no names)."""- r = _recent(h)- if not r or not r["count"]:- return {"present": False}- now = time.time()- mts = r["mts"]- folders = r["ext"].get("(folder_or_none)", 0)- return {"present": True, "count": r["count"], "operator_filtered": r["operator_filtered"],- "oldest": _iso(min(mts)), "newest": _iso(max(mts)), "folder_or_none": folders,- "files": r["count"] - folders, "target_ext_top": dict(r["ext"].most_common(10)),- "age_mtime": {k: r["ages"].get(k, 0) for k in AGE_KEYS},- "active_days_30d": len({time.strftime("%Y-%m-%d", time.localtime(t)) for t in mts if now - t < 30 * 86400})}---SHOT_NAME = re.compile(r"^(screenshot|screen shot|capture|snip|screen ?recording|scr_|shot_)", re.I)-IMG_EXT = {".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp", ".jxr", ".heic", ".tif", ".tiff"}-VIDEO_EXT = {".mp4", ".mkv", ".avi", ".mov", ".webm", ".wmv", ".m4v"}-AUDIO_EXT = {".mp3", ".flac", ".wav", ".m4a", ".aac", ".ogg", ".opus"}-DOC_EXT = {".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".txt", ".md", ".csv", ".odt", ".rtf"}-CODE_EXT = {".py", ".js", ".ts", ".json", ".toml", ".yaml", ".yml", ".sh", ".ps1", ".bat", ".rs", ".go", ".c", ".cpp",- ".h", ".java", ".ipynb", ".log", ".rst", ".html", ".css"}-INSTALLER_EXT = {".exe", ".msi", ".msix", ".appx", ".msixbundle", ".appxbundle"}-ARCHIVE_EXT = {".zip", ".7z", ".rar", ".tar", ".gz", ".iso", ".xz", ".bz2", ".zst"}---def _kind(ext):- for k, s in (("image", IMG_EXT), ("video", VIDEO_EXT), ("audio", AUDIO_EXT), ("document", DOC_EXT),- ("code", CODE_EXT), ("installer", INSTALLER_EXT), ("archive", ARCHIVE_EXT)):- if ext in s:- return k- return "other"---def _composition(h):- now = time.time()- deadline = time.perf_counter() + 8.0- shots = []- seen = set()- res = {}- for name in ("Desktop", "Documents", "Downloads", "Pictures", "Videos", "Music"):- p = _kf(h, name)- ext_n, ext_b, kind_b = collections.Counter(), collections.Counter(), collections.Counter()- ages, years = collections.Counter(), collections.Counter()- dup = [0]-- def on_file(e, s, depth, label=name):- ext = os.path.splitext(e.name)[1].lower() or "(none)"- if len(ext) > 12:- ext = "(long)"- ext_n[ext] += 1- ext_b[ext] += s.st_size- kind_b[_kind(ext)] += s.st_size- ages[_age_bucket(now - s.st_mtime)] += 1- years[time.localtime(s.st_mtime).tm_year] += 1- if re.search(r"\(\d+\)(\.[^.]+)?$", e.name):- dup[0] += 1- if ext in IMG_EXT or ext in (".mp4", ".mkv"):- low = e.path.lower()- if (SHOT_NAME.match(e.name) or any(s_ in low for s_ in ("\\screenshots\\", "\\captures\\", "\\sharex\\",- "\\ansel\\"))) and low not in seen:- seen.add(low)- shots.append((s.st_mtime, label, ext in IMG_EXT))- budget = max(0.2, min(3.0, deadline - time.perf_counter()))- st = _walk(p, max_depth=6, max_entries=100000, budget_s=budget, on_file=on_file,- skip_dir=lambda n, path: bool(OPERATOR_DEEP_RX.search(n)))- top = {"files": 0, "dirs": 0, "shortcuts": 0}- for e in h.list_dir(p, 5000):- full = os.path.join(p, e)- if e.lower() == "desktop.ini":- continue- if _isdir(full):- top["dirs"] += 1- else:- top["files"] += 1- top["shortcuts"] += e.lower().endswith((".lnk", ".url"))- res[name] = {"files": st["files"], "dirs": st["dirs"], "bytes": st["bytes"], "truncated": st["truncated"],- "depth": 6, "top_level": top, "ext_top_by_count": dict(ext_n.most_common(10)),- "ext_top_by_bytes": dict(ext_b.most_common(6)), "kind_bytes": dict(kind_b),- "age_mtime": {k: ages.get(k, 0) for k in AGE_KEYS},- "oldest_year": min(years) if years else None, "newest_year": max(years) if years else None,- "dup_suffix_files": dup[0], "ms": st.get("ms")}- return {"folders": res, "shots": shots}---@_probe(id="files.composition", level="L2", family="files", tier="T1", collect="extended", gate="files.known_folders",- timeout_ms=9000)-def files_composition(h, facts):- """Per known folder: files, bytes, extension/kind/age histograms, depth <= 6 (no file names)."""- c = _cached(h, "composition", _composition)- folders = c["folders"]- kind = collections.Counter()- for f in folders.values():- kind.update(f["kind_bytes"])- tot = sum(kind.values()) or 1- dl = folders.get("Downloads", {})- old = sum(dl.get("age_mtime", {}).get(k, 0) for k in ("lt_1y", "lt_2y", "ge_2y"))- return {"present": True, "folders": folders, "total_bytes": sum(f["bytes"] for f in folders.values()),- "byte_share": {k: round(v / tot, 3) for k, v in kind.most_common()},- "downloads_older_90d_share": round(old / dl["files"], 3) if dl.get("files") else None,- "shared_block_ms": _cache_ms(h, "composition")}---@_probe(id="files.screenshots", level="L2", family="files", tier="T1", collect="extended", gate="files.known_folders",- timeout_ms=9000)-def files_screenshots(h, facts):- """Screenshot/capture count, active days, cadence and local hour/weekday histograms (from the composition walk)."""- c = _cached(h, "composition", _composition)- imgs = sorted(t for t, _l, is_img in c["shots"] if is_img)- vids = sum(1 for _t, _l, is_img in c["shots"] if not is_img)- shots_kf = _kf(h, "Screenshots")- if not imgs:- return {"present": False}- now = time.time()- days = {time.strftime("%Y-%m-%d", time.localtime(t)) for t in imgs}- gaps = [(b - a) / 3600 for a, b in zip(imgs, imgs[1:])]- return {"present": True, "count": len(imgs), "video_captures": vids,- "by_folder": dict(collections.Counter(l for _t, l, i in c["shots"] if i)),- "screenshots_kf_exists": _isdir(shots_kf), "first": _iso(imgs[0]), "last": _iso(imgs[-1]),- "last_30d": sum(1 for t in imgs if now - t < 30 * 86400), "active_days": len(days),- "per_active_day": round(len(imgs) / len(days), 2),- "median_gap_h": round(statistics.median(gaps), 2) if gaps else None,- "hours": [sum(1 for t in imgs if time.localtime(t).tm_hour == hr) for hr in range(24)],- "weekdays_mon0": [sum(1 for t in imgs if time.localtime(t).tm_wday == d) for d in range(7)]}---def _user_sid(h):- home = _home().lower()- base = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"- for sid in h.reg(base) or []:- if sid.startswith("S-1-5-21-") and (h.reg(base + "\\" + sid, "ProfileImagePath") or "").lower() == home:- return sid- return None---@_probe(id="files.clutter", level="L2", family="files", tier="T1", collect="extended", gate="files.known_folders",- timeout_ms=6000)-def files_clutter(h, facts):- """Recycle Bin, TEMP and thumbnail-cache sizes; Desktop item count; Windows Search index size."""- out = {"present": True}- sid = _user_sid(h)- rb = rf"C:\$Recycle.Bin\{sid}" if sid else None- if rb and _isdir(rb):- items = [0]-- def cb(e, s, depth):- if depth == 0 and e.name.startswith("$R"):- items[0] += 1- st = _walk(rb, max_depth=6, max_entries=100000, budget_s=2.0, on_file=cb)- out["recycle_bin"] = {"items": items[0], "files": st["files"], "bytes": st["bytes"], "truncated": st["truncated"]}- tmp = _env("TEMP")- if tmp and _isdir(tmp):- st = _walk(tmp, max_depth=5, max_entries=100000, budget_s=2.0,- skip_dir=lambda n, p: n == "userscan" or bool(OPERATOR_DEEP_RX.search(n)))- out["temp_files"], out["temp_bytes"], out["temp_truncated"] = st["files"], st["bytes"], st["truncated"]- ex = h.expand(r"%LOCALAPPDATA%\Microsoft\Windows\Explorer")- tb = sum((h.meta(os.path.join(ex, n)).get("bytes") or 0) for n in h.list_dir(ex, 500)- if n.lower().startswith(("thumbcache_", "iconcache_")))- out["thumbcache_bytes"] = tb- idx = h.meta(r"C:\ProgramData\Microsoft\Search\Data\Applications\Windows\Windows.db")- out["search_index_bytes"] = idx.get("bytes")- desk = _kf(h, "Desktop")- names = [n for n in h.list_dir(desk, 5000) if n.lower() != "desktop.ini"]- out["desktop_items"] = len(names)- out["desktop_shortcuts"] = sum(1 for n in names if n.lower().endswith((".lnk", ".url")))- return out---def _mru_counts(path):- try:- subs = []- with _reg_key(path) as k:- wr = _winreg()- i = 0- while i < 2000:- try:- subs.append(wr.EnumKey(k, i))- except OSError:- break- i += 1- except OSError:- return None- per = {}- for sk in subs:- v = _reg_values(path + "\\" + sk) or {}- per[sk.lower()] = sum(1 for n in v if n.isdigit())- return per---EXT_OK = re.compile(r"^\.?[a-z0-9]{1,6}$|^folder$|^\*$")---def _bucket(per):- clean, odd = collections.Counter(), 0- for e, c in per.items():- if EXT_OK.match(e):- clean[e] += c- else:- odd += 1- clean["(url_or_odd)"] += c- return clean, odd---def _utf16_first(b):- try:- return b.decode("utf-16le", errors="ignore").split("\x00", 1)[0]- except Exception:- return None---@_probe(id="files.opensave_mru", level="L2", family="files", tier="T1", collect="extended", gate="files.known_folders")-def files_opensave_mru(h, facts):- """File-dialog history: per-extension item counts and the app exe names that used the dialog (no paths)."""- cd = HKCU_EXPLORER + r"\ComDlg32"- per = _mru_counts(cd + r"\OpenSavePidlMRU")- apps = collections.Counter()- for sub in ("LastVisitedPidlMRU", "CIDSizeMRU"):- for n, v in (_reg_values(cd + "\\" + sub) or {}).items():- if n.isdigit() and isinstance(v, bytes):- a = _utf16_first(v)- if a and re.fullmatch(r"[\w .\-]{1,64}\.exe", a, re.I):- apps[a.lower()] += 1- if per is None and not apps:- return {"present": False}- clean, odd = _bucket({k: v for k, v in (per or {}).items() if k != "*"})- return {"present": True, "all_items": (per or {}).get("*"), "ext_top": dict(clean.most_common(12)),- "odd_keys_redacted": odd, "apps": dict(apps.most_common(12)),- "last_write": _reg_lastwrite(cd + r"\OpenSavePidlMRU")}---@_probe(id="files.recentdocs", level="L2", family="files", tier="T1", collect="extended", gate="files.known_folders")-def files_recentdocs(h, facts):- """Explorer RecentDocs: total items and per-extension counts; URL/search-built subkeys bucketed."""- path = HKCU_EXPLORER + r"\RecentDocs"- top = _reg_values(path)- if top is None:- return {"present": False}- per = _mru_counts(path) or {}- clean, odd = _bucket(per)- return {"present": True, "total_items": sum(1 for n in top if n.isdigit()), "ext_subkeys": len(per),- "odd_keys_redacted": odd, "ext_top": dict(clean.most_common(12)), "last_write": _reg_lastwrite(path)}---def _reg_domain(host):- if not host or re.fullmatch(r"[\d.]+", host):- return host- parts = host.split(".")- if len(parts) >= 3 and parts[-2] in ("co", "com", "org", "net", "ac", "gov") and len(parts[-1]) == 2:- return ".".join(parts[-3:])- return ".".join(parts[-2:])---@_probe(id="files.download_sources", level="L2", family="files", tier="T1", collect="deep", gate="files.known_folders",- timeout_ms=6000)-def files_download_sources(h, facts):- """Zone.Identifier ADS in Downloads (depth <= 2): zone counts and source-site category counts (no hosts)."""- root = _kf(h, "Downloads")- if not _isdir(root):- return {"present": False}- zone, cats, ext_cat = collections.Counter(), collections.Counter(), collections.Counter()- n = with_ads = no_host = 0- deadline = time.perf_counter() + 5.0- stack, trunc = [(root, 0)], None- while stack:- d, depth = stack.pop()- try:- entries = list(os.scandir(d))- except OSError:- continue- for e in entries:- if e.is_dir(follow_symlinks=False):- if depth + 1 < 2 and not OPERATOR_DEEP_RX.search(e.name):- stack.append((e.path, depth + 1))- continue- n += 1- if n > 5000 or time.perf_counter() > deadline:- trunc = "cap"- stack.clear()- break- try:- with open(e.path + ":Zone.Identifier", "r", encoding="utf-8", errors="replace") as f:- txt = f.read(4096)- except OSError:- continue- with_ads += 1- kv = dict(line.split("=", 1) for line in txt.splitlines() if "=" in line)- zone[kv.get("ZoneId", "?").strip()] += 1- url = (kv.get("HostUrl") or "").strip()- if not url or url.startswith("about:"):- no_host += 1- continue- host, _ = _host_of(url)- c = _categorize(_reg_domain(host)) if host else "other"- c = "sensitive" if c in SENSITIVE_CATS else c- cats[c] += 1- ext_cat[f"{c}:{os.path.splitext(e.name)[1].lower() or '(none)'}"] += 1- return {"present": True, "files_scanned": n, "depth": 2, "truncated": trunc, "with_zone_identifier": with_ads,- "no_host_url": no_host, "zones": dict(zone), "source_categories": dict(cats.most_common()),- "category_ext_top": dict(ext_cat.most_common(10))}---STANDARD_DIRS = {"appdata", "desktop", "documents", "downloads", "pictures", "videos", "music", "onedrive", "contacts",- "favorites", "links", "saved games", "searches", "3d objects"}---@_probe(id="files.profile_size_walk", level="L2", family="files", tier="T2", collect="deep", gate="files.known_folders",- timeout_ms=30000)-def files_profile_size_walk(h, facts):- """Size of each top-level profile dir (depth <= 10, 300k entries/dir, 25 s total); operator dirs excluded."""- home = _home()- deadline = time.perf_counter() + 25.0- rows = []- loose = 0- try:- entries = list(os.scandir(home))- except OSError:- return {"present": False}- for e in entries:- try:- s = e.stat(follow_symlinks=False)- except OSError:- continue- if not e.is_dir(follow_symlinks=False):- loose += 1- continue- if getattr(s, "st_file_attributes", 0) & FILE_ATTRIBUTE_REPARSE_POINT:- continue- low = e.name.lower()- cls = ("operator" if OPERATOR_RX.match(e.name) else "dot" if low.startswith(".") else- "standard" if low in STANDARD_DIRS else "custom")- if cls == "operator":- rows.append({"name": e.name, "class": cls, "bytes": 0, "skipped": "operator"})- continue- remain = deadline - time.perf_counter()- if remain <= 0:- rows.append({"name": e.name, "class": cls, "bytes": 0, "skipped": "budget"})- continue- st = _walk(e.path, max_depth=10, max_entries=300000,- budget_s=min(12.0 if low == "appdata" else 4.0, remain))- rows.append({"name": e.name, "class": cls, "bytes": st["bytes"], "files": st["files"],- "truncated": st["truncated"], "ms": st.get("ms")})- rows.sort(key=lambda r: -r["bytes"])- shown = 0- for r in rows:- if r["class"] == "custom":- shown += 1- if shown > 5:- r["name"] = f"custom#{shown}"- cls = collections.Counter(r["class"] for r in rows)- return {"present": True, "top_dirs": [r for r in rows if r["class"] != "operator"][:12],- "class_counts": dict(cls), "custom_root_dirs": cls.get("custom", 0),- "operator_dirs_excluded": cls.get("operator", 0),- "custom_bytes": sum(r["bytes"] for r in rows if r["class"] == "custom"),- "total_bytes": sum(r["bytes"] for r in rows), "loose_root_files": loose,- "truncated_dirs": sum(1 for r in rows if r.get("truncated") or r.get("skipped") == "budget")}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/browser_files_comms.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/browser_files_comms.pynew file mode 100644index 00000000000..818c78828fe--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/browser_files_comms.py@@ -0,0 +1,415 @@+"""Comms and work probes (comms_work family, Windows).++Registration only at import time. Shared helpers and caches live in browser_files.+"""+from __future__ import annotations++import collections+import os+import re+import time++from .browser_files import (HKCU_EXPLORER, _cached, _env, _ft_iso, _hist_rows, _isdir, _iso,+ _load_json, _probe, _reg_values, _walk)++# ================================================================ family: comms_work++def _appx(h):+ out = {}+ for k in h.reg(r"HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel"+ r"\Repository\Packages") or []:+ parts = k.split("_")+ if len(parts) >= 2:+ out[parts[0]] = parts[1]+ return out+++def _prefetch(h):+ out = {}+ try:+ with os.scandir(r"C:\Windows\Prefetch") as it:+ for i, e in enumerate(it):+ if i > 5000:+ break+ if e.name.endswith(".pf"):+ exe = e.name.rsplit("-", 1)[0].upper()+ try:+ out[exe] = max(out.get(exe, 0), e.stat().st_mtime)+ except OSError:+ pass+ except OSError:+ return {}+ return out+++def _run_keys(h):+ names = []+ for p in (r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", r"HKLM\Software\Microsoft\Windows\CurrentVersion\Run"):+ names.extend((_reg_values(p) or {}).keys())+ return names+++def _app_rows(h, table):+ L, R = _env("LOCALAPPDATA"), _env("APPDATA")+ appx = _cached(h, "appx", _appx)+ pf = _cached(h, "prefetch", _prefetch)+ run = _cached(h, "runkeys", _run_keys)+ out = {}+ for aid, (paths, pfs, pkgs, launched_paths) in table.items():+ hit = [p for p in paths if os.path.exists(p.format(L=L, R=R))]+ ax = {a: appx[a] for a in pkgs if a in appx}+ if not hit and not ax:+ continue+ last = max((pf[e] for e in pfs if e in pf), default=None)+ launched = None+ if launched_paths:+ launched = any(os.path.exists(p.format(L=L, R=R)) and bool(os.listdir(p.format(L=L, R=R)))+ for p in launched_paths if _isdir(p.format(L=L, R=R)))+ row = {"installed": True, "appx_version": next(iter(ax.values()), None), "prefetch_last": _iso(last),+ "autostart": any(re.search(aid.split("_")[0], r, re.I) for r in run)}+ if launched is not None:+ row["launched"] = launched+ row["recent_use"] = bool(last and time.time() - last < 30 * 86400) or bool(launched)+ out[aid] = row+ return out+++COMMS_APPS = {+ # id: (install paths, prefetch exes, appx package families, dirs that are non-empty only after first launch)+ "slack": ([r"{L}\slack", r"{R}\Slack"], ["SLACK.EXE"], ["91750D7E.Slack"], []),+ "teams_new": ([r"{L}\Packages\MSTeams_8wekyb3d8bbwe"], ["MS-TEAMS.EXE", "MSTEAMS.EXE"], ["MSTeams"],+ [r"{L}\Packages\MSTeams_8wekyb3d8bbwe\LocalCache\Microsoft\MSTeams"]),+ "teams_classic": ([r"{L}\Microsoft\Teams", r"{R}\Microsoft\Teams"], ["TEAMS.EXE"], [], []),+ "zoom": ([r"{R}\Zoom", r"{L}\Zoom"], ["ZOOM.EXE"], ["ZoomVideoCommunications"], []),+ "telegram": ([r"{R}\Telegram Desktop"], ["TELEGRAM.EXE"], ["TelegramMessengerLLP.TelegramDesktop"], []),+ "whatsapp": ([r"{L}\Packages\5319275A.WhatsAppDesktop_cv1g1gvanyjgm", r"{L}\WhatsApp"], ["WHATSAPP.EXE"],+ ["5319275A.WhatsAppDesktop"], []),+ "signal": ([r"{R}\Signal", r"{L}\Programs\signal-desktop"], ["SIGNAL.EXE"], [], []),+ "skype": ([r"{R}\Microsoft\Skype for Desktop"], ["SKYPE.EXE"], ["Microsoft.SkypeApp"], []),+ "webex": ([r"{L}\CiscoSpark", r"{L}\WebEx"], ["CISCOCOLLABHOST.EXE", "WEBEX.EXE"], [], []),+ "element": ([r"{R}\Element"], ["ELEMENT.EXE"], [], []),+ "thunderbird": ([r"{R}\Thunderbird"], ["THUNDERBIRD.EXE"], [], []),+ "outlook_classic": ([r"{L}\Microsoft\Outlook"], ["OUTLOOK.EXE"], [], []),+ "outlook_new": ([r"{L}\Packages\Microsoft.OutlookForWindows_8wekyb3d8bbwe"], ["OLK.EXE"],+ ["Microsoft.OutlookForWindows"], [r"{L}\Microsoft\Olk"]),+ "mail_calendar_legacy": ([r"{L}\Packages\microsoft.windowscommunicationsapps_8wekyb3d8bbwe"],+ ["HXOUTLOOK.EXE"], ["microsoft.windowscommunicationsapps"], []),+}++NOTES_APPS = {+ "notion": ([r"{R}\Notion", r"{L}\Programs\Notion"], ["NOTION.EXE"], [], []),+ "notion_calendar": ([r"{R}\Notion Calendar", r"{L}\Programs\cron-web"], ["NOTION CALENDAR.EXE"], [], []),+ "obsidian": ([r"{R}\obsidian\obsidian.json", r"{L}\Programs\obsidian"], ["OBSIDIAN.EXE"], [], []),+ "onenote": ([r"{L}\Microsoft\OneNote"], ["ONENOTE.EXE"], ["Microsoft.Office.OneNote"], []),+}+++@_probe(id="comms.native_apps", level="L1", family="comms_work", tier="T0", collect="core")+def comms_native_apps(h, facts):+ """Native comms/mail apps installed (paths, appx) with prefetch last run and first-launch evidence."""+ rows = _app_rows(h, COMMS_APPS)+ if not rows:+ return {"present": False}+ return rows+++@_probe(id="discord.present", level="L1", family="comms_work", tier="T0", collect="core")+def discord_present(h, facts):+ """Discord desktop installed; version from app-* dir; autostart."""+ roam, local = h.expand(r"%APPDATA%\discord"), h.expand(r"%LOCALAPPDATA%\Discord")+ if not (_isdir(roam) or _isdir(local)):+ return {"present": False}+ vers = sorted(d[4:] for d in h.list_dir(local, 100) if d.startswith("app-"))+ run = _cached(h, "runkeys", _run_keys)+ return {"present": True, "version": vers[-1] if vers else None, "autostart": any("discord" in r.lower() for r in run)}+++@_probe(id="office.c2r", level="L1", family="comms_work", tier="T0", collect="core")+def office_c2r(h, facts):+ """Click-to-Run Office: product ids, version, platform, consumer vs business licence."""+ c = _reg_values(r"HKLM\SOFTWARE\Microsoft\Office\ClickToRun\Configuration") or {}+ pids = c.get("ProductReleaseIds")+ if not pids:+ return {"present": False}+ kind = ("consumer" if re.search(r"HomePrem|Personal|HomeStudent|Professional2", pids) else+ "business" if re.search(r"O365Business|ProPlus|Enterprise", pids) else "other")+ return {"present": True, "products": pids, "version": c.get("VersionToReport"), "platform": c.get("Platform"),+ "license_kind": kind}+++@_probe(id="onedrive.accounts", level="L1", family="comms_work", tier="T0", collect="core")+def onedrive_accounts(h, facts):+ """OneDrive client and account slots; signed in only when UserEmail/cid/ConfiguredTenantId is set."""+ base = r"HKCU\SOFTWARE\Microsoft\OneDrive"+ exe = (h.exists(r"%LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe") or+ h.exists(r"C:\Program Files\Microsoft OneDrive\OneDrive.exe"))+ keys = [k for k in (h.reg(base + r"\Accounts") or []) if k != "FileCoAuth"]+ if not exe and not keys:+ return {"present": False}+ signed = business = 0+ results = []+ for k in keys:+ v = _reg_values(base + r"\Accounts" + "\\" + k) or {}+ is_signed = bool(v.get("UserEmail") or v.get("cid") or v.get("ConfiguredTenantId"))+ signed += is_signed+ business += bool(is_signed and v.get("ConfiguredTenantId"))+ if isinstance(v.get("LastSignInResult"), int):+ results.append(hex(v["LastSignInResult"] & 0xFFFFFFFF))+ return {"present": True, "client_installed": bool(exe), "version": h.reg(base, "Version"),+ "account_slots": len(keys), "signed_in": signed, "business": business,+ "last_sign_in_results": sorted(set(results))}+++@_probe(id="productivity.notes_apps", level="L1", family="comms_work", tier="T0", collect="core")+def notes_apps(h, facts):+ """Notes apps installed: Notion, Notion Calendar, Obsidian, OneNote."""+ rows = _app_rows(h, NOTES_APPS)+ return {"present": bool(rows), "apps": sorted(rows), "detail": rows}+++@_probe(id="work.accounts", level="L1", family="comms_work", tier="T3", collect="core")+def work_accounts(h, facts):+ """Counts only: WAM token cache files, AAD broker accounts, MSA-linked logon marker. Files never opened."""+ tb = h.count_dir(r"%LOCALAPPDATA%\Microsoft\TokenBroker\Cache", 5000)+ aad = h.count_dir(r"%LOCALAPPDATA%\Packages\Microsoft.AAD.BrokerPlugin_cw5n1h2txyewy\AC\TokenBroker\Accounts", 5000)+ msa = h.reg(r"HKCU\SOFTWARE\Microsoft\IdentityCRL\UserExtendedProperties")+ aad_storage = h.reg(r"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\AAD\Storage") or []+ return {"present": True, "tokenbroker_cache_files": max(tb, 0), "aad_broker_accounts": max(aad, 0),+ "aad_storage_keys": len(aad_storage), "windows_logon_msa_linked": bool(msa)}+++@_probe(id="work.edition_org", level="L1", family="comms_work", tier="T0", collect="core")+def work_edition_org(h, facts):+ """Windows edition and whether RegisteredOrganization is set (the org name itself is not emitted)."""+ cv = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion"+ ed = h.reg(cv, "EditionID")+ org = (h.reg(cv, "RegisteredOrganization") or "").strip()+ return {"present": bool(ed), "edition": ed, "registered_org_set": bool(org)}+++@_probe(id="work.mdm", level="L1", family="comms_work", tier="T0", collect="core")+def work_mdm(h, facts):+ """Real MDM enrollments only (UPN, ProviderID MS DM Server, or DiscoveryServiceFullURL)."""+ base = r"HKLM\SOFTWARE\Microsoft\Enrollments"+ keys = h.reg(base) or []+ real = []+ for g in keys[:500]:+ v = _reg_values(base + "\\" + g) or {}+ if v.get("UPN") or v.get("ProviderID") in ("MS DM Server", "WMI_Bridge_Server") or v.get("DiscoveryServiceFullURL"):+ real.append({"type": v.get("EnrollmentType"), "provider": v.get("ProviderID")})+ omadm = h.reg(r"HKLM\SOFTWARE\Microsoft\Provisioning\OMADM\Accounts") or []+ return {"present": True, "real_enrollments": len(real), "enrollments": real[:5], "enrollment_keys_total": len(keys),+ "omadm_accounts": len(omadm),+ "intune_ime": h.exists(r"C:\Program Files (x86)\Microsoft Intune Management Extension")}+++@_probe(id="work.mdm_policy_areas", level="L1", family="comms_work", tier="T0", collect="core")+def work_mdm_policy_areas(h, facts):+ """PolicyManager device areas and providers (corroborates MDM; built-in areas exist on every box)."""+ areas = h.reg(r"HKLM\SOFTWARE\Microsoft\PolicyManager\current\device") or []+ prov = h.reg(r"HKLM\SOFTWARE\Microsoft\PolicyManager\providers") or []+ return {"present": True, "device_areas": len(areas), "providers": len(prov), "areas": sorted(areas)[:40]}+++@_probe(id="work.policies", level="L1", family="comms_work", tier="T0", collect="core")+def work_policies(h, facts):+ """Group-policy keys for browsers/Office/OneDrive/Teams/Slack/Zoom (HKLM+HKCU), value counts only."""+ out, apps = {}, {}+ for hive in ("HKLM", "HKCU"):+ out[hive + "_vendors"] = sorted(h.reg(hive + r"\SOFTWARE\Policies") or [])+ for b in (r"Google\Chrome", r"BraveSoftware\Brave", r"Microsoft\Edge", r"Mozilla\Firefox", r"Microsoft\Office",+ r"Microsoft\OneDrive", r"Microsoft\Teams", "Slack", "Zoom"):+ p = hive + r"\SOFTWARE\Policies" + "\\" + b+ v, sk = _reg_values(p), h.reg(p)+ if v is not None or sk is not None:+ apps[f"{hive}:{b}"] = {"values": len(v or {}), "subkeys": len(sk or [])}+ for area in ("TenantRestrictions", "WorkplaceJoin"):+ v = _reg_values(hive + r"\SOFTWARE\Policies\Microsoft\Windows" + "\\" + area)+ if v:+ out.setdefault("windows_area_value_names", {})[f"{hive}:{area}"] = sorted(v)[:10]+ configured = {k: v for k, v in apps.items() if v["values"] or v["subkeys"]}+ return {"present": True, "app_policies": configured, "app_policy_count": len(configured), **out}+++AGENT_RX = re.compile(r"^(IntuneManagementExtension|CSFalcon\w*|ZSATunnel|ZSAService|PanGPS|vpnagent|csc_\w*|Netskope\w*|"+ r"stAgent\w*|SentinelAgent|Tanium\w*|CylanceSvc|CcmExec|jamf\w*|Kandji\w*|FortiClient\w*|"+ r"NinjaRMM\w*|ManageEngine\w*|LTService|DattoRMM|CiscoAMP|OktaVerify\w*|DuoAuth\w*|Sense|"+ r"GlobalProtect\w*|CarbonBlack|CbDefense|elastic-agent|WinCollect|Qualys\w*|Rapid7\w*|"+ r"TaniumClient|TrendMicro\w*|SophosMCS\w*|Sophos\w*)$", re.I)+++@_probe(id="work.security_agents", level="L1", family="comms_work", tier="T0", collect="core")+def work_security_agents(h, facts):+ """EDR/ZTNA/RMM agents from the Services registry (not sc query). Sense (Defender) is reported separately."""+ svcs = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Services") or []+ hits = sorted(s for s in svcs if AGENT_RX.match(s))+ onboard = h.reg(r"HKLM\SOFTWARE\Microsoft\Windows Advanced Threat Protection\Status", "OnboardingState")+ return {"present": True, "agents": [s for s in hits if s.lower() != "sense"], "sense_present": "Sense" in hits,+ "defender_atp_onboarded": bool(onboard), "services_scanned": len(svcs)}+++@_probe(id="work.join_state", level="L2", family="comms_work", tier="T0", collect="extended", gate="work.edition_org",+ timeout_ms=5000)+def work_join_state(h, facts):+ """Entra/AD/workplace join from dsregcmd /status, with the CloudDomainJoin registry as a cheap cross-check."""+ join_info = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\CloudDomainJoin\JoinInfo") or []+ domain = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters", "Domain") or ""+ txt = h.run(["dsregcmd", "/status"], timeout_ms=5000, text=False) or ""+ got = {}+ for k in ("AzureAdJoined", "EnterpriseJoined", "DomainJoined", "WorkplaceJoined", "AzureAdPrt"):+ m = re.search(rf"^\s*{k}\s*:\s*(\w+)", txt, re.M)+ if m:+ got[k] = m.group(1).upper() == "YES"+ joined = got.get("AzureAdJoined") or got.get("DomainJoined") or got.get("EnterpriseJoined")+ return {"present": True, "source": "dsregcmd" if got else "registry",+ "azure_ad_joined": got.get("AzureAdJoined", bool(join_info)), "domain_joined": got.get("DomainJoined"),+ "enterprise_joined": got.get("EnterpriseJoined"), "workplace_joined": got.get("WorkplaceJoined"),+ "azure_ad_prt": got.get("AzureAdPrt"), "cloud_join_info_keys": len(join_info),+ "tcpip_domain_set": bool(domain), "state": "joined" if joined else "workgroup"}+++@_probe(id="comms.teams_launched", level="L2", family="comms_work", tier="T0", collect="core",+ gate="comms.native_apps")+def comms_teams_launched(h, facts):+ """New Teams actually started: LocalCache\\Microsoft\\MSTeams exists; tfw = work, tfl = personal profiles."""+ b = h.expand(r"%LOCALAPPDATA%\Packages\MSTeams_8wekyb3d8bbwe\LocalCache\Microsoft\MSTeams")+ if not _isdir(b):+ return {"present": False}+ prof = h.list_dir(os.path.join(b, "EBWebView"), 100)+ work = sum(1 for p in prof if "tfw" in p.lower())+ return {"present": True, "work_profile": work > 0, "work_profiles": work,+ "personal_profiles": sum(1 for p in prof if "tfl" in p.lower()),+ "log_files": max(h.count_dir(os.path.join(b, "Logs"), 5000), 0)}+++def _userassist(h, pattern):+ rx = re.compile(pattern, re.I)+ base = HKCU_EXPLORER + r"\UserAssist"+ rot = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",+ "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm")+ focus, last = 0, None+ for g in h.reg(base) or []:+ for n, v in (_reg_values(base + "\\" + g + r"\Count") or {}).items():+ if isinstance(v, bytes) and len(v) >= 68 and rx.search(n.translate(rot)):+ focus += int.from_bytes(v[12:16], "little") // 1000+ t = _ft_iso(int.from_bytes(v[60:68], "little"))+ last = max(filter(None, (last, t)), default=None)+ return focus, last+++@_probe(id="discord.usage", level="L2", family="comms_work", tier="T1", collect="extended", gate="discord.present",+ timeout_ms=3000)+def discord_usage(h, facts):+ """Signed-in and voice days from renderer_js.log line tags; absent when the app never got past login."""+ log = h.expand(r"%APPDATA%\discord\logs\renderer_js.log")+ pf = _cached(h, "prefetch", _prefetch).get("DISCORD.EXE")+ focus_s, ua_last = _userassist(h, r"discord")+ days, gw, rtc = set(), set(), set()+ last_gw = last_auth = None+ size = 0+ if os.path.isfile(log):+ size = os.path.getsize(log)+ rx = re.compile(r"^\[(\d{4}-\d\d-\d\d) ([\d:.]+)\] \[\w+\]\s+\[?([A-Za-z_]+)")+ with open(log, encoding="utf-8", errors="replace") as fh:+ if size > 16_000_000:+ fh.seek(size - 16_000_000)+ for line in fh:+ m = rx.match(line)+ if not m:+ continue+ d, tm, tag = m.groups()+ days.add(d)+ if tag == "GatewaySocket":+ gw.add(d)+ last_gw = d + "T" + tm[:8]+ elif tag.startswith("RTC"):+ rtc.add(d)+ elif tag == "useAuthWebsocket":+ last_auth = d + "T" + tm[:8]+ used = bool(gw or rtc)+ return {"present": used, "log_days": len(days), "first_day": min(days) if days else None,+ "last_day": max(days) if days else None, "gateway_days": len(gw), "rtc_days": len(rtc),+ "logged_in_last_session": bool(last_gw and (not last_auth or last_gw > last_auth)),+ "on_login_screen": bool(last_auth and (not last_gw or last_auth > last_gw)),+ "prefetch_last": _iso(pf), "userassist_focus_s": focus_s, "userassist_last": ua_last,+ "log_bytes": size}+++@_probe(id="office.usage", level="L2", family="comms_work", tier="T1", collect="core", gate="office.c2r")+def office_usage(h, facts):+ """Office identity count, File/Place MRU item counts per app, Office exe prefetch dates (no names or paths)."""+ base = r"HKCU\SOFTWARE\Microsoft\Office"+ ids = h.reg(base + r"\16.0\Common\Identity\Identities") or []+ mru = {}+ for app in ("Word", "Excel", "PowerPoint", "OneNote", "Access", "Visio", "Publisher"):+ n = 0+ for sub in ("File MRU", "Place MRU"):+ n += sum(1 for k in (_reg_values(rf"{base}\16.0\{app}\{sub}") or {}) if k.lower().startswith("item"))+ for u in h.reg(rf"{base}\16.0\{app}\User MRU") or []:+ n += sum(1 for k in (_reg_values(rf"{base}\16.0\{app}\User MRU\{u}\{sub}") or {})+ if k.lower().startswith("item"))+ if n:+ mru[app] = n+ pf = _cached(h, "prefetch", _prefetch)+ runs = {e: _iso(pf[e]) for e in ("WINWORD.EXE", "EXCEL.EXE", "POWERPNT.EXE", "OUTLOOK.EXE", "ONENOTE.EXE") if e in pf}+ return {"present": True, "identities": len(ids), "mru_items": sum(mru.values()), "mru_by_app": mru,+ "prefetch_last": runs, "used": bool(mru or runs)}+++@_probe(id="obsidian.vaults", level="L2", family="comms_work", tier="T1", collect="extended",+ gate="productivity.notes_apps")+def obsidian_vaults(h, facts):+ """Obsidian vault count and note counts (vault names and paths are not emitted)."""+ j = _load_json(h.expand(r"%APPDATA%\obsidian\obsidian.json"))+ vs = (j or {}).get("vaults") or {} if isinstance(j, dict) else {}+ if not vs:+ return {"present": False}+ notes, files, newest = 0, 0, 0++ def on_file(e, s, depth):+ nonlocal notes, newest+ if e.name.lower().endswith(".md"):+ notes += 1+ newest = max(newest, s.st_mtime)+ for v in list(vs.values())[:10]:+ p = v.get("path") if isinstance(v, dict) else None+ if p and _isdir(p):+ st = _walk(p, max_depth=6, max_entries=30000, budget_s=1.5, on_file=on_file,+ skip_dir=lambda n, _p: n in (".obsidian", ".git", ".trash", "node_modules"))+ files += st["files"]+ return {"present": True, "vaults": len(vs), "open": sum(1 for v in vs.values() if isinstance(v, dict) and v.get("open")),+ "notes_md": notes, "files": files, "newest_note": _iso(newest)}+++def _history_ids(h):+ tot = collections.Counter()+ for r in _hist_rows(h):+ tot.update(r.get("_ids") or {})+ return tot+++@_probe(id="browser.history.workspaces", level="L2", family="comms_work", tier="T2", collect="extended",+ gate="browser.catalog")+def history_workspaces(h, facts):+ """Distinct Discord guild / Slack workspace / Gmail slot / Linear workspace ids seen in history (counts only)."""+ rows = _hist_rows(h)+ if not rows:+ return {"present": False}+ ids = _history_ids(h)+ return {"discord": ids["discord_guilds"], "slack": ids["slack_workspaces"], "gmail": ids["gmail_slots"],+ "linear": ids["linear_workspaces"]}+++@_probe(id="browser.history.work_hosts", level="L2", family="comms_work", tier="T2", collect="extended",+ gate="browser.catalog")+def history_work_hosts(h, facts):+ """Top hostnames for Slack, nousresearch.com, Discord, Notion and Linear (default profiles)."""+ hosts = {}+ for r in _hist_rows(h):+ if not r["is_default_profile"]:+ continue+ for k, c in (r.get("_work_hosts") or {}).items():+ hosts.setdefault(k, collections.Counter()).update(c)+ if not hosts:+ return {"present": False}+ return {"present": True, "hosts": {k: [x for x, _ in v.most_common(5)] for k, v in hosts.items()}}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/browser_files_content.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/browser_files_content.pynew file mode 100644index 00000000000..5620efd7ee4--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/browser_files_content.py@@ -0,0 +1,510 @@+"""Files and content probes (files family, Windows): known folders, composition, screenshots.++Registration only at import time. Shared helpers and caches live in browser_files.+"""+from __future__ import annotations++import collections+import os+import re+import statistics+import time++from .browser_files import (AGE_KEYS, FILE_ATTRIBUTE_REPARSE_POINT, HKCU_EXPLORER,+ OPERATOR_DEEP_RX, OPERATOR_RX, SENSITIVE_CATS, _age_bucket, _cache_ms, _cached, _categorize, _env, _home,+ _host_of, _isdir, _iso, _probe, _redact, _reg_key, _reg_lastwrite, _reg_values, _walk, _winreg)++# ================================================================ family: files++KF_GUIDS = {+ "Desktop": "{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}", "Documents": "{FDD39AD0-238F-46AF-ADB4-6C85480369C7}",+ "Downloads": "{374DE290-123F-4565-9164-39C4925E467B}", "Pictures": "{33E28130-4E1E-4676-835A-98395C3BC3BB}",+ "Videos": "{18989B1D-99B5-455B-841C-AB7C74E4DDFC}", "Music": "{4BD8D571-6D19-48D3-BE97-422220080E43}",+ "Screenshots": "{B7BEDE81-DF94-4682-A7D8-57A52620B86F}", "Captures": "{EDC0FE71-98D8-4F4A-B920-C8DC133CB165}",+ "CameraRoll": "{AB5FB87B-7CE2-4F83-915D-550846C9537B}",+}+++def _known_folders(h):+ import ctypes++ class GUID(ctypes.Structure):+ _fields_ = [("Data1", ctypes.c_ulong), ("Data2", ctypes.c_ushort), ("Data3", ctypes.c_ushort),+ ("Data4", ctypes.c_ubyte * 8)]+ out = {}+ for name, g in KF_GUIDS.items():+ guid = GUID()+ ctypes.oledll.ole32.CLSIDFromString(ctypes.c_wchar_p(g), ctypes.byref(guid))+ p = ctypes.c_wchar_p()+ try:+ ctypes.windll.shell32.SHGetKnownFolderPath(ctypes.byref(guid), 0x4000, None, ctypes.byref(p)) # DONT_VERIFY+ out[name] = p.value+ except OSError:+ out[name] = None+ finally:+ if p:+ ctypes.windll.ole32.CoTaskMemFree(p)+ return out+++def _kf(h, name):+ try:+ p = _cached(h, "kf", _known_folders).get(name)+ except RuntimeError:+ p = None+ return p or os.path.join(_home(), name)+++@_probe(id="files.known_folders", level="L1", family="files", tier="T0", collect="core")+def files_known_folders(h, facts):+ """Known-folder paths (SHGetKnownFolderPath, DONT_VERIFY): exists, under profile, under OneDrive."""+ kf = _cached(h, "kf", _known_folders)+ home = _home().lower()+ rows = {n: {"path": _redact(p), "exists": bool(p and _isdir(p)),+ "under_profile": bool(p and p.lower().startswith(home)),+ "under_onedrive": bool(p and "onedrive" in p.lower())} for n, p in kf.items()}+ return {"present": any(r["exists"] for r in rows.values()), "folders": rows}+++@_probe(id="sync.other", level="L1", family="files", tier="T0", collect="core")+def sync_other(h, facts):+ """Other sync clients: Dropbox, Google Drive, iCloud, Box, MEGA, Proton Drive, pCloud, Syncthing."""+ cands = {"dropbox": r"%LOCALAPPDATA%\Dropbox\info.json", "google_drive": r"%LOCALAPPDATA%\Google\DriveFS",+ "icloud": r"%LOCALAPPDATA%\Apple Inc\iCloud", "box": r"%LOCALAPPDATA%\Box",+ "mega": r"%LOCALAPPDATA%\MEGAsync", "proton_drive": r"%LOCALAPPDATA%\Proton\Proton Drive",+ "pcloud": r"%APPDATA%\pCloud", "syncthing": r"%LOCALAPPDATA%\Syncthing"}+ found = [k for k, p in cands.items() if h.exists(p)]+ roots = h.reg(r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\SyncRootManager") or []+ providers = sorted({r.split("!")[0] for r in roots if not r.lower().startswith("onedrive")})+ return {"present": bool(found), "clients": found, "sync_root_providers_non_onedrive": providers[:10]}+++@_probe(id="jumplists.counts", level="L1", family="files", tier="T0", collect="core")+def jumplists_counts(h, facts):+ """Jump-list file counts and sizes (Automatic/CustomDestinations); entries never parsed."""+ base = h.expand(r"%APPDATA%\Microsoft\Windows\Recent")+ out = {}+ for sub in ("AutomaticDestinations", "CustomDestinations"):+ n = b = 0+ try:+ with os.scandir(os.path.join(base, sub)) as it:+ for i, e in enumerate(it):+ if i >= 5000:+ break+ if e.is_file():+ n += 1+ b += e.stat().st_size+ except OSError:+ continue+ out[sub] = {"files": n, "bytes": b}+ return {"present": bool(out), **out}+++@_probe(id="onedrive.kfm", level="L1", family="files", tier="T0", collect="core", gate="onedrive.accounts")+def onedrive_kfm(h, facts):+ """Known-folder move: Desktop/Documents/Pictures redirected into OneDrive (User Shell Folders)."""+ usf = _reg_values(HKCU_EXPLORER + r"\User Shell Folders") or {}+ red = [k for k in ("Desktop", "Personal", "My Pictures", "My Video", "My Music") if "onedrive" in str(usf.get(k, "")).lower()]+ return {"present": True, "redirected": bool(red), "folders": red}+++@_probe(id="onedrive.root_size", level="L2", family="files", tier="T0", collect="core", gate="onedrive.accounts")+def onedrive_root_size(h, facts):+ """Bounded size of %USERPROFILE%\\OneDrive* without hydrating placeholders."""+ home = _home()+ roots = {}+ for name in h.list_dir(home, 500):+ if name.lower().startswith("onedrive") and _isdir(os.path.join(home, name)):+ st = _walk(os.path.join(home, name), max_depth=6, max_entries=50000, budget_s=2.0)+ roots[name] = {k: st[k] for k in ("files", "bytes", "cloud_placeholders", "truncated")}+ if not roots:+ return {"present": False}+ return {"present": True, "roots": roots, "files": sum(r["files"] for r in roots.values()),+ "bytes": sum(r["bytes"] for r in roots.values())}+++def _recent(h):+ rec = h.expand(r"%APPDATA%\Microsoft\Windows\Recent")+ now = time.time()+ ext, ages, mts = collections.Counter(), collections.Counter(), []+ operator = 0+ try:+ it = os.scandir(rec)+ except OSError:+ return None+ with it:+ for i, e in enumerate(it):+ if i >= 20000:+ break+ if not e.name.lower().endswith(".lnk") or not e.is_file():+ continue+ if OPERATOR_DEEP_RX.search(e.name) or OPERATOR_RX.match(e.name[:-4]):+ operator += 1+ continue+ try:+ s = e.stat()+ except OSError:+ continue+ mts.append(s.st_mtime)+ ages[_age_bucket(now - s.st_mtime)] += 1+ x = os.path.splitext(e.name[:-4])[1].lower()+ ext[x if re.fullmatch(r"\.[a-z0-9]{1,5}", x or "") else "(folder_or_none)"] += 1+ return {"count": len(mts), "operator_filtered": operator, "ext": ext, "ages": ages, "mts": mts}+++@_probe(id="files.recent_lnk", level="L2", family="files", tier="T1", collect="core", gate="files.known_folders")+def files_recent_lnk(h, facts):+ """Recent .lnk count, date range, folder vs file split, target extension counts (no names)."""+ r = _recent(h)+ if not r or not r["count"]:+ return {"present": False}+ now = time.time()+ mts = r["mts"]+ folders = r["ext"].get("(folder_or_none)", 0)+ return {"present": True, "count": r["count"], "operator_filtered": r["operator_filtered"],+ "oldest": _iso(min(mts)), "newest": _iso(max(mts)), "folder_or_none": folders,+ "files": r["count"] - folders, "target_ext_top": dict(r["ext"].most_common(10)),+ "age_mtime": {k: r["ages"].get(k, 0) for k in AGE_KEYS},+ "active_days_30d": len({time.strftime("%Y-%m-%d", time.localtime(t)) for t in mts if now - t < 30 * 86400})}+++SHOT_NAME = re.compile(r"^(screenshot|screen shot|capture|snip|screen ?recording|scr_|shot_)", re.I)+IMG_EXT = {".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp", ".jxr", ".heic", ".tif", ".tiff"}+VIDEO_EXT = {".mp4", ".mkv", ".avi", ".mov", ".webm", ".wmv", ".m4v"}+AUDIO_EXT = {".mp3", ".flac", ".wav", ".m4a", ".aac", ".ogg", ".opus"}+DOC_EXT = {".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".txt", ".md", ".csv", ".odt", ".rtf"}+CODE_EXT = {".py", ".js", ".ts", ".json", ".toml", ".yaml", ".yml", ".sh", ".ps1", ".bat", ".rs", ".go", ".c", ".cpp",+ ".h", ".java", ".ipynb", ".log", ".rst", ".html", ".css"}+INSTALLER_EXT = {".exe", ".msi", ".msix", ".appx", ".msixbundle", ".appxbundle"}+ARCHIVE_EXT = {".zip", ".7z", ".rar", ".tar", ".gz", ".iso", ".xz", ".bz2", ".zst"}+++def _kind(ext):+ for k, s in (("image", IMG_EXT), ("video", VIDEO_EXT), ("audio", AUDIO_EXT), ("document", DOC_EXT),+ ("code", CODE_EXT), ("installer", INSTALLER_EXT), ("archive", ARCHIVE_EXT)):+ if ext in s:+ return k+ return "other"+++def _composition(h):+ now = time.time()+ deadline = time.perf_counter() + 8.0+ shots = []+ seen = set()+ res = {}+ for name in ("Desktop", "Documents", "Downloads", "Pictures", "Videos", "Music"):+ p = _kf(h, name)+ ext_n, ext_b, kind_b = collections.Counter(), collections.Counter(), collections.Counter()+ ages, years = collections.Counter(), collections.Counter()+ dup = [0]++ def on_file(e, s, depth, label=name):+ ext = os.path.splitext(e.name)[1].lower() or "(none)"+ if len(ext) > 12:+ ext = "(long)"+ ext_n[ext] += 1+ ext_b[ext] += s.st_size+ kind_b[_kind(ext)] += s.st_size+ ages[_age_bucket(now - s.st_mtime)] += 1+ years[time.localtime(s.st_mtime).tm_year] += 1+ if re.search(r"\(\d+\)(\.[^.]+)?$", e.name):+ dup[0] += 1+ if ext in IMG_EXT or ext in (".mp4", ".mkv"):+ low = e.path.lower()+ if (SHOT_NAME.match(e.name) or any(s_ in low for s_ in ("\\screenshots\\", "\\captures\\", "\\sharex\\",+ "\\ansel\\"))) and low not in seen:+ seen.add(low)+ shots.append((s.st_mtime, label, ext in IMG_EXT))+ budget = max(0.2, min(3.0, deadline - time.perf_counter()))+ st = _walk(p, max_depth=6, max_entries=100000, budget_s=budget, on_file=on_file,+ skip_dir=lambda n, path: bool(OPERATOR_DEEP_RX.search(n)))+ top = {"files": 0, "dirs": 0, "shortcuts": 0}+ for e in h.list_dir(p, 5000):+ full = os.path.join(p, e)+ if e.lower() == "desktop.ini":+ continue+ if _isdir(full):+ top["dirs"] += 1+ else:+ top["files"] += 1+ top["shortcuts"] += e.lower().endswith((".lnk", ".url"))+ res[name] = {"files": st["files"], "dirs": st["dirs"], "bytes": st["bytes"], "truncated": st["truncated"],+ "depth": 6, "top_level": top, "ext_top_by_count": dict(ext_n.most_common(10)),+ "ext_top_by_bytes": dict(ext_b.most_common(6)), "kind_bytes": dict(kind_b),+ "age_mtime": {k: ages.get(k, 0) for k in AGE_KEYS},+ "oldest_year": min(years) if years else None, "newest_year": max(years) if years else None,+ "dup_suffix_files": dup[0], "ms": st.get("ms")}+ return {"folders": res, "shots": shots}+++@_probe(id="files.composition", level="L2", family="files", tier="T1", collect="extended", gate="files.known_folders",+ timeout_ms=9000)+def files_composition(h, facts):+ """Per known folder: files, bytes, extension/kind/age histograms, depth <= 6 (no file names)."""+ c = _cached(h, "composition", _composition)+ folders = c["folders"]+ kind = collections.Counter()+ for f in folders.values():+ kind.update(f["kind_bytes"])+ tot = sum(kind.values()) or 1+ dl = folders.get("Downloads", {})+ old = sum(dl.get("age_mtime", {}).get(k, 0) for k in ("lt_1y", "lt_2y", "ge_2y"))+ return {"present": True, "folders": folders, "total_bytes": sum(f["bytes"] for f in folders.values()),+ "byte_share": {k: round(v / tot, 3) for k, v in kind.most_common()},+ "downloads_older_90d_share": round(old / dl["files"], 3) if dl.get("files") else None,+ "shared_block_ms": _cache_ms(h, "composition")}+++@_probe(id="files.screenshots", level="L2", family="files", tier="T1", collect="extended", gate="files.known_folders",+ timeout_ms=9000)+def files_screenshots(h, facts):+ """Screenshot/capture count, active days, cadence and local hour/weekday histograms (from the composition walk)."""+ c = _cached(h, "composition", _composition)+ imgs = sorted(t for t, _l, is_img in c["shots"] if is_img)+ vids = sum(1 for _t, _l, is_img in c["shots"] if not is_img)+ shots_kf = _kf(h, "Screenshots")+ if not imgs:+ return {"present": False}+ now = time.time()+ days = {time.strftime("%Y-%m-%d", time.localtime(t)) for t in imgs}+ gaps = [(b - a) / 3600 for a, b in zip(imgs, imgs[1:])]+ return {"present": True, "count": len(imgs), "video_captures": vids,+ "by_folder": dict(collections.Counter(l for _t, l, i in c["shots"] if i)),+ "screenshots_kf_exists": _isdir(shots_kf), "first": _iso(imgs[0]), "last": _iso(imgs[-1]),+ "last_30d": sum(1 for t in imgs if now - t < 30 * 86400), "active_days": len(days),+ "per_active_day": round(len(imgs) / len(days), 2),+ "median_gap_h": round(statistics.median(gaps), 2) if gaps else None,+ "hours": [sum(1 for t in imgs if time.localtime(t).tm_hour == hr) for hr in range(24)],+ "weekdays_mon0": [sum(1 for t in imgs if time.localtime(t).tm_wday == d) for d in range(7)]}+++def _user_sid(h):+ home = _home().lower()+ base = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"+ for sid in h.reg(base) or []:+ if sid.startswith("S-1-5-21-") and (h.reg(base + "\\" + sid, "ProfileImagePath") or "").lower() == home:+ return sid+ return None+++@_probe(id="files.clutter", level="L2", family="files", tier="T1", collect="extended", gate="files.known_folders",+ timeout_ms=6000)+def files_clutter(h, facts):+ """Recycle Bin, TEMP and thumbnail-cache sizes; Desktop item count; Windows Search index size."""+ out = {"present": True}+ sid = _user_sid(h)+ rb = rf"C:\$Recycle.Bin\{sid}" if sid else None+ if rb and _isdir(rb):+ items = [0]++ def cb(e, s, depth):+ if depth == 0 and e.name.startswith("$R"):+ items[0] += 1+ st = _walk(rb, max_depth=6, max_entries=100000, budget_s=2.0, on_file=cb)+ out["recycle_bin"] = {"items": items[0], "files": st["files"], "bytes": st["bytes"], "truncated": st["truncated"]}+ tmp = _env("TEMP")+ if tmp and _isdir(tmp):+ st = _walk(tmp, max_depth=5, max_entries=100000, budget_s=2.0,+ skip_dir=lambda n, p: n == "userscan" or bool(OPERATOR_DEEP_RX.search(n)))+ out["temp_files"], out["temp_bytes"], out["temp_truncated"] = st["files"], st["bytes"], st["truncated"]+ ex = h.expand(r"%LOCALAPPDATA%\Microsoft\Windows\Explorer")+ tb = sum((h.meta(os.path.join(ex, n)).get("bytes") or 0) for n in h.list_dir(ex, 500)+ if n.lower().startswith(("thumbcache_", "iconcache_")))+ out["thumbcache_bytes"] = tb+ idx = h.meta(r"C:\ProgramData\Microsoft\Search\Data\Applications\Windows\Windows.db")+ out["search_index_bytes"] = idx.get("bytes")+ desk = _kf(h, "Desktop")+ names = [n for n in h.list_dir(desk, 5000) if n.lower() != "desktop.ini"]+ out["desktop_items"] = len(names)+ out["desktop_shortcuts"] = sum(1 for n in names if n.lower().endswith((".lnk", ".url")))+ return out+++def _mru_counts(path):+ try:+ subs = []+ with _reg_key(path) as k:+ wr = _winreg()+ i = 0+ while i < 2000:+ try:+ subs.append(wr.EnumKey(k, i))+ except OSError:+ break+ i += 1+ except OSError:+ return None+ per = {}+ for sk in subs:+ v = _reg_values(path + "\\" + sk) or {}+ per[sk.lower()] = sum(1 for n in v if n.isdigit())+ return per+++EXT_OK = re.compile(r"^\.?[a-z0-9]{1,6}$|^folder$|^\*$")+++def _bucket(per):+ clean, odd = collections.Counter(), 0+ for e, c in per.items():+ if EXT_OK.match(e):+ clean[e] += c+ else:+ odd += 1+ clean["(url_or_odd)"] += c+ return clean, odd+++def _utf16_first(b):+ try:+ return b.decode("utf-16le", errors="ignore").split("\x00", 1)[0]+ except Exception:+ return None+++@_probe(id="files.opensave_mru", level="L2", family="files", tier="T1", collect="extended", gate="files.known_folders")+def files_opensave_mru(h, facts):+ """File-dialog history: per-extension item counts and the app exe names that used the dialog (no paths)."""+ cd = HKCU_EXPLORER + r"\ComDlg32"+ per = _mru_counts(cd + r"\OpenSavePidlMRU")+ apps = collections.Counter()+ for sub in ("LastVisitedPidlMRU", "CIDSizeMRU"):+ for n, v in (_reg_values(cd + "\\" + sub) or {}).items():+ if n.isdigit() and isinstance(v, bytes):+ a = _utf16_first(v)+ if a and re.fullmatch(r"[\w .\-]{1,64}\.exe", a, re.I):+ apps[a.lower()] += 1+ if per is None and not apps:+ return {"present": False}+ clean, odd = _bucket({k: v for k, v in (per or {}).items() if k != "*"})+ return {"present": True, "all_items": (per or {}).get("*"), "ext_top": dict(clean.most_common(12)),+ "odd_keys_redacted": odd, "apps": dict(apps.most_common(12)),+ "last_write": _reg_lastwrite(cd + r"\OpenSavePidlMRU")}+++@_probe(id="files.recentdocs", level="L2", family="files", tier="T1", collect="extended", gate="files.known_folders")+def files_recentdocs(h, facts):+ """Explorer RecentDocs: total items and per-extension counts; URL/search-built subkeys bucketed."""+ path = HKCU_EXPLORER + r"\RecentDocs"+ top = _reg_values(path)+ if top is None:+ return {"present": False}+ per = _mru_counts(path) or {}+ clean, odd = _bucket(per)+ return {"present": True, "total_items": sum(1 for n in top if n.isdigit()), "ext_subkeys": len(per),+ "odd_keys_redacted": odd, "ext_top": dict(clean.most_common(12)), "last_write": _reg_lastwrite(path)}+++def _reg_domain(host):+ if not host or re.fullmatch(r"[\d.]+", host):+ return host+ parts = host.split(".")+ if len(parts) >= 3 and parts[-2] in ("co", "com", "org", "net", "ac", "gov") and len(parts[-1]) == 2:+ return ".".join(parts[-3:])+ return ".".join(parts[-2:])+++@_probe(id="files.download_sources", level="L2", family="files", tier="T1", collect="deep", gate="files.known_folders",+ timeout_ms=6000)+def files_download_sources(h, facts):+ """Zone.Identifier ADS in Downloads (depth <= 2): zone counts and source-site category counts (no hosts)."""+ root = _kf(h, "Downloads")+ if not _isdir(root):+ return {"present": False}+ zone, cats, ext_cat = collections.Counter(), collections.Counter(), collections.Counter()+ n = with_ads = no_host = 0+ deadline = time.perf_counter() + 5.0+ stack, trunc = [(root, 0)], None+ while stack:+ d, depth = stack.pop()+ try:+ entries = list(os.scandir(d))+ except OSError:+ continue+ for e in entries:+ if e.is_dir(follow_symlinks=False):+ if depth + 1 < 2 and not OPERATOR_DEEP_RX.search(e.name):+ stack.append((e.path, depth + 1))+ continue+ n += 1+ if n > 5000 or time.perf_counter() > deadline:+ trunc = "cap"+ stack.clear()+ break+ try:+ with open(e.path + ":Zone.Identifier", "r", encoding="utf-8", errors="replace") as f:+ txt = f.read(4096)+ except OSError:+ continue+ with_ads += 1+ kv = dict(line.split("=", 1) for line in txt.splitlines() if "=" in line)+ zone[kv.get("ZoneId", "?").strip()] += 1+ url = (kv.get("HostUrl") or "").strip()+ if not url or url.startswith("about:"):+ no_host += 1+ continue+ host, _ = _host_of(url)+ c = _categorize(_reg_domain(host)) if host else "other"+ c = "sensitive" if c in SENSITIVE_CATS else c+ cats[c] += 1+ ext_cat[f"{c}:{os.path.splitext(e.name)[1].lower() or '(none)'}"] += 1+ return {"present": True, "files_scanned": n, "depth": 2, "truncated": trunc, "with_zone_identifier": with_ads,+ "no_host_url": no_host, "zones": dict(zone), "source_categories": dict(cats.most_common()),+ "category_ext_top": dict(ext_cat.most_common(10))}+++STANDARD_DIRS = {"appdata", "desktop", "documents", "downloads", "pictures", "videos", "music", "onedrive", "contacts",+ "favorites", "links", "saved games", "searches", "3d objects"}+++@_probe(id="files.profile_size_walk", level="L2", family="files", tier="T2", collect="deep", gate="files.known_folders",+ timeout_ms=30000)+def files_profile_size_walk(h, facts):+ """Size of each top-level profile dir (depth <= 10, 300k entries/dir, 25 s total); operator dirs excluded."""+ home = _home()+ deadline = time.perf_counter() + 25.0+ rows = []+ loose = 0+ try:+ entries = list(os.scandir(home))+ except OSError:+ return {"present": False}+ for e in entries:+ try:+ s = e.stat(follow_symlinks=False)+ except OSError:+ continue+ if not e.is_dir(follow_symlinks=False):+ loose += 1+ continue+ if getattr(s, "st_file_attributes", 0) & FILE_ATTRIBUTE_REPARSE_POINT:+ continue+ low = e.name.lower()+ cls = ("operator" if OPERATOR_RX.match(e.name) else "dot" if low.startswith(".") else+ "standard" if low in STANDARD_DIRS else "custom")+ if cls == "operator":+ rows.append({"name": e.name, "class": cls, "bytes": 0, "skipped": "operator"})+ continue+ remain = deadline - time.perf_counter()+ if remain <= 0:+ rows.append({"name": e.name, "class": cls, "bytes": 0, "skipped": "budget"})+ continue+ st = _walk(e.path, max_depth=10, max_entries=300000,+ budget_s=min(12.0 if low == "appdata" else 4.0, remain))+ rows.append({"name": e.name, "class": cls, "bytes": st["bytes"], "files": st["files"],+ "truncated": st["truncated"], "ms": st.get("ms")})+ rows.sort(key=lambda r: -r["bytes"])+ shown = 0+ for r in rows:+ if r["class"] == "custom":+ shown += 1+ if shown > 5:+ r["name"] = f"custom#{shown}"+ cls = collections.Counter(r["class"] for r in rows)+ return {"present": True, "top_dirs": [r for r in rows if r["class"] != "operator"][:12],+ "class_counts": dict(cls), "custom_root_dirs": cls.get("custom", 0),+ "operator_dirs_excluded": cls.get("operator", 0),+ "custom_bytes": sum(r["bytes"] for r in rows if r["class"] == "custom"),+ "total_bytes": sum(r["bytes"] for r in rows), "loose_root_files": loose,+ "truncated_dirs": sum(1 for r in rows if r.get("truncated") or r.get("skipped") == "budget")}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps.pyindex f1e7c37cede..ad4486ab292 100644--- a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps.py+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps.py@@ -1,4 +1,5 @@-"""macOS user-level probes: apps, ai_agents, dev, browser, comms_work, files, gaming, media.+"""macOS user-level probes: apps, ai_agents. The dev, browser/comms_work and files/gaming/media families live+in darwin_apps_dev, darwin_apps_browser and darwin_apps_files and share this module's helpers.Registration only at import time. Signal ids match the Windows modules wherever macOS has a source, so derive.pyrules fire unchanged. Where a Windows extractor is path-agnostic (Claude/Codex JSONL scans, Chromium History SQL,@@ -14,8 +15,6 @@ auth.json, .env, ~/.ssh keys) are stat'ed only.from __future__ import annotationsimport collections-import ctypes-import ctypes.utilimport datetime as dtimport globimport json@@ -27,10 +26,9 @@ import sqlite3import subprocessimport time-from userscan.registry import REGISTRY, probe-from userscan.specs import apps_dev as ad-from userscan.specs import browser_files as bf-from userscan.specs import usage_gaming as ug+from ..registry import REGISTRY, probe+from . import apps_dev as ad+from . import apps_dev_agents as ad_agentsMAC = "darwin"APPS, AI, DEV, BROWSER, COMMS, FILES, GAMING, MEDIA = (@@ -205,14 +203,14 @@ def _which(h, name):return None-def _spawn(args, timeout=5.0):+def _spawn(h, args, timeout=5.0):"""(rc, stdout, ms) with stdin closed; stderr dropped. PATH gains Homebrew and the user's tool dirs."""t = time.perf_counter()try:- path = os.environ.get("PATH", "") + ":" + ":".join(d for d in _extra_bins(None) if os.path.isdir(d))+ path = h.child_env().get("PATH", "") + ":" + ":".join(d for d in _extra_bins(None) if os.path.isdir(d))r = subprocess.run(args, capture_output=True, timeout=timeout, stdin=subprocess.DEVNULL,- env=dict(os.environ, PATH=path, NO_COLOR="1", HERMES_NO_UPDATE_CHECK="1",- HOMEBREW_NO_AUTO_UPDATE="1", LC_ALL="C"))+ env=h.child_env(PATH=path, NO_COLOR="1", HERMES_NO_UPDATE_CHECK="1",+ HOMEBREW_NO_AUTO_UPDATE="1", LC_ALL="C"))return r.returncode, (r.stdout or b"").decode("utf-8", "replace").strip(), round((time.perf_counter() - t) * 1000, 1)except Exception:return None, "", round((time.perf_counter() - t) * 1000, 1)@@ -259,7 +257,7 @@ def _procs(h):"""Counter of executable basenames for the invoking uid (one `ps` spawn, comm only, no argv),plus the total process count across all users (a count, no names)."""def build():- rc, txt, _ms = _spawn(["ps", "-axo", "uid=,comm="], timeout=4)+ rc, txt, _ms = _spawn(h, ["ps", "-axo", "uid=,comm="], timeout=4)me = os.getuid()names, total = collections.Counter(), 0for line in txt.splitlines():@@ -511,7 +509,7 @@ _PROC_INTEREST = re.compile(r"claude|codex|hermes|ollama|lm ?studio|cursor|windsdef tasks_nonms(h, facts):"""This user's scheduled jobs: `crontab -l` entry count and command names, user LaunchAgents with aStartInterval/StartCalendarInterval; lab jobs counted separately."""- rc, txt, _ms = _spawn(["crontab", "-l"], timeout=2) if shutil.which("crontab") else (None, "", 0)+ rc, txt, _ms = _spawn(h, ["crontab", "-l"], timeout=2) if shutil.which("crontab") else (None, "", 0)jobs = [l for l in txt.splitlines() if l.strip() and not l.lstrip().startswith("#") and not re.match(r"^\w+=", l.strip())]names, op = collections.Counter(), 0for j in jobs:@@ -634,7 +632,7 @@ def browser_automation(h, facts):return {"present": bool(out), **out}-_mirror("browser_harness.present", ad.browser_harness_present)+_mirror("browser_harness.present", ad_agents.browser_harness_present)@_mp("claude_code.present", level="L1", family=AI, tier="T0", collect="core")@@ -660,10 +658,10 @@ def claude_code_present(h, facts):"running": sum(_running(h, r"^claude$|claude-code").values())}-_mirror("claude_code.config", ad.claude_code_config)-_mirror("claude_code.claude_json", ad.claude_code_claude_json)-_mirror("claude_code.sessions", ad.claude_code_sessions)-_mirror("claude_code.titles", ad.claude_code_titles)+_mirror("claude_code.config", ad_agents.claude_code_config)+_mirror("claude_code.claude_json", ad_agents.claude_code_claude_json)+_mirror("claude_code.sessions", ad_agents.claude_code_sessions)+_mirror("claude_code.titles", ad_agents.claude_code_titles)@_mp("claude_desktop.present", level="L1", family=AI, tier="T0", collect="core")@@ -683,7 +681,7 @@ def claude_desktop_present(h, facts):@_mp("codex.present", level="L1", family=AI, tier="T0", collect="core")def codex_present(h, facts):"""OpenAI Codex: ~/.codex home (or CODEX_HOME), Codex desktop app bundle, npm global, binary on PATH."""- home = ad._codex_home(h)+ home = ad_agents._codex_home(h)npm = _npm_pkg(h, "@openai/codex")exe = _which(h, "codex")b = _app(h, "Codex")@@ -697,10 +695,10 @@ def codex_present(h, facts):@_mp("codex.auth_presence", level="L1", family=AI, tier="T3", collect="core")def codex_auth_presence(h, facts):"""Codex auth.json presence/size/mtime (never opened)."""- return h.meta(os.path.join(ad._codex_home(h), "auth.json"))+ return h.meta(os.path.join(ad_agents._codex_home(h), "auth.json"))-_mirror("codex.config", ad.codex_config)+_mirror("codex.config", ad_agents.codex_config)_TURN_MODEL = re.compile(rb'"model":"([^"]{1,60})"')_TURN_EFFORT = re.compile(rb'"(?:reasoning_)?effort":"([^"]{1,20})"')@@ -710,7 +708,7 @@ def codex_usage(h, facts):"""Codex rollouts (count/bytes/date range from file names; turn models from a byte-level scan, newest filesfirst, 2.5 s budget) + state_*.sqlite thread counts and thread_history turn durations opened read-only in place.Same keys as the Windows extractor; `content_scan` says how much of the rollout bytes were scanned."""- home = ad._codex_home(h)+ home = ad_agents._codex_home(h)if not _isdir(home):return Nonefiles = sorted(glob.glob(os.path.join(home, "sessions", "*", "*", "*", "rollout-*.jsonl")) +@@ -796,10 +794,10 @@ def codex_usage(h, facts):out["turns"] = {"error": type(e).__name__}return out-_mirror("codex.extras", ad.codex_extras)-_mirror("codex.chatgpt_catalog", ad.codex_chatgpt_catalog)-_mirror("copilot_cli.present", ad.copilot_cli_present)-_mirror("docker.model_runner", ad.docker_model_runner)+_mirror("codex.extras", ad_agents.codex_extras)+_mirror("codex.chatgpt_catalog", ad_agents.codex_chatgpt_catalog)+_mirror("copilot_cli.present", ad_agents.copilot_cli_present)+_mirror("docker.model_runner", ad_agents.docker_model_runner)@_mp("cua_driver.present", level="L1", family=AI, tier="T0", collect="core")@@ -838,7 +836,7 @@ def _prime_hermes(h):def hermes_present(h, facts):"""Hermes Agent: HERMES_HOME / ~/.hermes, install method, agent version, desktop app, launchd gateway, running."""_prime_hermes(h)- hh = ad._hermes_homes(h)+ hh = ad_agents._hermes_homes(h)homes = []for c in hh["cands"]:p = c["path"]@@ -870,9 +868,9 @@ def hermes_present(h, facts):"desktop_userdata_dirs": len(glob.glob(_AS(h, "Hermes*"))), "running": sum(_running(h, r"hermes").values())}-_mirror("hermes.auth_presence", ad.hermes_auth_presence, _prime_hermes)-_mirror("hermes.config", ad.hermes_config, _prime_hermes)-_mirror("hermes.skills", ad.hermes_skills, _prime_hermes)+_mirror("hermes.auth_presence", ad_agents.hermes_auth_presence, _prime_hermes)+_mirror("hermes.config", ad_agents.hermes_config, _prime_hermes)+_mirror("hermes.skills", ad_agents.hermes_skills, _prime_hermes)def _hermes_summary(path, titles=False):@@ -914,7 +912,7 @@ def _hermes_summary(path, titles=False):def hermes_usage(h, facts):"""Primary Hermes state.db opened read-only in place: session/message/tool-call counts, date range, sources, models."""_prime_hermes(h)- hh = ad._hermes_homes(h)+ hh = ad_agents._hermes_homes(h)p = hh["primary"]if not p:return None@@ -939,7 +937,7 @@ def hermes_usage(h, facts):def hermes_titles(h, facts):"""Most recent top-level Hermes session titles (redacted). T2 content, opt-in."""_prime_hermes(h)- p = ad._hermes_homes(h)["primary"]+ p = ad_agents._hermes_homes(h)["primary"]if not p:return Nonetry:@@ -957,10 +955,10 @@ def l3_mcp_inventory(h, facts):_prime_hermes(h)U = _U(h)by = {}- cj = ad._claude_json(h)+ cj = ad_agents._claude_json(h)if cj:by["claude_code"] = sorted(set(cj["global_mcp_servers"]) | set(cj["project_mcp_servers"]))- cp = os.path.join(ad._codex_home(h), "config.toml")+ cp = os.path.join(ad_agents._codex_home(h), "config.toml")if ad.tomllib and os.path.exists(cp):try:with open(cp, "rb") as f:@@ -980,15 +978,15 @@ def l3_mcp_inventory(h, facts):if isinstance(j.get(k), dict):by[label] = sorted(j[k].keys())break- p = ad._hermes_homes(h)["primary"]+ p = ad_agents._hermes_homes(h)["primary"]if p and os.path.exists(os.path.join(p["path"], "config.yaml")):try:- by["hermes"] = ad._parse_hermes_yaml(os.path.join(p["path"], "config.yaml"))["mcp_servers"]+ by["hermes"] = ad_agents._parse_hermes_yaml(os.path.join(p["path"], "config.yaml"))["mcp_servers"]except OSError:pass- user = sorted({n for v in by.values() for n in v if n not in ad.BUNDLED_MCP})+ user = sorted({n for v in by.values() for n in v if n not in ad_agents.BUNDLED_MCP})return {"present": True, "by_agent": {k: v for k, v in by.items() if v}, "user_configured": user,- "user_configured_total": len(user), "vendor_bundled": sorted({n for v in by.values() for n in v if n in ad.BUNDLED_MCP})}+ "user_configured_total": len(user), "vendor_bundled": sorted({n for v in by.values() for n in v if n in ad_agents.BUNDLED_MCP})}@_mp("ollama.present", level="L1", family=AI, tier="T0", collect="core")@@ -996,7 +994,7 @@ def ollama_present(h, facts):"""Ollama: app bundle (version), binary, ~/.ollama models dir, running."""exe = _which(h, "ollama")b = _app(h, "Ollama")- mroot = ad._ollama_models_root(h)+ mroot = ad_agents._ollama_models_root(h)if not (exe or b or _isdir(os.path.join(_U(h), ".ollama"))):return Nonereturn {"present": True, "app": bool(b), "version": (b or {}).get("version"), "install_date": (b or {}).get("install_date"),@@ -1004,1591 +1002,4 @@ def ollama_present(h, facts):"running": _running(h, r"^ollama")}-_mirror("ollama.models", ad.ollama_models)---# ================================================================== dev--@_mp("apps.pkg_managers", level="L1", family=DEV, tier="T0", collect="core")-def apps_pkg_managers(h, facts):- """Package managers: Homebrew, MacPorts, nix, npm/pnpm/bun/yarn, cargo, go, uv, pipx, mas."""- U = _U(h)- b = {"brew": bool(_brew_prefix()), "macports": _ex("/opt/local/bin/port"),- "nix": _ex("/nix", os.path.join(U, ".nix-profile")), "npm": bool(_which(h, "npm")), "pnpm": bool(_which(h, "pnpm")),- "bun": bool(_which(h, "bun")), "yarn": bool(_which(h, "yarn")), "cargo": bool(_which(h, "cargo")),- "go": bool(_which(h, "go")), "uv": bool(_which(h, "uv")), "pipx": bool(_which(h, "pipx")),- "mas": bool(_which(h, "mas")), "fnm": bool(_which(h, "fnm")), "nvm": _isdir(os.path.join(U, ".nvm")),- "pkgx": bool(_which(h, "pkgx")), "mise": bool(_which(h, "mise")), "asdf": _isdir(os.path.join(U, ".asdf"))}- return {"present": True, **b, "managers": sorted(k for k, v in b.items() if v)}---def _ls_pkgs(root, cap=500):- names = _ls(root, cap)- if names is None:- return None- pk = []- for n in names:- if n.startswith("@"):- pk += [f"{n}/{s}" for s in (_ls(os.path.join(root, n), 100) or []) if not s.startswith(".")]- elif not n.startswith("."):- pk.append(n)- return sorted(pk)---@_mp("dev.npm_globals", level="L2", family=DEV, tier="T1", collect="core", gate="apps.pkg_managers")-def dev_npm_globals(h, facts):- """Global JS packages by manager (npm roots incl. Homebrew/fnm/nvm, pnpm, bun, yarn); directory listings, no spawn."""- U = _U(h)- out, allp = {}, set()- for r in _npm_roots(h):- pk = [p for p in (_ls_pkgs(r) or []) if p not in ("npm", "corepack")]- if pk:- key = "npm_user" if r.startswith(U) else "npm_system"- out.setdefault(key, []).extend(pk)- allp.update(pk)- for key, r in (("pnpm", os.path.join(U, "Library", "pnpm", "global", "5", "node_modules")),- ("bun", os.path.join(U, ".bun", "install", "global", "node_modules")),- ("yarn", _cfg(h, "yarn", "global", "node_modules"))):- pk = _ls_pkgs(r)- if pk:- out[key] = pk- allp.update(pk)- if not out:- return {"present": False}- return {"present": True, "count": len(allp), "packages": sorted(allp)[:80],- "by_manager": {k: len(set(v)) for k, v in out.items()}}---@_mp("dev.lang_globals", level="L2", family=DEV, tier="T1", collect="core", gate="apps.pkg_managers")-def dev_lang_globals(h, facts):- """cargo-installed crates (~/.cargo/.crates2.json) and ~/go/bin binaries; names only."""- U = _U(h)- out = {}- cj = _read_json(os.path.join(U, ".cargo", ".crates2.json"))- if isinstance(cj, dict) and isinstance(cj.get("installs"), dict):- out["cargo"] = sorted({k.split(" ")[0] for k in cj["installs"]})[:60]- elif _isdir(os.path.join(U, ".cargo", "bin")):- out["cargo_bin"] = sorted(n for n in _ls(os.path.join(U, ".cargo", "bin")) or [] if not n.startswith("."))[:60]- gb = _ls(os.path.join(os.environ.get("GOPATH") or os.path.join(U, "go"), "bin"))- if gb:- out["go_bin"] = sorted(gb)[:60]- if not out:- return {"present": False}- return {"present": True, "count": sum(len(v) for v in out.values()), **out}---@_mp("dev.uv_tools", level="L2", family=DEV, tier="T1", collect="core", gate="dev.toolchain_presence")-def dev_uv_tools(h, facts):- """uv tools and uv-managed Pythons (~/.local/share/uv listing, equals `uv tool list`), ~/.local/bin entries."""- tools = _ls(_data(h, "uv", "tools"), 200)- py = _ls(_data(h, "uv", "python"), 200)- lb = _ls(os.path.join(_U(h), ".local", "bin"), 300)- if tools is None and py is None and lb is None:- return {"present": False}- return {"present": True, "tools": sorted(t for t in (tools or []) if not t.startswith("."))[:60],- "pythons": sorted(p for p in (py or []) if p.startswith(("cpython", "pypy")))[:30],- "local_bin_count": len(lb or []), "local_bin": sorted(lb or [])[:40]}---@_mp("dev.git", level="L1", family=DEV, tier="T0", collect="core")-def dev_git(h, facts):- """git binary (no spawn): Xcode Command Line Tools shim, Homebrew git or other."""- exe = _which(h, "git")- if not exe:- return None- rp = os.path.realpath(exe)- kind = "homebrew" if "/homebrew/" in rp or "/Cellar/" in rp else "apple_clt" if exe == "/usr/bin/git" else \- "user" if exe.startswith(_U(h)) else "other"- return {"present": True, "on_path": bool(shutil.which("git")), "path_kind": kind,- "clt_installed": _isdir("/Library/Developer/CommandLineTools"), "xdg_config": os.path.exists(_cfg(h, "git", "config"))}---_mirror("dev.git_global_config", ad.dev_git_global_config)---@_mp("dev.gh_auth_presence", level="L1", family=DEV, tier="T3", collect="core")-def dev_gh_auth_presence(h, facts):- """GitHub CLI hosts.yml presence/size (means gh logged in; never opened)."""- return h.meta(_cfg(h, "gh", "hosts.yml"))---@_mp("dev.docker_config_presence", level="L1", family=DEV, tier="T3", collect="core")-def dev_docker_config_presence(h, facts):- """~/.docker/config.json presence/size (may hold registry auths; never opened)."""- return h.meta(os.path.join(_U(h), ".docker", "config.json"))---_mirror("dev.npmrc_presence", ad.dev_npmrc_presence)--_PATH_TOOLS = [("homebrew", r"^/opt/homebrew/|^/usr/local/(s?bin)$"), ("local_bin", r"/\.local/bin$"), ("home_bin", r"^/Users/[^/]+/bin$"),- ("bun", r"/\.bun/bin"), ("cargo", r"/\.cargo/bin"), ("go", r"/go/bin"), ("fnm", r"fnm"), ("nvm", r"\.nvm"),- ("volta", r"\.volta"), ("pnpm", r"pnpm"), ("deno", r"\.deno"), ("nix", r"\.nix-profile|/nix/"),- ("conda", r"conda|miniforge"), ("pyenv", r"\.pyenv"), ("rye", r"\.rye"), ("hermes", r"hermes"),- ("lmstudio", r"\.lmstudio"), ("orbstack", r"orbstack"), ("docker", r"Docker\.app"), ("macports", r"^/opt/local/"),- ("postgres_app", r"Postgres\.app"), ("vscode", r"Visual Studio Code\.app")]---@_mp("dev.path_entries", level="L1", family=DEV, tier="T0", collect="core")-def dev_path_entries(h, facts):- """PATH entry count and known-tool dir matches for this process (paths not emitted); user bin dirs off PATH."""- ents = [e for e in os.environ.get("PATH", "").split(":") if e]- tools = sorted({t for t, rx in _PATH_TOOLS for e in ents if re.search(rx, e)})- U = _U(h)- off = [os.path.relpath(d, U) for d in _extra_bins(h) if d.startswith(U) and _isdir(d) and d not in ents]- helper = len(_ls("/etc/paths.d") or [])- return {"present": True, "entries": len(ents), "user": sum(1 for e in ents if e.startswith(U)),- "machine": sum(1 for e in ents if not e.startswith(U)), "tools": tools, "user_bin_dirs_off_path": off,- "paths_d_entries": helper}---_mirror("dev.ssh_config", ad.dev_ssh_config)--_TOOLCHAIN = ["node", "npm", "pnpm", "yarn", "bun", "deno", "fnm", "nvm", "volta", "uv", "pipx", "conda", "poetry",- "rustc", "cargo", "rustup", "go", "dotnet", "java", "javac", "mvn", "gradle", "cmake", "ninja", "make", "clang",- "gcc", "zig", "swift", "xcodebuild", "xcrun", "pod", "gh", "docker", "podman", "colima", "orb", "kubectl",- "terraform", "tailscale", "claude", "codex", "hermes", "ollama", "code", "cursor", "windsurf", "zed", "nvim",- "vim", "emacs", "python3", "python", "tmux", "zellij", "lazygit", "rg", "fd", "fzf", "zoxide", "mcfly",- "atuin", "btop", "htop", "jq", "ssh", "mosh", "brew", "mas", "gcloud", "aws", "vercel", "wrangler", "flyctl"]---@_mp("dev.toolchain_presence", level="L1", family=DEV, tier="T0", collect="core")-def dev_toolchain_presence(h, facts):- """which() for language/infra/AI/editor CLIs over PATH plus Homebrew and user tool dirs; off-PATH install dirs."""- U = _U(h)- found, user_found = [], []- for t in _TOOLCHAIN:- p = _which(h, t)- if p:- found.append(t)- if p.startswith(U):- user_found.append(t)- off = {k: _isdir(p) for k, p in [- ("cargo_home", os.path.join(U, ".cargo")), ("rustup", os.path.join(U, ".rustup")), ("go_root", "/usr/local/go"),- ("gopath", os.path.join(U, "go")), ("uv_pythons", _data(h, "uv", "python")), ("pyenv", os.path.join(U, ".pyenv")),- ("miniconda", os.path.join(U, "miniconda3")), ("anaconda", os.path.join(U, "anaconda3")),- ("miniforge", os.path.join(U, "miniforge3")), ("nvm", os.path.join(U, ".nvm")), ("sdkman", os.path.join(U, ".sdkman")),- ("android_sdk", _LIB(h, "Android", "sdk")), ("xcode", "/Applications/Xcode.app"),- ("xcode_derived_data", _LIB(h, "Developer", "Xcode", "DerivedData")), ("clt", "/Library/Developer/CommandLineTools"),- ("dotnet", os.path.join(U, ".dotnet")), ("rye", os.path.join(U, ".rye"))]}- return {"present": True, "on_path": found, "user_installed": user_found, "off_path": sorted(k for k, v in off.items() if v)}---@_mp("dev.toolchain_versions", level="L2", family=DEV, tier="T0", collect="extended", gate="dev.toolchain_presence",- timeout_ms=12000)-def dev_toolchain_versions(h, facts):- """--version spawns (parallel, gated on which) for runtimes, package managers, AI CLIs and infra CLIs.- `hermes --version` and `brew --version` are excluded (both start slow interpreters); versions come from files."""- from concurrent.futures import ThreadPoolExecutor- specs = [("node", ["--version"]), ("npm", ["--version"]), ("uv", ["--version"]), ("gh", ["--version"]),- ("git", ["--version"]), ("docker", ["--version"]), ("bun", ["--version"]), ("pnpm", ["--version"]),- ("deno", ["--version"]), ("rustc", ["--version"]), ("cargo", ["--version"]), ("go", ["version"]),- ("python3", ["--version"]), ("claude", ["--version"]), ("codex", ["--version"]), ("ollama", ["--version"]),- ("tmux", ["-V"]), ("nvim", ["--version"]), ("swift", ["--version"]), ("tailscale", ["version"])]- todo = [(n, [_which(h, n)] + a) for n, a in specs if _which(h, n)]- if "git" in dict(todo) and not _isdir("/Library/Developer/CommandLineTools") and not _isdir("/Applications/Xcode.app"):- todo = [t for t in todo if t[0] != "git"]-- def one(item):- name, args = item- rc, txt, ms = _spawn(args, timeout=3)- line = next((l.strip() for l in txt.splitlines() if l.strip()), None)- return name, {"version": ad._redact(line, 90) if line else None, "rc": rc, "ms": ms}- out = {}- with ThreadPoolExecutor(max_workers=6) as ex:- for name, r in ex.map(one, todo):- out[name] = r- return {"present": bool(out), "tools": out}---_EDITORS = {- # name: (app bundle names, extension dir(s), Application Support user dir)- "vscode": (["Visual Studio Code"], [".vscode/extensions"], "Code"),- "vscode_insiders": (["Visual Studio Code - Insiders"], [".vscode-insiders/extensions"], "Code - Insiders"),- "cursor": (["Cursor"], [".cursor/extensions"], "Cursor"),- "windsurf": (["Windsurf"], [".windsurf/extensions"], "Windsurf"),- "vscodium": (["VSCodium"], [".vscode-oss/extensions"], "VSCodium"),- "kiro": (["Kiro"], [".kiro/extensions"], "Kiro"),- "trae": (["Trae"], [".trae/extensions"], "Trae"),-}---@_mp("editor.vscode", level="L2", family=DEV, tier="T2", collect="core", gate="dev.toolchain_presence")-def editor_vscode(h, facts):- """VS Code family: extension ids (AI flagged), workspaces opened, MCP/chat; other editors (JetBrains, Zed, Xcode...)."""- U = _U(h)- out = {}- for name, (apps, extds, userd) in _EDITORS.items():- b = _app(h, *apps)- extd = next((os.path.join(U, e) for e in extds if _isdir(os.path.join(U, e))), None)- user = _AS(h, userd, "User") if userd else None- if not (b or extd or (user and _isdir(user))):- continue- ids = ad._ext_ids(extd) if extd else []- e = {"installed": bool(b), "version": (b or {}).get("version"), "extensions": len(ids), "extension_ids": ids[:80],- "ai_extensions": [i for i in ids if ad._AI_EXT.search(i)]}- if user and _isdir(user):- ws = _ls(os.path.join(user, "workspaceStorage"), 5000)- e["workspaces_opened"] = len(ws) if ws is not None else 0- e["settings_json"] = os.path.exists(os.path.join(user, "settings.json"))- e["keybindings_json"] = os.path.exists(os.path.join(user, "keybindings.json"))- e["profiles"] = len(_ls(os.path.join(user, "profiles")) or [])- mj = _read_json(os.path.join(user, "mcp.json"), jsonc=True)- e["mcp_servers"] = len((mj.get("servers") or mj.get("mcpServers") or {})) if isinstance(mj, dict) else 0- e["chat_sessions"] = len(glob.glob(os.path.join(user, "workspaceStorage", "*", "chatSessions", "*"))[:5000])- e["user_mtime"] = _mtime(user)- out[name] = e- other = {"jetbrains": [x for x in (_ls(_AS(h, "JetBrains")) or []) if re.match(r"^[A-Za-z]+\d{4}\.\d", x)],- "zed": bool(_app(h, "Zed")) or _isdir(_cfg(h, "zed")), "xcode": bool(_app(h, "Xcode")),- "neovim_config": _isdir(_cfg(h, "nvim")), "vimrc": _ex(os.path.join(U, ".vimrc"), os.path.join(U, ".vim")),- "emacs": _ex(os.path.join(U, ".emacs.d"), os.path.join(U, ".emacs"), _cfg(h, "emacs")),- "helix": _isdir(_cfg(h, "helix")), "sublime": _isdir(_AS(h, "Sublime Text")) or bool(_app(h, "Sublime Text")),- "nova": bool(_app(h, "Nova")), "bbedit": bool(_app(h, "BBEdit"))}- other = {k: v for k, v in other.items() if v}- customised = any(e["extensions"] or e.get("settings_json") or e.get("keybindings_json") for e in out.values()) or \- bool(other.get("neovim_config") or other.get("emacs"))- return {"present": bool(out or other), "extensions": sum(e["extensions"] for e in out.values()),- "customised": customised, "editors": out, "other": other}---# ---------------- repos (deep)--_REPO_SKIP = {"node_modules", ".cache", "__pycache__", ".venv", "venv", "site-packages", ".npm", ".rustup", ".cargo",- ".bun", ".vscode", ".cursor", ".trash", "target", "dist", "build", ".next", ".git", "go", ".gradle", ".m2",- ".nvm", ".pyenv", "miniconda3", "anaconda3", ".docker", ".ollama", ".orbstack", "library", "applications",- "movies", "music", "pictures", ".rye", ".lmstudio", ".colima"}---def _repos_mac(h):- """Bounded repo walk: home depth 5, 60k dirs, 8 s; ~/Library and media folders skipped;- classes user_area / tool_managed (dot dirs) / operator."""- def build():- deadline = time.perf_counter() + 8.0- U = _U(h)- hits, seen, visited = [], set(), [0]- stack = [(U, 0)]- while stack and time.perf_counter() < deadline and visited[0] < 60000:- d, depth = stack.pop()- visited[0] += 1- try:- with os.scandir(d) as it:- ents = list(zip(range(3000), it))- except OSError:- continue- names = {e.name for _, e in ents}- if ".git" in names and (os.path.exists(os.path.join(d, ".git", "HEAD")) or os.path.isfile(os.path.join(d, ".git"))):- rp = os.path.realpath(d)- if rp not in seen:- seen.add(rp)- hits.append(d)- continue- if depth >= 5:- continue- for _, e in ents:- if e.name.lower() in _REPO_SKIP or e.name.startswith(".Trash"):- continue- try:- if not e.is_dir(follow_symlinks=False):- continue- except OSError:- continue- stack.append((e.path, depth + 1))- repos = []- for d in hits[:300]:- rel = os.path.relpath(d, U)- cls = "operator" if _is_op(h, d) else "tool_managed" if rel.startswith(".") else "user_area"- gd = os.path.join(d, ".git")- remotes, branch, head_mtime, local_email = [], None, None, None- if os.path.isdir(gd):- try:- with open(os.path.join(gd, "HEAD"), encoding="utf-8", errors="replace") as f:- hd = f.read(200).strip()- branch = hd[16:] if hd.startswith("ref: refs/heads/") else "detached"- except OSError:- pass- head_mtime = _mtime(os.path.join(gd, "logs", "HEAD")) or _mtime(os.path.join(gd, "index"))- try:- with open(os.path.join(gd, "config"), encoding="utf-8", errors="replace") as f:- cfg = f.read(100_000)- remotes = re.findall(r"^\s*url\s*=\s*(\S+)", cfg, re.M)- m = re.search(r"^\s*email\s*=\s*(\S+)", cfg, re.M)- local_email = m.group(1).lower() if m else None- except OSError:- pass- markers = [m for m in ("package.json", "pyproject.toml", "uv.lock", "Cargo.toml", "go.mod", "pom.xml",- "build.gradle", "Dockerfile", "flake.nix", "Package.swift", "AGENTS.md", "CLAUDE.md", ".mcp.json")- if os.path.exists(os.path.join(d, m))]- if any(n.endswith(".xcodeproj") for n in (_ls(d, 300) or [])):- markers.append("xcodeproj")- repos.append({"path": d, "class": cls, "branch": branch, "head_mtime": head_mtime, "remotes": remotes,- "local_email": local_email, "markers": markers})- return {"repos": repos, "visited_dirs": visited[0], "timed_out": time.perf_counter() >= deadline}- return build---def _commits_mac(h):- def build():- git = _which(h, "git")- if not git:- return None- env_ids = {x.strip().lower() for x in os.environ.get("UIL_GIT_IDENTITY", "").split(",") if x.strip()}- ids = set(env_ids)- for gc in (os.path.join(_U(h), ".gitconfig"), _cfg(h, "git", "config")):- try:- with open(gc, encoding="utf-8", errors="replace") as f:- ids |= {m.lower() for m in re.findall(r"^\s*email\s*=\s*(\S+)", f.read(100_000), re.M)}- except OSError:- pass- res = {"identity_sources": {"env": bool(env_ids), "global": bool(ids - env_ids), "repo_local": 0}, "by_class": {},- "hours_local": collections.Counter(), "tz_offsets": collections.Counter(), "weekday": collections.Counter(),- "month": collections.Counter(), "repos_with_own": {}}- # Newest HEAD first, so when the deadline cuts the scan it drops the stalest repos, not a random set.- deadline = time.perf_counter() + 10.0- res["repos_scanned"], res["timed_out"] = 0, False- for x in sorted(ad._repos(h)["repos"], key=lambda r: str(r.get("head_mtime") or ""), reverse=True):- if x["class"] == "operator":- continue- if time.perf_counter() > deadline:- res["timed_out"] = True- break- rid = set(ids)- if x["local_email"]:- rid.add(x["local_email"])- res["identity_sources"]["repo_local"] += 1- rc, txt, _ms = _spawn([git, "-C", x["path"], "log", "--all", "--no-merges",- "--format=%ae%x09%an%x09%at%x09%ai", "-n", "100000"], timeout=max(0.5, deadline - time.perf_counter()))- if rc != 0:- continue- res["repos_scanned"] += 1- mine = total = 0- for line in txt.splitlines():- parts = line.split("\t")- if len(parts) < 4:- continue- total += 1- if parts[0].lower() in rid or parts[1].lower() in rid:- mine += 1- try:- t = dt.datetime.fromtimestamp(int(parts[2]))- res["hours_local"][t.hour] += 1- res["weekday"][t.strftime("%a")] += 1- res["month"][t.strftime("%Y-%m")] += 1- except (ValueError, OSError):- pass- res["tz_offsets"][parts[3].strip()[-5:]] += 1- c = res["by_class"].setdefault(x["class"], [0, 0])- c[0] += mine- c[1] += total- if mine:- res["repos_with_own"][x["class"]] = res["repos_with_own"].get(x["class"], 0) + 1- return res- return build---def _prime_repos(h):- ad._memo(h, "repos", _repos_mac(h))---def _prime_commits(h):- _prime_repos(h)- ad._memo(h, "commits", _commits_mac(h))---# dev.repos and dev.repos.remotes need only the walk; priming commits there made them wait for git log on every repo.-_mirror("dev.repos", ad.dev_repos, _prime_repos)-_mirror("dev.repos.remotes", ad.dev_repos_remotes, _prime_repos)-_mirror("dev.repos.my_commits", ad.dev_repos_my_commits, _prime_commits)-_mirror("dev.repos.commit_hours", ad.dev_repos_commit_hours, _prime_commits)--_BUILTINS = {"cd", "export", "source", ".", "alias", "unalias", "echo", "exit", "history", "set", "unset", "eval", "exec",- "type", "which", "for", "if", "while", "sudo", "time", "nohup", "env", "clear", "pwd", "ls", "ll", "la", "fg",- "bg", "jobs", "kill", "z", "zi", "man", "help", "open", "defaults", "killall"}---def _cmd_name(line, known):- t = line.strip().split()- while t and (t[0] in ("sudo", "time", "nohup", "env", "exec") or "=" in t[0]):- t = t[1:]- if not t:- return None- c = os.path.basename(t[0])- if not re.fullmatch(r"[A-Za-z0-9._+\-]{1,32}", c):- return None- return c if c in _BUILTINS or c in known else None---@_mp("dev.shell_history", level="L2", family=DEV, tier="T1", collect="extended", gate="dev.path_entries")-def dev_shell_history(h, facts):- """zsh/bash/fish/python/node history: line counts, last write, top command names (resolved executables or- builtins only), Apple Terminal ~/.zsh_sessions count. Command lines, arguments and paths are never emitted."""- U = _U(h)- files = [("zsh", os.environ.get("HISTFILE") or os.path.join(U, ".zsh_history")), ("bash", os.path.join(U, ".bash_history")),- ("fish", _data(h, "fish", "fish_history")), ("python", os.path.join(U, ".python_history")),- ("node", os.path.join(U, ".node_repl_history")), ("mcfly_db", _AS(h, "McFly", "history.db")),- ("atuin_db", _data(h, "atuin", "history.db"))]- known = set()- for d in os.environ.get("PATH", "").split(":") + _extra_bins(h):- known.update(_ls(d, 20000) or [])- out, cmds, total = {}, collections.Counter(), 0- seen = set()- for label, p in files:- try:- rp = os.path.realpath(p)- if rp in seen:- continue- st = os.stat(p)- except OSError:- continue- seen.add(rp)- if label.endswith("_db"):- out[label] = {"bytes": st.st_size, "mtime": _day(st.st_mtime)}- continue- if st.st_size > 50_000_000:- out[label] = {"bytes": st.st_size, "lines": None, "mtime": _day(st.st_mtime)}- continue- n = 0- with open(p, "rb") as f:- for raw in f:- line = raw.decode("utf-8", "replace").strip()- if not line:- continue- if label == "fish":- if not line.startswith("- cmd: "):- continue- line = line[7:]- elif label == "zsh":- line = re.sub(r"^: \d+:\d+;", "", line)- n += 1- if label in ("bash", "zsh", "fish"):- c = _cmd_name(line, known)- if c:- cmds[c] += 1- out[label] = {"lines": n, "bytes": st.st_size, "mtime": _day(st.st_mtime)}- if label in ("bash", "zsh", "fish"):- total += n- zs = _ls(os.path.join(U, ".zsh_sessions"), 20000)- if zs:- out["zsh_sessions"] = {"files": sum(1 for x in zs if x.endswith(".history")), "mtime": _day(_newest_mtime([os.path.join(U, ".zsh_sessions")]))}- if not out:- return {"present": False}- return {"present": True, "lines": total, "files": out, "top_commands": dict(cmds.most_common(15)),- "distinct_commands": len(cmds), "login_shell": os.path.basename(os.environ.get("SHELL", ""))}---def _docker_sock(h):- for p in (os.path.join(_U(h), ".docker", "run", "docker.sock"), "/var/run/docker.sock",- os.path.join(_U(h), ".orbstack", "run", "docker.sock"), os.path.join(_U(h), ".colima", "default", "docker.sock")):- try:- import stat as _st- if _st.S_ISSOCK(os.stat(p).st_mode):- return p- except OSError:- continue- return None---@_mp("dev.docker", level="L1", family=DEV, tier="T0", collect="core")-def dev_docker(h, facts):- """Docker on macOS: CLI, Docker Desktop / OrbStack / Colima installs, live engine socket (daemon running)."""- cli = _which(h, "docker")- desktop = bool(_app(h, "Docker")) or _isdir(_LIB(h, "Group Containers", "group.com.docker"))- orb = bool(_app(h, "OrbStack")) or _isdir(os.path.join(_U(h), ".orbstack"))- colima = _isdir(os.path.join(_U(h), ".colima"))- if not (cli or desktop or orb or colima):- return None- sock = _docker_sock(h)- return {"present": True, "cli": bool(cli), "docker_desktop": desktop, "orbstack": orb, "colima": colima,- "engine_socket": bool(sock), "socket_access": bool(sock and os.access(sock, os.R_OK | os.W_OK)),- "podman": bool(_which(h, "podman"))}---def _gb(s):- m = re.match(r"([\d.]+)\s*([kKMGT]?B)", s or "")- if not m:- return 0.0- return float(m.group(1)) * {"B": 1e-9, "kB": 1e-6, "KB": 1e-6, "MB": 1e-3, "GB": 1.0, "TB": 1e3}.get(m.group(2), 0)---@_mp("dev.docker_runtime", level="L2", family=DEV, tier="T2", collect="extended", gate="dev.docker", timeout_ms=8000)-def dev_docker_runtime(h, facts):- """`docker ps` names/images and `docker images` repos/sizes only, only when an engine socket is live."""- d = _fact(facts, "dev.docker") or {}- cli = _which(h, "docker")- if not cli or not d.get("socket_access"):- return {"present": True, "accessible": False, "count": 0}- rc, ps, ms1 = _spawn([cli, "ps", "--format", "{{.Names}}\t{{.Image}}\t{{.RunningFor}}"], timeout=5)- rc2, im, ms2 = _spawn([cli, "images", "--format", "{{.Repository}}:{{.Tag}}\t{{.Size}}"], timeout=5)- if rc != 0 and rc2 != 0:- return {"present": True, "accessible": False, "count": 0}- running = [dict(zip(("name", "image", "up"), l.split("\t"))) for l in ps.splitlines() if l.strip()]- images = [l.split("\t") for l in im.splitlines() if l.strip()]- return {"present": True, "accessible": True, "count": len(running),- "running": [{"name": r.get("name"), "image": (r.get("image") or "").split("@")[0][:80], "up": r.get("up")}- for r in running[:40]],- "images": len(images), "images_gb": round(sum(_gb(x[1]) for x in images if len(x) > 1), 2),- "image_repos": sorted({x[0].rsplit(":", 1)[0] for x in images})[:40], "ms": round(ms1 + ms2, 1)}---@_mp("dev.multiplexers", level="L2", family=DEV, tier="T1", collect="core", gate="dev.toolchain_presence")-def dev_multiplexers(h, facts):- """tmux / zellij / screen session counts for this user (session names not emitted); terminal apps installed."""- uid = os.getuid()- out = {}- tdir = os.path.join(os.environ.get("TMUX_TMPDIR", "/private/tmp"), f"tmux-{uid}")- socks = [os.path.join(tdir, n) for n in (_ls(tdir) or [])]- tm = _which(h, "tmux")- if socks or tm:- n = 0- for s in socks[:10]:- rc, txt, _ = _spawn([tm, "-S", s, "ls"], timeout=2) if tm else (None, "", 0)- if rc == 0:- n += len([l for l in txt.splitlines() if l.strip()])- out["tmux"] = {"installed": bool(tm), "sockets": len(socks), "sessions": n,- "config": _ex(os.path.join(_U(h), ".tmux.conf"), _cfg(h, "tmux", "tmux.conf"))}- zj = _which(h, "zellij")- tmp = os.environ.get("TMPDIR") or "/tmp"- zsocks = [p for p in glob.glob(os.path.join(tmp, "zellij-*", "*", "*")) if not os.path.isdir(p)]- zres = glob.glob(_LIB(h, "Caches", "org.Zellij-Contributors.Zellij", "*", "session_info", "*"))- if zj or zsocks or zres:- out["zellij"] = {"installed": bool(zj), "live_sessions": len(zsocks), "resurrectable": len(zres),- "config": _isdir(_cfg(h, "zellij"))}- terms = [n for n in ("iTerm", "Ghostty", "WezTerm", "Alacritty", "kitty", "Warp", "cmux", "Hyper", "Tabby")- if _app(h, n)]- if terms:- out["terminal_apps"] = terms- if not out:- return {"present": False}- return {"present": True, "count": sum(v.get("sessions", 0) + v.get("live_sessions", 0) for v in out.values()- if isinstance(v, dict)), **out}---# ================================================================== browser--_CHROMIUM = [("chrome", ("Google", "Chrome")), ("chrome_beta", ("Google", "Chrome Beta")),- ("chrome_canary", ("Google", "Chrome Canary")), ("chromium", ("Chromium",)),- ("brave", ("BraveSoftware", "Brave-Browser")), ("brave_beta", ("BraveSoftware", "Brave-Browser-Beta")),- ("brave_nightly", ("BraveSoftware", "Brave-Browser-Nightly")), ("edge", ("Microsoft Edge",)),- ("edge_beta", ("Microsoft Edge Beta",)), ("edge_dev", ("Microsoft Edge Dev",)), ("vivaldi", ("Vivaldi",)),- ("opera", ("com.operasoftware.Opera",)), ("arc", ("Arc", "User Data")), ("dia", ("Dia", "User Data")),- ("comet", ("Comet",)), ("helium", ("net.imput.helium",)), ("thorium", ("Thorium",)),- ("aside", ("Aside",)), ("atlas", ("com.openai.atlas", "browser-data", "host")), ("sidekick", ("Sidekick",)),- ("yandex", ("Yandex", "YandexBrowser"))]---def _gecko_roots(h):- return [("firefox", _AS(h, "Firefox")), ("zen", _AS(h, "zen")), ("librewolf", _AS(h, "librewolf")),- ("floorp", _AS(h, "Floorp")), ("waterfox", _AS(h, "Waterfox")), ("tor", _AS(h, "TorBrowser-Data"))]---def _catalog_mac(h):- found_c, found_g = {}, {}- n = 0- for bid, rel in _CHROMIUM:- n += 1- p = _AS(h, *rel)- if _isdir(p) and os.path.exists(os.path.join(p, "Local State")):- found_c[bid] = p- for bid, root in _gecko_roots(h):- n += 1- ok = _isdir(root) if bid == "tor" else os.path.isfile(os.path.join(root, "profiles.ini"))- if ok:- found_g[bid] = root- return {"chromium": found_c, "gecko": found_g, "checked": n}---def _prime_browser(h):- bf._cached(h, "catalog", _catalog_mac)---SAFARI_HISTORY = ("Library", "Safari", "History.db")---@_mp("browser.catalog", level="L1", family=BROWSER, tier="T0", collect="core")-def browser_catalog(h, facts):- """Chromium (~/Library/Application Support: Chrome, Brave, Edge, Arc, Dia, Vivaldi, Opera, ...), Gecko and Safari roots."""- c = bf._cached(h, "catalog", _catalog_mac)- saf = _fda_meta(os.path.join(_U(h), *SAFARI_HISTORY))- return {"present": bool(c["chromium"] or c["gecko"] or saf.get("present")), "chromium": sorted(c["chromium"]),- "gecko": sorted(c["gecko"]), "safari_history": saf, "checked": c["checked"] + 1}---@_mp("browser.brave.present", level="L1", family=BROWSER, tier="T0", collect="core")-def brave_present(h, facts):- """Brave user-data dir exists."""- p = _AS(h, "BraveSoftware", "Brave-Browser")- if not _isdir(p):- return {"present": False}- return {"present": True, "local_state_mtime": bf._iso(h.meta(os.path.join(p, "Local State")).get("mtime"))}---@_mp("browser.edge.present", level="L1", family=BROWSER, tier="T0", collect="core")-def edge_present(h, facts):- """Microsoft Edge user-data dir with a Local State (on macOS Edge is never preinstalled)."""- p = _AS(h, "Microsoft Edge")- if not os.path.exists(os.path.join(p, "Local State")):- return {"present": False, "dir_only": _isdir(p)}- return {"present": True, "local_state_mtime": bf._iso(h.meta(os.path.join(p, "Local State")).get("mtime"))}---def _ls_handlers(h):- """LaunchServices handler table: {scheme or content type: bundle id} from launchservices.secure.plist."""- def build():- d = _plist(_LIB(h, "Preferences", "com.apple.LaunchServices", "com.apple.launchservices.secure.plist")) or {}- out = {}- for e in d.get("LSHandlers", []) if isinstance(d, dict) else []:- if not isinstance(e, dict):- continue- key = e.get("LSHandlerURLScheme") or e.get("LSHandlerContentType")- val = e.get("LSHandlerRoleAll") or e.get("LSHandlerRoleViewer") or e.get("LSHandlerRoleEditor")- if key and val and key not in out:- out[str(key).lower()] = str(val)- return out- return _memo(h, "ls_handlers", build)---_BROWSER_IDS = [("brave", r"com\.brave\.browser"), ("chrome", r"com\.google\.chrome"), ("chromium", r"org\.chromium"),- ("firefox", r"org\.mozilla\.firefox"), ("edge", r"com\.microsoft\.edgemac"), ("vivaldi", r"vivaldi"),- ("opera", r"operasoftware"), ("arc", r"company\.thebrowser\.browser"), ("dia", r"company\.thebrowser\.dia"),- ("safari", r"com\.apple\.safari"), ("zen", r"zen"), ("comet", r"perplexity|comet"), ("aside", r"aside"),- ("atlas", r"com\.openai\.atlas"), ("orion", r"kagi"), ("helium", r"helium")]---def _browser_of(bid):- d = (bid or "").lower()- return next((b for b, rx in _BROWSER_IDS if re.search(rx, d)), bid)---@_mp("browser.default", level="L1", family=BROWSER, tier="T0", collect="core")-def browser_default(h, facts):- """Default browser from the LaunchServices handler for https/http (Safari when no user handler is set)."""- m = _ls_handlers(h)- pid = m.get("https") or m.get("http") or m.get("public.html")- return {"present": True, "browser": _browser_of(pid) if pid else "safari", "prog_id": pid or "com.apple.safari",- "set_by_user": bool(pid), "handlers": {k: _browser_of(m[k]) for k in ("https", "http", "public.html") if k in m}}---@_mp("defaults.mailto_pdf_media", level="L1", family=BROWSER, tier="T0", collect="core")-def defaults_mailto_pdf_media(h, facts):- """User-set default handlers (bundle ids) for mailto, PDF, video, audio, images, text, source code."""- m = _ls_handlers(h)- keys = {"mailto": "mailto", ".pdf": "com.adobe.pdf", ".mp4": "public.mpeg-4", ".mkv": "org.matroska.mkv",- ".mp3": "public.mp3", ".jpg": "public.jpeg", ".png": "public.png", ".txt": "public.plain-text",- ".md": "net.daringfireball.markdown", ".py": "public.python-script", "source": "public.source-code",- "ssh": "ssh", "vscode": "vscode"}- got = {k: m[v] for k, v in keys.items() if v in m}- return {"present": bool(got), "handlers": got, "user_handlers_total": len(m)}---@_mp("browser.registered", level="L2", family=BROWSER, tier="T0", collect="core", gate="apps.uninstall")-def browser_registered(h, facts):- """Installed browser app bundles (by bundle id)."""- names = sorted({_browser_of(b["bundle_id"]) for b in _bundles(h)- if b["bundle_id"] and _browser_of(b["bundle_id"]) != b["bundle_id"]})- return {"present": bool(names), "browsers": names}---_T3_CHROMIUM = ("Cookies", "Network/Cookies", "Login Data", "Login Data For Account", "Web Data", "Account Web Data")-_T3_GECKO = ("cookies.sqlite", "logins.json", "key4.db", "formhistory.sqlite")---@_mp("browser.t3_presence", level="L1", family=BROWSER, tier="T3", collect="core")-def browser_t3_presence(h, facts):- """Credential/cookie stores per profile (Chromium, Gecko, Safari): stat only (size), never opened."""- _prime_browser(h)- rows = {}- for bid, ud, pdir, _i in bf._profiles(h):- base = os.path.join(ud, pdir) if pdir else ud- sizes = {f.replace("Network/", ""): m["bytes"] for f in _T3_CHROMIUM- for m in [h.meta(os.path.join(base, f))] if m.get("present")}- if sizes:- rows[bf._pkey(bid, pdir)] = sizes- for bid, root in bf._cached(h, "catalog", _catalog_mac)["gecko"].items():- for pd in glob.glob(os.path.join(root, "Profiles", "*"))[:30]:- sizes = {f: m["bytes"] for f in _T3_GECKO for m in [h.meta(os.path.join(pd, f))] if m.get("present")}- if sizes:- rows[f"{bid}:{len(rows)}"] = sizes- saf = {f: m["bytes"] for f, p in (("Cookies.binarycookies", _LIB(h, "Containers", "com.apple.Safari", "Data", "Library",- "Cookies", "Cookies.binarycookies")),- ("Cookies.binarycookies_legacy", _LIB(h, "Cookies", "Cookies.binarycookies")))- for m in [h.meta(p)] if m.get("present")}- if saf:- rows["safari"] = saf- return {"present": bool(rows), "profiles": rows}---@_mp("browser.generic_sweep", level="L1", family=BROWSER, tier="T0", collect="extended")-def browser_generic_sweep(h, facts):- """Chromium-style user-data dirs under ~/Library/Application Support not in the catalog (Local State + Default- profile). Electron apps have a Local State but no Default profile and are not counted."""- known = {os.path.realpath(p) for p in bf._cached(h, "catalog", _catalog_mac)["chromium"].values()}- unknown = []- for pat in (_AS(h, "*", "Local State"), _AS(h, "*", "*", "Local State"), _AS(h, "*", "*", "*", "Local State")):- for p in glob.glob(pat)[:300]:- d = os.path.dirname(p)- if os.path.realpath(d) not in known and os.path.isfile(os.path.join(d, "Default", "History")) \- and _isdir(os.path.join(d, "Default", "Extensions")) and not _is_op(h, d) \- and not re.search(r"/Caches/|/htmlcache", d):- unknown.append(os.path.relpath(d, _U(h)))- return {"present": True, "unknown_forks": len(unknown), "roots": unknown[:10]}---for _id, _fn in (("browser.local_state", bf.browser_local_state), ("browser.tab_stats", bf.browser_tab_stats),- ("browser.profile_prefs", bf.browser_profile_prefs), ("browser.extensions", bf.browser_extensions),- ("browser.bookmarks", bf.browser_bookmarks), ("browser.history.copy", bf.history_copy),- ("browser.history.stats", bf.history_stats), ("browser.history.hour_weekday", bf.history_hour_weekday),- ("browser.history.top_domains", bf.history_top_domains),- ("browser.history.top_domains_named", bf.history_top_domains_named),- ("browser.history.localhost", bf.history_localhost), ("browser.history.downloads", bf.history_downloads),- ("browser.history.search_terms", bf.history_search_terms),- ("browser.history.github_repos", bf.history_github_repos), ("browser.firefox.history", bf.firefox_history),- ("l3.browser_category_share", bf.l3_browser_category_share), ("l3.primary_browser", bf.l3_primary_browser),- ("l3.browser_rhythm", bf.l3_browser_rhythm), ("l3.browser_persona_hints", bf.l3_browser_persona_hints),- ("browser.history.workspaces", bf.history_workspaces), ("browser.history.work_hosts", bf.history_work_hosts)):- _mirror(_id, _fn, _prime_browser)---@_mp("browser.safari.history", level="L2", family=BROWSER, tier="T1", collect="extended", gate="browser.catalog",- timeout_ms=5000)-def safari_history(h, facts):- """Safari History.db aggregates: visits, URLs, first/last visit, active days, hour histogram, domain-category- shares (sensitive categories folded). No URLs, titles or domains are emitted. Needs Full Disk Access."""- p = os.path.join(_U(h), *SAFARI_HISTORY)- m = _fda_meta(p)- if not m.get("present"):- return {"present": False}- if not m.get("readable"):- return {"present": False, "needs_fda": True, "bytes": m.get("bytes")}- rows = h.sqlite(p, "select v.visit_time, i.url from history_visits v join history_items i on i.id = v.history_item",- timeout_ms=4000)- if rows is None:- return {"present": False, "error": "query_failed"}- urls = h.sqlite(p, "select count(*) from history_items") or [[0]]- cats, days, hours = collections.Counter(), collections.Counter(), [0] * 24- ts = []- for vt, url in rows:- if vt is None:- continue- t = vt + MAC_EPOCH- ts.append(t)- lt = time.localtime(t)- days[time.strftime("%Y-%m-%d", lt)] += 1- hours[lt.tm_hour] += 1- host, _ = bf._host_of(url or "")- c = bf._categorize(bf._reg_domain(host)) if host else "other"- cats["sensitive" if c in bf.SENSITIVE_CATS else c] += 1- if not ts:- return {"present": False}- tot = sum(cats.values()) or 1- return {"present": True, "visits": len(ts), "urls": urls[0][0], "first_visit": bf._iso(min(ts)),- "last_visit": bf._iso(max(ts)), "active_days": len(days),- "visits_per_active_day": round(len(ts) / len(days), 1), "hours": hours,- "category_share": {k: round(v / tot, 3) for k, v in cats.most_common()}, "via": h.last_via}---# ================================================================== comms_work--def _app_row(h, apps, data_dirs, activity=()):- """installed/launched/last-used for one app. activity = files whose mtime means the app ran."""- b = _app(h, *apps) if apps else None- data = [p for p in data_dirs if _isdir(p)]- if not (b or data):- return None- last = _newest_mtime([a for a in activity if a] + data)- return {"installed": bool(b), "version": (b or {}).get("version"), "launched": bool(data), "last_used": _day(last),- "recent_use": bool(last and time.time() - last < 30 * 86400)}---def _comms_cands(h):- return {- "slack": (["Slack"], [_AS(h, "Slack")], [_AS(h, "Slack", "logs"), _AS(h, "Slack", "Local Storage")]),- "telegram": (["Telegram", "Telegram Desktop"], [_LIB(h, "Group Containers", "6N38VWS5BX.ru.keepcoder.Telegram"),- _AS(h, "Telegram Desktop")], []),- "signal": (["Signal"], [_AS(h, "Signal")], [_AS(h, "Signal", "logs")]),- "whatsapp": (["WhatsApp"], [_LIB(h, "Group Containers", "group.net.whatsapp.WhatsApp.shared")], []),- "zoom": (["zoom.us"], [_AS(h, "zoom.us")], [_AS(h, "zoom.us", "data")]),- "teams": (["Microsoft Teams", "Microsoft Teams (work or school)"], [_LIB(h, "Containers", "com.microsoft.teams2")], []),- "element": (["Element"], [_AS(h, "Element")], []),- "beeper": (["Beeper Desktop", "Beeper"], [_AS(h, "BeeperTexts")], []),- "outlook": (["Microsoft Outlook"], [_LIB(h, "Group Containers", "UBF8T346G9.Office", "Outlook")], []),- "apple_mail": (["Mail"], [_LIB(h, "Mail")], []),- "messages": ([], [_LIB(h, "Messages")], []),- "facetime": (["FaceTime"], [_AS(h, "FaceTime")], []),- "spark": (["Spark", "Spark Desktop"], [_LIB(h, "Group Containers", "3L68KQB4HG.group.com.readdle.smartemail")], []),- "superhuman": (["Superhuman"], [_AS(h, "Superhuman")], []),- "webex": (["Webex"], [_AS(h, "Cisco Spark")], []),- "around": (["Around"], [_AS(h, "Around")], []),- "linear": (["Linear"], [_AS(h, "Linear")], []),- "mattermost": (["Mattermost"], [_AS(h, "Mattermost")], []),- "skype": (["Skype"], [_AS(h, "Microsoft", "Skype for Desktop")], []),- }---@_mp("comms.native_apps", level="L1", family=COMMS, tier="T0", collect="core")-def comms_native_apps(h, facts):- """Native comms/mail apps: installed (bundle), launched (data dir exists), last-used day from data-dir mtimes."""- rows = {}- for app, (inst, data, act) in _comms_cands(h).items():- r = _app_row(h, inst, data, act)- if r:- rows[app] = r- if not rows:- return {"present": False}- return {"present": True, **rows}---@_mp("comms.teams_launched", level="L2", family=COMMS, tier="T0", collect="core", gate="comms.native_apps")-def comms_teams_launched(h, facts):- """New Teams for Mac actually started: com.microsoft.teams2 container with WebView profile dirs; tfw = work,- tfl = personal."""- b = _LIB(h, "Containers", "com.microsoft.teams2", "Data", "Library", "Application Support", "Microsoft", "MSTeams")- if not _isdir(b):- return {"present": False}- prof = h.list_dir(os.path.join(b, "EBWebView"), 100) + h.list_dir(os.path.join(b, "WebView"), 100)- work = sum(1 for p in prof if "tfw" in p.lower())- return {"present": True, "work_profile": work > 0, "work_profiles": work,- "personal_profiles": sum(1 for p in prof if "tfl" in p.lower()),- "log_files": max(h.count_dir(os.path.join(b, "Logs"), 5000), 0)}---@_mp("office.c2r", level="L1", family=COMMS, tier="T0", collect="core")-def office_c2r(h, facts):- """Microsoft 365 for Mac: Word/Excel/PowerPoint/Outlook/OneNote bundles and versions (licence kind is not- readable without opening the Office licensing store)."""- rows = {}- for n in ("Microsoft Word", "Microsoft Excel", "Microsoft PowerPoint", "Microsoft Outlook", "Microsoft OneNote"):- b = _app(h, n)- if b:- rows[n.split()[-1].lower()] = b["version"]- if not rows:- return {"present": False}- return {"present": True, "products": ",".join(sorted(rows)), "versions": rows, "platform": "mac",- "mas": any(b["mas"] for b in _bundles(h) if b["name"].startswith("Microsoft ")), "license_kind": None}---def _discord_dirs(h):- return [d for d in (_AS(h, "discord"), _AS(h, "discordcanary"), _AS(h, "discordptb")) if _isdir(d)]---@_mp("discord.present", level="L1", family=COMMS, tier="T0", collect="core")-def discord_present(h, facts):- """Discord desktop: app bundle, profile dir, version dir."""- b = _app(h, "Discord", "Discord Canary", "Discord PTB")- dirs = _discord_dirs(h)- if not (b or dirs):- return {"present": False}- vers = sorted(n for d in dirs for n in (_ls(d) or []) if re.fullmatch(r"\d+\.\d+\.\d+", n))- return {"present": True, "installed": bool(b), "profile_dir": bool(dirs),- "version": (b or {}).get("version") or (vers[-1] if vers else None)}---@_mp("discord.usage", level="L2", family=COMMS, tier="T1", collect="extended", gate="discord.present", timeout_ms=3000)-def discord_usage(h, facts):- """Signed-in and voice days from logs/renderer_js.log tags; last use from Local Storage mtime."""- dirs = _discord_dirs(h)- if not dirs:- return {"present": False}- days, gw, rtc = set(), set(), set()- size = 0- rx = re.compile(r"^\[(\d{4}-\d\d-\d\d) ([\d:.]+)\] \[\w+\]\s+\[?([A-Za-z_]+)")- for d in dirs:- for log in glob.glob(os.path.join(d, "logs", "renderer_js*.log"))[:5]:- size += os.path.getsize(log)- with open(log, encoding="utf-8", errors="replace") as fh:- if os.path.getsize(log) > 16_000_000:- fh.seek(os.path.getsize(log) - 16_000_000)- for line in fh:- m = rx.match(line)- if not m:- continue- dd, _tm, tag = m.groups()- days.add(dd)- if tag == "GatewaySocket":- gw.add(dd)- elif tag.startswith("RTC"):- rtc.add(dd)- ls = _newest_mtime([os.path.join(d, "Local Storage", "leveldb") for d in dirs])- used = bool(gw or rtc) or bool(ls and time.time() - ls < 90 * 86400)- return {"present": used, "log_days": len(days), "first_day": min(days) if days else None,- "last_day": max(days) if days else None, "gateway_days": len(gw), "rtc_days": len(rtc),- "local_storage_last": _day(ls), "log_bytes": size}---MESSAGES_DB = ("Library", "Messages", "chat.db")-NOTES_DB = ("Library", "Group Containers", "group.com.apple.notes", "NoteStore.sqlite")---@_mp("comms.imessage", level="L2", family=COMMS, tier="T1", collect="extended", gate="comms.native_apps", timeout_ms=5000)-def comms_imessage(h, facts):- """Messages chat.db record counts only: messages, chats, sent share, by service, first/last date, per-month- counts. No text, no handles, no attachments. Needs Full Disk Access."""- p = os.path.join(_U(h), *MESSAGES_DB)- m = _fda_meta(p)- if not m.get("present"):- return {"present": False}- if not m.get("readable"):- return {"present": False, "needs_fda": True, "bytes": m.get("bytes")}- r = h.sqlite(p, "select count(*), sum(is_from_me), min(date), max(date) from message", timeout_ms=4000)- if not r:- return {"present": False, "error": "query_failed"}- n, mine, a, z = r[0]- scale = 1e9 if (z or 0) > 1e12 else 1- chats = (h.sqlite(p, "select count(*) from chat") or [[None]])[0][0]- svc = dict(h.sqlite(p, "select coalesce(service,'?'), count(*) from message group by 1") or [])- cut = (time.time() - MAC_EPOCH - 30 * 86400) * scale- n30 = (h.sqlite(p, "select count(*) from message where date >= ?", (cut,)) or [[None]])[0][0]- months = dict(h.sqlite(p, f"select strftime('%Y-%m', date / {scale} + {MAC_EPOCH}, 'unixepoch'), count(*) "- "from message group by 1") or [])- return {"present": True, "messages": n, "sent_share": round((mine or 0) / n, 3) if n else None, "chats": chats,- "by_service": svc, "messages_30d": n30, "first": bf._iso(a / scale + MAC_EPOCH) if a else None,- "last": bf._iso(z / scale + MAC_EPOCH) if z else None, "by_month": dict(sorted(months.items())[-24:]),- "via": h.last_via}---def _notes_cands(h):- U = _U(h)- return {- "obsidian": (["Obsidian"], [_AS(h, "obsidian")], [_AS(h, "obsidian", "obsidian.json")]),- "notion": (["Notion"], [_AS(h, "Notion")], []),- "logseq": (["Logseq"], [os.path.join(U, ".logseq"), _AS(h, "Logseq")], []),- "apple_notes": (["Notes"], [_LIB(h, "Group Containers", "group.com.apple.notes")], []),- "bear": (["Bear"], [_LIB(h, "Group Containers", "9K33E3U3T4.net.shinyfrog.bear")], []),- "craft": (["Craft"], [_LIB(h, "Containers", "com.lukilabs.lukiapp")], []),- "joplin": (["Joplin"], [os.path.join(U, ".config", "joplin-desktop")], []),- "evernote": (["Evernote"], [_LIB(h, "Containers", "com.evernote.Evernote")], []),- "todoist": (["Todoist"], [_AS(h, "Todoist")], []),- "zotero": (["Zotero"], [_AS(h, "Zotero"), os.path.join(U, "Zotero")], []),- "granola": (["Granola"], [_AS(h, "Granola")], []),- "anytype": (["Anytype"], [_AS(h, "anytype")], []),- }---@_mp("productivity.notes_apps", level="L1", family=COMMS, tier="T0", collect="core")-def notes_apps(h, facts):- """Notes apps installed or launched: Obsidian, Notion, Logseq, Apple Notes, Bear, Craft, Zotero, ..."""- rows = {}- for app, (inst, data, act) in _notes_cands(h).items():- r = _app_row(h, inst, data, act)- if r:- rows[app] = r- return {"present": bool(rows), "apps": sorted(rows), "detail": rows}---@_mp("obsidian.vaults", level="L2", family=COMMS, tier="T1", collect="extended", gate="productivity.notes_apps")-def obsidian_vaults(h, facts):- """Obsidian vault count and note counts (vault names and paths are not emitted)."""- j = _read_json(_AS(h, "obsidian", "obsidian.json"))- vs = ((j or {}).get("vaults") or {}) if isinstance(j, dict) else {}- if not vs:- return {"present": False}- notes, files, newest = 0, 0, 0-- def on_file(e, s, depth):- nonlocal notes, newest- if e.name.lower().endswith(".md"):- notes += 1- newest = max(newest, s.st_mtime)- for v in list(vs.values())[:10]:- p = v.get("path") if isinstance(v, dict) else None- if p and _isdir(p) and p.startswith(_U(h)):- st = bf._walk(p, max_depth=6, max_entries=30000, budget_s=1.5, on_file=on_file,- skip_dir=lambda n, _p: n in (".obsidian", ".git", ".trash", "node_modules"))- files += st["files"]- return {"present": True, "vaults": len(vs), "open": sum(1 for v in vs.values() if isinstance(v, dict) and v.get("open")),- "notes_md": notes, "files": files, "newest_note": bf._iso(newest) if newest else None}---@_mp("productivity.apple_notes", level="L2", family=COMMS, tier="T1", collect="extended", gate="productivity.notes_apps",- timeout_ms=4000)-def apple_notes(h, facts):- """Apple Notes NoteStore.sqlite record counts only: notes, folders, accounts, created/modified range. No titles- or bodies. Needs Full Disk Access."""- p = os.path.join(_U(h), *NOTES_DB)- m = _fda_meta(p)- if not m.get("present"):- return {"present": False}- if not m.get("readable"):- return {"present": False, "needs_fda": True, "bytes": m.get("bytes")}- cols = {r[1] for r in (h.sqlite(p, "pragma table_info(ZICCLOUDSYNCINGOBJECT)") or [])}- if not cols:- return {"present": False, "error": "schema"}- crt = "ZCREATIONDATE3" if "ZCREATIONDATE3" in cols else "ZCREATIONDATE1" if "ZCREATIONDATE1" in cols else None- mod = "ZMODIFICATIONDATE1" if "ZMODIFICATIONDATE1" in cols else None- note_where = "ZNOTEDATA is not null" if "ZNOTEDATA" in cols else "ZTITLE1 is not null"- q = f"select count(*), min({crt or 'null'}), max({mod or 'null'}) from ZICCLOUDSYNCINGOBJECT where {note_where}"- if "ZMARKEDFORDELETION" in cols:- q += " and coalesce(ZMARKEDFORDELETION, 0) = 0"- r = h.sqlite(p, q) or [[0, None, None]]- folders = (h.sqlite(p, "select count(*) from ZICCLOUDSYNCINGOBJECT where ZTITLE2 is not null") or [[None]])[0][0] \- if "ZTITLE2" in cols else None- accts = (h.sqlite(p, "select count(*) from ZICCLOUDSYNCINGOBJECT where ZACCOUNTTYPE is not null") or [[None]])[0][0] \- if "ZACCOUNTTYPE" in cols else None- n, a, z = r[0]- n30 = None- if mod:- n30 = (h.sqlite(p, f"select count(*) from ZICCLOUDSYNCINGOBJECT where {note_where} and {mod} >= ?",- (time.time() - MAC_EPOCH - 30 * 86400,)) or [[None]])[0][0]- return {"present": bool(n), "notes": n, "folders": folders, "accounts": accts, "modified_30d": n30,- "first_created": bf._iso(a + MAC_EPOCH) if a else None, "last_modified": bf._iso(z + MAC_EPOCH) if z else None,- "via": h.last_via}---_EDR = {"crowdstrike": ["/Applications/Falcon.app", "/Library/CS"], "sentinelone": ["/Library/Sentinel", "/Applications/SentinelOne"],- "defender": ["/Applications/Microsoft Defender.app"], "jamf_protect": ["/Applications/JamfProtect.app"],- "jamf": ["/usr/local/jamf", "/Library/Application Support/JAMF"], "kandji": ["/Library/Kandji"],- "mosyle": ["/Library/Application Support/Mosyle"], "addigy": ["/Library/Addigy"],- "intune_agent": ["/Library/Intune", "/Applications/Company Portal.app"], "zscaler": ["/Applications/Zscaler"],- "netskope": ["/Library/Application Support/Netskope"], "globalprotect": ["/Applications/GlobalProtect.app"],- "cisco_secure_client": ["/opt/cisco/secureclient", "/opt/cisco/anyconnect"], "osquery": ["/private/var/osquery", "/opt/osquery"],- "kolide": ["/usr/local/kolide-k2"], "fleetd": ["/opt/orbit"], "santa": ["/Applications/Santa.app"],- "sophos": ["/Library/Sophos Anti-Virus"], "carbonblack": ["/Applications/VMware Carbon Black Cloud"],- "tanium": ["/Library/Tanium"], "lulu": ["/Applications/LuLu.app"], "little_snitch": ["/Applications/Little Snitch.app"],- "blockblock": ["/Applications/BlockBlock Helper.app"]}---@_mp("work.security_agents", level="L1", family=COMMS, tier="T0", collect="core")-def work_security_agents(h, facts):- """EDR/MDM/ZTNA agents and personal firewalls by install path (no launchctl queries)."""- hits = sorted(k for k, ps in _EDR.items() if _ex(*ps))- personal = {"lulu", "little_snitch", "blockblock"}- return {"present": True, "agents": [a for a in hits if a not in personal],- "personal_security_tools": [a for a in hits if a in personal], "checked": len(_EDR)}---@_mp("work.mdm", level="L1", family=COMMS, tier="T0", collect="core")-def work_mdm(h, facts):- """MDM enrollment: DEP activation record and enrollment markers under /var/db/ConfigurationProfiles, managed- preference domains under /Library/Managed Preferences (counts only; no `profiles` spawn)."""- cp = "/private/var/db/ConfigurationProfiles"- dep = _ex(os.path.join(cp, "Settings", ".cloudConfigHasActivationRecord"), os.path.join(cp, "Settings", ".cloudConfigRecordFound"))- enrolled = _ex(os.path.join(cp, "Settings", ".profilesAreInstalled"), os.path.join(cp, "Store", "ConfigProfiles.binary"))- managed = [n for n in (_ls("/Library/Managed Preferences") or []) if n.endswith(".plist")]- real = ["mdm"] if (enrolled and (dep or managed)) else []- return {"present": True, "real_enrollments": len(real), "enrollments": real, "dep_activation_record": dep,- "profiles_marker": enrolled, "managed_pref_domains": len(managed)}---@_mp("work.join_state", level="L1", family=COMMS, tier="T0", collect="core")-def work_join_state(h, facts):- """Directory binding: Active Directory plugin config, Kerberos SSO / Platform SSO extension presence."""- ad_cfg = _ex("/Library/Preferences/OpenDirectory/Configurations/Active Directory")- ad_bound = bool(_ls("/Library/Preferences/OpenDirectory/Configurations/Active Directory"))- psso = _ex("/Library/Preferences/com.apple.extensiblesso.plist", "/Library/Managed Preferences/com.apple.extensiblesso.plist")- return {"present": True, "state": "joined" if ad_bound else "workgroup", "domain_joined": ad_bound,- "ad_plugin_config": ad_cfg, "azure_ad_joined": psso, "platform_sso": psso}---@_mp("work.policies", level="L1", family=COMMS, tier="T0", collect="core")-def work_policies(h, facts):- """Managed app policy plists (Chrome, Edge, Brave, Firefox, Office) under /Library/Managed Preferences: counts."""- doms = {"chrome": "com.google.Chrome", "edge": "com.microsoft.Edge", "brave": "com.brave.Browser",- "firefox": "org.mozilla.firefox", "office": "com.microsoft.office", "safari": "com.apple.Safari"}- root = "/Library/Managed Preferences"- names = _ls(root) or []- user = _ls(os.path.join(root, os.environ.get("USER", ""))) or []- configured = {k: {"values": sum(1 for n in names + user if n.startswith(d)), "subkeys": 0} for k, d in doms.items()- if any(n.startswith(d) for n in names + user)}- return {"present": True, "app_policies": configured, "app_policy_count": len(configured)}---@_mp("onedrive.accounts", level="L1", family=COMMS, tier="T0", collect="core")-def onedrive_accounts(h, facts):- """OneDrive for Mac: app bundle and File Provider roots under ~/Library/CloudStorage (OneDrive-Personal /- OneDrive-TENANT). Folder names are not emitted."""- b = _app(h, "OneDrive")- roots = [n for n in (_ls(_LIB(h, "CloudStorage")) or []) if n.startswith("OneDrive")]- if not (b or roots):- return {"present": False}- return {"present": True, "installed": bool(b), "accounts": len(roots), "signed_in": len(roots),- "business": sum(1 for n in roots if n != "OneDrive-Personal")}---# ================================================================== files--def _known_folders_mac(h):- U = _U(h)- out = {n: os.path.join(U, n) for n in ("Desktop", "Documents", "Downloads", "Pictures", "Music")}- out["Videos"] = os.path.join(U, "Movies")- sc = _plist(_LIB(h, "Preferences", "com.apple.screencapture.plist")) or {}- loc = sc.get("location") if isinstance(sc, dict) else None- out["Screenshots"] = os.path.expanduser(loc) if isinstance(loc, str) and loc else out["Desktop"]- return out---def _prime_kf(h):- bf._cached(h, "kf", _known_folders_mac)---_STANDARD = {"desktop", "documents", "downloads", "pictures", "movies", "music", "public", "applications", "library"}---def _home_root(h):- U = _U(h)- cls, loose = collections.Counter(), 0- try:- ents = list(zip(range(5000), os.scandir(U)))- except OSError:- return None- for _, e in ents:- try:- is_dir = e.is_dir(follow_symlinks=False)- except OSError:- continue- if not is_dir:- loose += 0 if e.name.startswith(".") else 1- continue- low = e.name.lower()- cls["operator" if _OP_TOP.match(e.name) else "dot" if low.startswith(".") else- "standard" if low in _STANDARD else "custom"] += 1- return {"dirs_by_class": dict(cls), "loose_visible_files": loose}---@_mp("files.known_folders", level="L1", family=FILES, tier="T0", collect="core")-def files_known_folders(h, facts):- """Home folders (Desktop, Documents, Downloads, Pictures, Movies, Music) and the screenshot location;- whether Desktop & Documents sync to iCloud Drive."""- kf = bf._cached(h, "kf", _known_folders_mac)- U = _U(h)- icloud_dd = _isdir(_LIB(h, "Mobile Documents", "com~apple~CloudDocs", "Desktop"))- rows = {n: {"path": ("~" + p[len(U):]) if p and p.startswith(U) else p, "exists": bool(p and _isdir(p)),- "under_profile": bool(p and p.startswith(U)), "under_onedrive": False} for n, p in kf.items()}- return {"present": any(r["exists"] for r in rows.values()), "folders": rows, "icloud_desktop_documents": icloud_dd,- "screenshot_location_custom": kf["Screenshots"] != kf["Desktop"]}---@_mp("files.composition", level="L2", family=FILES, tier="T1", collect="extended", gate="files.known_folders",- timeout_ms=9000)-def files_composition(h, facts):- """Per home folder: files, bytes, extension/kind/age histograms (depth <= 6, 100k entries), plus home-root dir- classes (dot/standard/custom/operator). No file names."""- _prime_kf(h)- v = bf.files_composition(h, facts)- if isinstance(v, dict):- v["home_root"] = _home_root(h)- return v---_mirror("files.screenshots", bf.files_screenshots, _prime_kf)---@_mp("files.recent_lnk", level="L2", family=FILES, tier="T1", collect="core", gate="files.known_folders")-def files_recent_lnk(h, facts):- """Recent-document lists (com.apple.sharedfilelist *.sfl3): number of apps with a recent list, list file dates.- The lists themselves are not parsed. The directory is TCC-protected (Full Disk Access)."""- d = _AS(h, "com.apple.sharedfilelist", "com.apple.LSSharedFileList.ApplicationRecentDocuments")- if not _isdir(_AS(h, "com.apple.sharedfilelist")):- return {"present": False}- names = _ls(d, 2000)- if names is None:- return {"present": False, "needs_fda": True}- mts = [m for m in (_newest_mtime([os.path.join(d, n)]) for n in names if n.endswith((".sfl2", ".sfl3"))) if m]- now = time.time()- return {"present": bool(mts), "count": len(mts), "apps_with_recents": len(mts),- "oldest": bf._iso(min(mts)) if mts else None, "newest": bf._iso(max(mts)) if mts else None,- "active_days_30d": len({time.strftime("%Y-%m-%d", time.localtime(t)) for t in mts if now - t < 30 * 86400})}---@_mp("files.clutter", level="L2", family=FILES, tier="T1", collect="extended", gate="files.known_folders", timeout_ms=6000)-def files_clutter(h, facts):- """Trash (needs FDA), ~/Library/Caches size, this user's files in TMPDIR, Desktop item count (bounded walks)."""- _prime_kf(h)- out = {"present": True}- tr = os.path.join(_U(h), ".Trash")- if _dir_readable(tr):- st = bf._walk(tr, max_depth=6, max_entries=100000, budget_s=1.5)- out["recycle_bin"] = {"items": len(_ls(tr, 100000) or []), "files": st["files"], "bytes": st["bytes"],- "truncated": st["truncated"]}- else:- out["recycle_bin"] = {"needs_fda": _isdir(tr)}- st = bf._walk(_LIB(h, "Caches"), max_depth=6, max_entries=150000, budget_s=1.5)- out["cache_bytes"], out["cache_files"], out["cache_truncated"] = st["bytes"], st["files"], st["truncated"]- me, n, b = os.getuid(), [0], [0]-- def mine(e, s, depth):- if s.st_uid == me:- n[0] += 1- b[0] += s.st_size- tmp = os.environ.get("TMPDIR") or "/tmp"- st = bf._walk(tmp, max_depth=3, max_entries=50000, budget_s=1.0, on_file=mine,- skip_dir=lambda nm, p: nm == "userscan" or bool(_OP_DEEP.search(p)))- out["temp_files"], out["temp_bytes"], out["temp_truncated"] = n[0], b[0], st["truncated"]- desk = bf._kf(h, "Desktop")- names = [x for x in h.list_dir(desk, 5000) if not x.startswith(".")]- out["desktop_items"] = len(names)- out["desktop_screenshots"] = sum(1 for x in names if bf.SHOT_NAME.match(x))- return out---def _where_froms(path):- """kMDItemWhereFroms xattr (binary plist of source URLs) via getxattr(2); None when absent."""- try:- lib = _where_froms.lib- except AttributeError:- lib = _where_froms.lib = ctypes.CDLL(ctypes.util.find_library("c"), use_errno=True)- lib.getxattr.restype = ctypes.c_ssize_t- lib.getxattr.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_int]- name = b"com.apple.metadata:kMDItemWhereFroms"- p = os.fsencode(path)- n = lib.getxattr(p, name, None, 0, 0, 1) # XATTR_NOFOLLOW- if n <= 0 or n > 65536:- return None- buf = ctypes.create_string_buffer(n)- n = lib.getxattr(p, name, buf, n, 0, 1)- if n <= 0:- return None- try:- v = plistlib.loads(buf.raw[:n])- except Exception:- return None- return [x for x in v if isinstance(x, str)] if isinstance(v, list) else None---QUARANTINE = ("Library", "Preferences", "com.apple.LaunchServices.QuarantineEventsV2")---@_mp("files.download_sources", level="L2", family=FILES, tier="T1", collect="extended", gate="files.known_folders",- timeout_ms=6000)-def files_download_sources(h, facts):- """Where downloads come from, as counts: LaunchServices QuarantineEventsV2 (events by downloading app, by month,- source-site categories when a URL was recorded) and kMDItemWhereFroms xattrs on files in Downloads (depth <= 2):- source-site category counts and distinct host count. No hosts, URLs or file names are emitted."""- _prime_kf(h)- out = {"present": False}- q = os.path.join(_U(h), *QUARANTINE)- if os.path.exists(q):- rows = h.sqlite(q, "select LSQuarantineTimeStamp, LSQuarantineAgentName, LSQuarantineOriginURLString, "- "LSQuarantineDataURLString from LSQuarantineEvent")- if rows is not None:- agents, months, cats, hosts = collections.Counter(), collections.Counter(), collections.Counter(), set()- ts = []- for t, agent, origin, data in rows:- if t:- ts.append(t + MAC_EPOCH)- months[_day(t + MAC_EPOCH)[:7]] += 1- agents[(agent or "?")[:40]] += 1- url = origin or data- if url:- host, _ = bf._host_of(url)- if host:- hosts.add(host)- c = bf._categorize(bf._reg_domain(host))- cats["sensitive" if c in bf.SENSITIVE_CATS else c] += 1- out.update({"present": bool(rows), "quarantine": {- "events": len(rows), "first": bf._iso(min(ts)) if ts else None, "last": bf._iso(max(ts)) if ts else None,- "by_agent": dict(agents.most_common(10)), "by_month": dict(sorted(months.items())[-24:]),- "with_url": sum(cats.values()), "distinct_hosts": len(hosts), "source_categories": dict(cats.most_common())}})- root = bf._kf(h, "Downloads")- if _isdir(root):- cats, ext_cat, hosts = collections.Counter(), collections.Counter(), set()- n = with_x = 0- deadline = time.perf_counter() + 3.0- stack, trunc = [(root, 0)], None- while stack:- d, depth = stack.pop()- try:- entries = list(os.scandir(d))- except OSError:- continue- for e in entries:- try:- if e.is_dir(follow_symlinks=False):- if depth + 1 < 2 and not _OP_DEEP.search(e.path) and not e.name.endswith((".app", ".photoslibrary")):- stack.append((e.path, depth + 1))- continue- except OSError:- continue- n += 1- if n > 5000 or time.perf_counter() > deadline:- trunc = "cap"- stack.clear()- break- urls = _where_froms(e.path)- if not urls:- continue- with_x += 1- host, _ = bf._host_of(urls[0])- if host:- hosts.add(host)- c = bf._categorize(bf._reg_domain(host)) if host else "other"- c = "sensitive" if c in bf.SENSITIVE_CATS else c- cats[c] += 1- ext_cat[f"{c}:{os.path.splitext(e.name)[1].lower() or '(none)'}"] += 1- out["downloads_folder"] = {"files_scanned": n, "depth": 2, "truncated": trunc, "with_origin_xattr": with_x,- "distinct_hosts": len(hosts), "source_categories": dict(cats.most_common()),- "category_ext_top": dict(ext_cat.most_common(10))}- out["present"] = out["present"] or n > 0- return out---@_mp("files.profile_size_walk", level="L2", family=FILES, tier="T2", collect="deep", gate="files.known_folders",- timeout_ms=30000)-def files_profile_size_walk(h, facts):- """Size of each top-level home dir (depth <= 10, 300k entries/dir, 25 s total); operator dirs excluded."""- U = _U(h)- deadline = time.perf_counter() + 25.0- rows, loose = [], 0- try:- entries = list(os.scandir(U))- except OSError:- return {"present": False}- for e in entries:- try:- if not e.is_dir(follow_symlinks=False):- loose += 1- continue- except OSError:- continue- low = e.name.lower()- cls = ("operator" if _OP_TOP.match(e.name) else "dot" if low.startswith(".") else- "standard" if low in _STANDARD else "custom")- if cls == "operator":- rows.append({"name": e.name, "class": cls, "bytes": 0, "skipped": "operator"})- continue- remain = deadline - time.perf_counter()- if remain <= 0:- rows.append({"name": e.name, "class": cls, "bytes": 0, "skipped": "budget"})- continue- st = bf._walk(e.path, max_depth=10, max_entries=300000, budget_s=min(4.0, remain))- rows.append({"name": e.name, "class": cls, "bytes": st["bytes"], "files": st["files"], "truncated": st["truncated"]})- rows.sort(key=lambda r: -r["bytes"])- shown = 0- for r in rows:- if r["class"] == "custom":- shown += 1- if shown > 5:- r["name"] = f"custom#{shown}"- cls = collections.Counter(r["class"] for r in rows)- return {"present": True, "top_dirs": [r for r in rows if r["class"] != "operator"][:12], "class_counts": dict(cls),- "custom_root_dirs": cls.get("custom", 0), "operator_dirs_excluded": cls.get("operator", 0),- "custom_bytes": sum(r["bytes"] for r in rows if r["class"] == "custom"),- "total_bytes": sum(r["bytes"] for r in rows), "loose_root_files": loose,- "truncated_dirs": sum(1 for r in rows if r.get("truncated") or r.get("skipped") == "budget")}---@_mp("sync.other", level="L1", family=FILES, tier="T0", collect="core")-def sync_other(h, facts):- """Sync clients: iCloud Drive, Dropbox, Google Drive, Box, pCloud, Syncthing, MEGA, Proton Drive, Nextcloud- (File Provider roots under ~/Library/CloudStorage plus app data dirs). OneDrive is onedrive.accounts."""- cs = _ls(_LIB(h, "CloudStorage")) or []-- def root(prefix):- return any(n.startswith(prefix) for n in cs)- cands = {"icloud_drive": _isdir(_LIB(h, "Mobile Documents", "com~apple~CloudDocs")),- "dropbox": root("Dropbox") or _isdir(os.path.join(_U(h), ".dropbox")),- "google_drive": root("GoogleDrive") or _isdir(_AS(h, "Google", "DriveFS")),- "box": root("Box") or _isdir(_AS(h, "Box")), "pcloud": root("pCloud"),- "syncthing": _isdir(_AS(h, "Syncthing")) or _isdir(_LIB(h, "Application Support", "Syncthing")),- "mega": _isdir(_AS(h, "Mega Limited")), "proton_drive": root("ProtonDrive"),- "nextcloud": _isdir(_AS(h, "Nextcloud")) or root("Nextcloud")}- found = sorted(k for k, v in cands.items() if v)- return {"present": bool(found), "clients": found, "cloudstorage_roots": len(cs)}---# ================================================================== gaming--def _steam_root(h):- p = _AS(h, "Steam")- if _isdir(os.path.join(p, "steamapps")) or _isdir(os.path.join(p, "userdata")):- return p- return None---def _steam_mac(h):- def load():- sp = _steam_root(h)- if not sp:- return None- libs = []- txt = ug._read(os.path.join(sp, "steamapps", "libraryfolders.vdf"))- if txt:- for _k, v in (ug._ci(ug._vdf(txt), "libraryfolders") or {}).items():- if isinstance(v, dict) and v.get("path"):- libs.append(os.path.normpath(v["path"]))- libs = libs or [sp]- installed = []- for lib in libs[:20]:- sa = os.path.join(lib, "steamapps")- for n in h.list_dir(sa, 2000):- if n.startswith("appmanifest_") and n.endswith(".acf"):- st = ug._ci(ug._vdf(ug._read(os.path.join(sa, n)) or ""), "AppState") or {}- installed.append({"appid": int(st.get("appid", 0) or 0), "name": st.get("name"),- "size_gb": round(int(st.get("SizeOnDisk", 0) or 0) / 1e9, 1),- "drive": "home" if lib.startswith(_U(h)) else "other",- "last_played": int(st.get("LastPlayed", 0) or 0)})- ud = os.path.join(sp, "userdata")- uids = [u for u in h.list_dir(ud, 50) if u.isdigit()]- users = {}- for uid in uids:- apps = {}- t = ug._read(os.path.join(ud, uid, "config", "localconfig.vdf"))- if t:- node = ug._ci(ug._vdf(t), "UserLocalConfigStore", "Software", "Valve", "Steam", "apps") or {}- for aid, v in node.items():- if isinstance(v, dict) and aid.isdigit() and ("Playtime" in v or "LastPlayed" in v):- apps[int(aid)] = {"min": int(v.get("Playtime", 0) or 0), "min2wk": int(v.get("Playtime2wks", 0) or 0),- "last": int(v.get("LastPlayed", 0) or 0)}- users[uid] = apps- return {"path": sp, "libs": libs, "installed": installed, "uids": uids, "users": users,- "appinfo_path": os.path.join(sp, "appcache", "appinfo.vdf")}- return load---def _prime_steam(h):- ug._cached(("steam", h.l0.get("run_id")), _steam_mac(h))---@_mp("steam.present", level="L1", family=GAMING, tier="T0", collect="core")-def steam_present(h, facts):- """Steam client data dir (~/Library/Application Support/Steam) and app bundle; gates the Steam subtree."""- sp = _steam_root(h)- if not sp:- return None- b = _app(h, "Steam")- return {"present": True, "via": "native", "app": bool(b), "userdata_accounts": len([u for u in (_ls(os.path.join(sp, "userdata")) or [])- if u.isdigit()])}---for _id, _fn in (("steam.installed", ug.steam_installed), ("steam.playtime", ug.steam_playtime),- ("steam.appinfo_genres", ug.steam_appinfo_genres), ("steam.local_sessions", ug.steam_local_sessions),- ("steam.non_steam_shortcuts", ug.steam_non_steam_shortcuts), ("steam.screenshots", ug.steam_screenshots),- ("steam.login_users", ug.steam_login_users), ("steam.remote_clients", ug.steam_remote_clients)):- _mirror(_id, _fn, _prime_steam)---def _epic_manifests(h):- return _first(_AS(h, "Epic", "EpicGamesLauncher", "Data", "Manifests"))---@_mp("epic.present", level="L1", family=GAMING, tier="T0", collect="core")-def epic_present(h, facts):- """Epic Games Launcher for Mac (app bundle, ~/Library/Application Support/Epic) or Heroic."""- b = _app(h, "Epic Games Launcher")- d = _AS(h, "Epic")- heroic = _AS(h, "heroic")- if not (b or _isdir(d) or _isdir(heroic)):- return None- return {"present": True, "via": "epic" if (b or _isdir(d)) else "heroic", "mtime": _mtime(d if _isdir(d) else heroic)}---@_mp("epic.installs", level="L2", family=GAMING, tier="T0", collect="core", gate="epic.present")-def epic_installs(h, facts):- """Epic installs from launcher .item manifests: titles and GB."""- d = _epic_manifests(h)- rows = []- for f in glob.glob(os.path.join(d, "*.item"))[:200] if d else []:- j = _read_json(f) or {}- if isinstance(j, dict):- rows.append([j.get("DisplayName") or os.path.basename(f), round((j.get("InstallSize") or 0) / 1e9, 1)])- if not rows:- return {"present": False}- rows.sort(key=lambda r: -r[1])- return {"present": True, "count": len(rows), "total_gb": round(sum(r[1] for r in rows), 1), "manifests": rows[:20]}---@_mp("launchers.other", level="L1", family=GAMING, tier="T0", collect="core")-def launchers_other(h, facts):- """macOS game launchers and compatibility layers: Battle.net, GOG Galaxy, Heroic, CrossOver, Whisky, Game- Porting Toolkit, Parallels, Prism/Minecraft, itch, Porting Kit, Apple Games."""- U = _U(h)- apps = {"battlenet": ["Battle.net"], "gog": ["GOG Galaxy"], "heroic": ["Heroic"], "crossover": ["CrossOver"],- "whisky": ["Whisky"], "parallels": ["Parallels Desktop"], "prismlauncher": ["PrismLauncher", "Prism Launcher"],- "itch": ["itch"], "porting_kit": ["Porting Kit"], "apple_games": ["Games"], "minecraft_launcher": ["Minecraft"],- "ea": ["EA app"], "ubisoft": ["Ubisoft Connect"], "moonlight": ["Moonlight"], "geforce_now": ["GeForceNOW"]}- hits = {k for k, names in apps.items() if _app(h, *names)}- for k, p in (("minecraft", _AS(h, "minecraft")), ("prismlauncher", _AS(h, "PrismLauncher")),- ("heroic", _AS(h, "heroic")), ("gptk", "/usr/local/opt/game-porting-toolkit"), ("wine", os.path.join(U, ".wine"))):- if _ex(p):- hits.add(k)- return {"present": True, "launchers": sorted(hits)} if hits else None---@_mp("emulators", level="L1", family=GAMING, tier="T0", collect="core")-def emulators(h, facts):- """Emulators: OpenEmu, RetroArch, Dolphin, PPSSPP, Ryujinx, PCSX2, RPCS3, Cemu, DuckStation, melonDS, UTM."""- c = {"OpenEmu": ["OpenEmu"], "RetroArch": ["RetroArch"], "Dolphin": ["Dolphin"], "PPSSPP": ["PPSSPPSDL", "PPSSPP"],- "Ryujinx": ["Ryujinx"], "PCSX2": ["PCSX2"], "RPCS3": ["RPCS3"], "Cemu": ["Cemu"], "DuckStation": ["DuckStation"],- "melonDS": ["melonDS"], "UTM": ["UTM"], "Provenance": ["Provenance"]}- hits = sorted(k for k, names in c.items() if _app(h, *names))- if _isdir(_AS(h, "OpenEmu")) and "OpenEmu" not in hits:- hits.append("OpenEmu")- return {"present": True, "found": hits} if hits else None---# ================================================================== media--@_mp("media.libraries", level="L1", family=MEDIA, tier="T1", collect="core")-def media_libraries(h, facts):- """Music/Movies/Pictures file counts by type and size (bounded walk; Photos/Music library packages not- entered), Apple Photos and Music library package sizes (stat only), screenshot count."""- kf = bf._cached(h, "kf", _known_folders_mac)- out = {}- for short in ("Music", "Videos", "Pictures"):- p = kf.get(short) or os.path.join(_U(h), short)- s = ug._walk_media(p, budget_s=0.6)- s["gb"] = round(s.pop("bytes") / 1e9, 2)- s["onedrive"] = False- out[short] = s- photos = [n for n in (_ls(kf.get("Pictures") or "") or []) if n.endswith(".photoslibrary")]- out["photos_libraries"] = len(photos)- out["apple_music_library"] = _ex(os.path.join(kf.get("Music") or "", "Music", "Music Library.musiclibrary"))- out["screenshots"] = sum(1 for n in (_ls(kf.get("Screenshots") or "", 20000) or []) if bf.SHOT_NAME.match(n))- return {"present": True, **out}---@_mp("media.obs", level="L1", family=MEDIA, tier="T0", collect="core")-def media_obs(h, facts):- """OBS Studio app bundle and whether a config dir exists (launched at least once); other recorders."""- b = _app(h, "OBS")- cfg = _isdir(_AS(h, "obs-studio"))- others = [n for n in ("Screen Studio", "Loom", "CleanShot X", "Cap", "Kap", "ScreenFlow", "Descript") if _app(h, n)]- if not (b or cfg):- return None- return {"present": True, "obs_installs": ["app"] if b else [], "obs_configs": ["native"] if cfg else [],- "config_dir": cfg, "version": (b or {}).get("version"), "obs_config_in_agent_container": 0,- "streamlabs": bool(_app(h, "Streamlabs Desktop")), "streamlabs_config": False, "other_recorders": others}---@_mp("media.players", level="L1", family=MEDIA, tier="T0", collect="core")-def media_players(h, facts):- """Music/video players and streaming apps: Spotify, Apple Music/TV/Podcasts (library present), IINA, VLC, mpv,- Infuse, Plex, Jellyfin, TIDAL, ..."""- kf = bf._cached(h, "kf", _known_folders_mac)- found = {"spotify": bool(_app(h, "Spotify")) or _isdir(_AS(h, "Spotify")),- "apple_music": _ex(os.path.join(kf.get("Music") or "", "Music", "Music Library.musiclibrary")),- "apple_tv": _isdir(_AS(h, "TV")) or _ex(os.path.join(kf.get("Videos") or "", "TV")),- "podcasts": _isdir(_LIB(h, "Group Containers", "243LU875E5.groups.com.apple.podcasts")),- "iina": bool(_app(h, "IINA")), "vlc": bool(_app(h, "VLC")), "mpv": bool(_which(h, "mpv")) or bool(_app(h, "mpv")),- "infuse": bool(_app(h, "Infuse 7", "Infuse")), "plex": bool(_app(h, "Plex", "Plexamp")),- "jellyfin": bool(_app(h, "Jellyfin Media Player")), "tidal": bool(_app(h, "TIDAL")),- "youtube_music": bool(_app(h, "YouTube Music")), "audirvana": bool(_app(h, "Audirvana Studio"))}- hits = sorted(k for k, v in found.items() if v)- return {"present": True, "players": hits} if hits else None---VLC_PREFS = ("Library", "Preferences", "org.videolan.vlc.plist")---@_mp("media.vlc", level="L1", family=MEDIA, tier="T0", collect="core")-def media_vlc(h, facts):- """VLC app bundle and whether its preferences exist (launched)."""- b = _app(h, "VLC")- cfg = _ex(os.path.join(_U(h), *VLC_PREFS), _AS(h, "org.videolan.vlc"))- return {"present": True, "installed": bool(b), "version": (b or {}).get("version"), "user_config": cfg} \- if (b or cfg) else None---@_mp("media.vlc_recents", level="L2", family=MEDIA, tier="T2", collect="extended", gate="media.vlc")-def media_vlc_recents(h, facts):- """VLC recent-media count, local vs stream split and extension histogram; the list itself is not emitted."""- d = _plist(os.path.join(_U(h), *VLC_PREFS)) or {}- items = d.get("recentlyPlayedMedia") or d.get("NSRecentDocuments") or []- if isinstance(items, dict):- items = list(items.keys())- items = [str(x) for x in items if isinstance(x, (str, bytes))][:500] if isinstance(items, list) else []- if not items:- return {"present": False}- kinds = collections.Counter("local" if x.startswith(("file:", "/")) else "stream" for x in items)- exts = collections.Counter()- for x in items:- m2 = re.search(r"\.([A-Za-z0-9]{1,5})$", x.split("?")[0])- exts["." + m2.group(1).lower() if m2 else ""] += 1- return {"present": True, "count": len(items), "kinds": dict(kinds), "ext": dict(exts),- "ini_mtime": _mtime(os.path.join(_U(h), *VLC_PREFS))}+_mirror("ollama.models", ad_agents.ollama_models)diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps_browser.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps_browser.pynew file mode 100644index 00000000000..8f02c1c681e--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps_browser.py@@ -0,0 +1,556 @@+"""macOS user-level probes: browser, comms_work.++Registration only at import time. Shared helpers and registration wrappers live in darwin_apps.+"""+from __future__ import annotations++import collections+import glob+import os+import re+import time++from . import browser_files as bf+from . import browser_files_comms as bf_comms+from . import browser_files_content as bf_content+from .darwin_apps import (BROWSER, COMMS, MAC_EPOCH, _AS, _LIB, _U, _app, _bundles, _day, _ex,+ _fda_meta, _is_op, _isdir, _ls, _memo, _mirror, _mp, _newest_mtime, _plist, _read_json)++# ================================================================== browser++_CHROMIUM = [("chrome", ("Google", "Chrome")), ("chrome_beta", ("Google", "Chrome Beta")),+ ("chrome_canary", ("Google", "Chrome Canary")), ("chromium", ("Chromium",)),+ ("brave", ("BraveSoftware", "Brave-Browser")), ("brave_beta", ("BraveSoftware", "Brave-Browser-Beta")),+ ("brave_nightly", ("BraveSoftware", "Brave-Browser-Nightly")), ("edge", ("Microsoft Edge",)),+ ("edge_beta", ("Microsoft Edge Beta",)), ("edge_dev", ("Microsoft Edge Dev",)), ("vivaldi", ("Vivaldi",)),+ ("opera", ("com.operasoftware.Opera",)), ("arc", ("Arc", "User Data")), ("dia", ("Dia", "User Data")),+ ("comet", ("Comet",)), ("helium", ("net.imput.helium",)), ("thorium", ("Thorium",)),+ ("aside", ("Aside",)), ("atlas", ("com.openai.atlas", "browser-data", "host")), ("sidekick", ("Sidekick",)),+ ("yandex", ("Yandex", "YandexBrowser"))]+++def _gecko_roots(h):+ return [("firefox", _AS(h, "Firefox")), ("zen", _AS(h, "zen")), ("librewolf", _AS(h, "librewolf")),+ ("floorp", _AS(h, "Floorp")), ("waterfox", _AS(h, "Waterfox")), ("tor", _AS(h, "TorBrowser-Data"))]+++def _catalog_mac(h):+ found_c, found_g = {}, {}+ n = 0+ for bid, rel in _CHROMIUM:+ n += 1+ p = _AS(h, *rel)+ if _isdir(p) and os.path.exists(os.path.join(p, "Local State")):+ found_c[bid] = p+ for bid, root in _gecko_roots(h):+ n += 1+ ok = _isdir(root) if bid == "tor" else os.path.isfile(os.path.join(root, "profiles.ini"))+ if ok:+ found_g[bid] = root+ return {"chromium": found_c, "gecko": found_g, "checked": n}+++def _prime_browser(h):+ bf._cached(h, "catalog", _catalog_mac)+++SAFARI_HISTORY = ("Library", "Safari", "History.db")+++@_mp("browser.catalog", level="L1", family=BROWSER, tier="T0", collect="core")+def browser_catalog(h, facts):+ """Chromium (~/Library/Application Support: Chrome, Brave, Edge, Arc, Dia, Vivaldi, Opera, ...), Gecko and Safari roots."""+ c = bf._cached(h, "catalog", _catalog_mac)+ saf = _fda_meta(os.path.join(_U(h), *SAFARI_HISTORY))+ return {"present": bool(c["chromium"] or c["gecko"] or saf.get("present")), "chromium": sorted(c["chromium"]),+ "gecko": sorted(c["gecko"]), "safari_history": saf, "checked": c["checked"] + 1}+++@_mp("browser.brave.present", level="L1", family=BROWSER, tier="T0", collect="core")+def brave_present(h, facts):+ """Brave user-data dir exists."""+ p = _AS(h, "BraveSoftware", "Brave-Browser")+ if not _isdir(p):+ return {"present": False}+ return {"present": True, "local_state_mtime": bf._iso(h.meta(os.path.join(p, "Local State")).get("mtime"))}+++@_mp("browser.edge.present", level="L1", family=BROWSER, tier="T0", collect="core")+def edge_present(h, facts):+ """Microsoft Edge user-data dir with a Local State (on macOS Edge is never preinstalled)."""+ p = _AS(h, "Microsoft Edge")+ if not os.path.exists(os.path.join(p, "Local State")):+ return {"present": False, "dir_only": _isdir(p)}+ return {"present": True, "local_state_mtime": bf._iso(h.meta(os.path.join(p, "Local State")).get("mtime"))}+++def _ls_handlers(h):+ """LaunchServices handler table: {scheme or content type: bundle id} from launchservices.secure.plist."""+ def build():+ d = _plist(_LIB(h, "Preferences", "com.apple.LaunchServices", "com.apple.launchservices.secure.plist")) or {}+ out = {}+ for e in d.get("LSHandlers", []) if isinstance(d, dict) else []:+ if not isinstance(e, dict):+ continue+ key = e.get("LSHandlerURLScheme") or e.get("LSHandlerContentType")+ val = e.get("LSHandlerRoleAll") or e.get("LSHandlerRoleViewer") or e.get("LSHandlerRoleEditor")+ if key and val and key not in out:+ out[str(key).lower()] = str(val)+ return out+ return _memo(h, "ls_handlers", build)+++_BROWSER_IDS = [("brave", r"com\.brave\.browser"), ("chrome", r"com\.google\.chrome"), ("chromium", r"org\.chromium"),+ ("firefox", r"org\.mozilla\.firefox"), ("edge", r"com\.microsoft\.edgemac"), ("vivaldi", r"vivaldi"),+ ("opera", r"operasoftware"), ("arc", r"company\.thebrowser\.browser"), ("dia", r"company\.thebrowser\.dia"),+ ("safari", r"com\.apple\.safari"), ("zen", r"zen"), ("comet", r"perplexity|comet"), ("aside", r"aside"),+ ("atlas", r"com\.openai\.atlas"), ("orion", r"kagi"), ("helium", r"helium")]+++def _browser_of(bid):+ d = (bid or "").lower()+ return next((b for b, rx in _BROWSER_IDS if re.search(rx, d)), bid)+++@_mp("browser.default", level="L1", family=BROWSER, tier="T0", collect="core")+def browser_default(h, facts):+ """Default browser from the LaunchServices handler for https/http (Safari when no user handler is set)."""+ m = _ls_handlers(h)+ pid = m.get("https") or m.get("http") or m.get("public.html")+ return {"present": True, "browser": _browser_of(pid) if pid else "safari", "prog_id": pid or "com.apple.safari",+ "set_by_user": bool(pid), "handlers": {k: _browser_of(m[k]) for k in ("https", "http", "public.html") if k in m}}+++@_mp("defaults.mailto_pdf_media", level="L1", family=BROWSER, tier="T0", collect="core")+def defaults_mailto_pdf_media(h, facts):+ """User-set default handlers (bundle ids) for mailto, PDF, video, audio, images, text, source code."""+ m = _ls_handlers(h)+ keys = {"mailto": "mailto", ".pdf": "com.adobe.pdf", ".mp4": "public.mpeg-4", ".mkv": "org.matroska.mkv",+ ".mp3": "public.mp3", ".jpg": "public.jpeg", ".png": "public.png", ".txt": "public.plain-text",+ ".md": "net.daringfireball.markdown", ".py": "public.python-script", "source": "public.source-code",+ "ssh": "ssh", "vscode": "vscode"}+ got = {k: m[v] for k, v in keys.items() if v in m}+ return {"present": bool(got), "handlers": got, "user_handlers_total": len(m)}+++@_mp("browser.registered", level="L2", family=BROWSER, tier="T0", collect="core", gate="apps.uninstall")+def browser_registered(h, facts):+ """Installed browser app bundles (by bundle id)."""+ names = sorted({_browser_of(b["bundle_id"]) for b in _bundles(h)+ if b["bundle_id"] and _browser_of(b["bundle_id"]) != b["bundle_id"]})+ return {"present": bool(names), "browsers": names}+++_T3_CHROMIUM = ("Cookies", "Network/Cookies", "Login Data", "Login Data For Account", "Web Data", "Account Web Data")+_T3_GECKO = ("cookies.sqlite", "logins.json", "key4.db", "formhistory.sqlite")+++@_mp("browser.t3_presence", level="L1", family=BROWSER, tier="T3", collect="core")+def browser_t3_presence(h, facts):+ """Credential/cookie stores per profile (Chromium, Gecko, Safari): stat only (size), never opened."""+ _prime_browser(h)+ rows = {}+ for bid, ud, pdir, _i in bf._profiles(h):+ base = os.path.join(ud, pdir) if pdir else ud+ sizes = {f.replace("Network/", ""): m["bytes"] for f in _T3_CHROMIUM+ for m in [h.meta(os.path.join(base, f))] if m.get("present")}+ if sizes:+ rows[bf._pkey(bid, pdir)] = sizes+ for bid, root in bf._cached(h, "catalog", _catalog_mac)["gecko"].items():+ for pd in glob.glob(os.path.join(root, "Profiles", "*"))[:30]:+ sizes = {f: m["bytes"] for f in _T3_GECKO for m in [h.meta(os.path.join(pd, f))] if m.get("present")}+ if sizes:+ rows[f"{bid}:{len(rows)}"] = sizes+ saf = {f: m["bytes"] for f, p in (("Cookies.binarycookies", _LIB(h, "Containers", "com.apple.Safari", "Data", "Library",+ "Cookies", "Cookies.binarycookies")),+ ("Cookies.binarycookies_legacy", _LIB(h, "Cookies", "Cookies.binarycookies")))+ for m in [h.meta(p)] if m.get("present")}+ if saf:+ rows["safari"] = saf+ return {"present": bool(rows), "profiles": rows}+++@_mp("browser.generic_sweep", level="L1", family=BROWSER, tier="T0", collect="extended")+def browser_generic_sweep(h, facts):+ """Chromium-style user-data dirs under ~/Library/Application Support not in the catalog (Local State + Default+ profile). Electron apps have a Local State but no Default profile and are not counted."""+ known = {os.path.realpath(p) for p in bf._cached(h, "catalog", _catalog_mac)["chromium"].values()}+ unknown = []+ for pat in (_AS(h, "*", "Local State"), _AS(h, "*", "*", "Local State"), _AS(h, "*", "*", "*", "Local State")):+ for p in glob.glob(pat)[:300]:+ d = os.path.dirname(p)+ if os.path.realpath(d) not in known and os.path.isfile(os.path.join(d, "Default", "History")) \+ and _isdir(os.path.join(d, "Default", "Extensions")) and not _is_op(h, d) \+ and not re.search(r"/Caches/|/htmlcache", d):+ unknown.append(os.path.relpath(d, _U(h)))+ return {"present": True, "unknown_forks": len(unknown), "roots": unknown[:10]}+++for _id, _fn in (("browser.local_state", bf.browser_local_state), ("browser.tab_stats", bf.browser_tab_stats),+ ("browser.profile_prefs", bf.browser_profile_prefs), ("browser.extensions", bf.browser_extensions),+ ("browser.bookmarks", bf.browser_bookmarks), ("browser.history.copy", bf.history_copy),+ ("browser.history.stats", bf.history_stats), ("browser.history.hour_weekday", bf.history_hour_weekday),+ ("browser.history.top_domains", bf.history_top_domains),+ ("browser.history.top_domains_named", bf.history_top_domains_named),+ ("browser.history.localhost", bf.history_localhost), ("browser.history.downloads", bf.history_downloads),+ ("browser.history.search_terms", bf.history_search_terms),+ ("browser.history.github_repos", bf.history_github_repos), ("browser.firefox.history", bf.firefox_history),+ ("l3.browser_category_share", bf.l3_browser_category_share), ("l3.primary_browser", bf.l3_primary_browser),+ ("l3.browser_rhythm", bf.l3_browser_rhythm), ("l3.browser_persona_hints", bf.l3_browser_persona_hints),+ ("browser.history.workspaces", bf_comms.history_workspaces), ("browser.history.work_hosts", bf_comms.history_work_hosts)):+ _mirror(_id, _fn, _prime_browser)+++@_mp("browser.safari.history", level="L2", family=BROWSER, tier="T1", collect="extended", gate="browser.catalog",+ timeout_ms=5000)+def safari_history(h, facts):+ """Safari History.db aggregates: visits, URLs, first/last visit, active days, hour histogram, domain-category+ shares (sensitive categories folded). No URLs, titles or domains are emitted. Needs Full Disk Access."""+ p = os.path.join(_U(h), *SAFARI_HISTORY)+ m = _fda_meta(p)+ if not m.get("present"):+ return {"present": False}+ if not m.get("readable"):+ return {"present": False, "needs_fda": True, "bytes": m.get("bytes")}+ rows = h.sqlite(p, "select v.visit_time, i.url from history_visits v join history_items i on i.id = v.history_item",+ timeout_ms=4000)+ if rows is None:+ return {"present": False, "error": "query_failed"}+ urls = h.sqlite(p, "select count(*) from history_items") or [[0]]+ cats, days, hours = collections.Counter(), collections.Counter(), [0] * 24+ ts = []+ for vt, url in rows:+ if vt is None:+ continue+ t = vt + MAC_EPOCH+ ts.append(t)+ lt = time.localtime(t)+ days[time.strftime("%Y-%m-%d", lt)] += 1+ hours[lt.tm_hour] += 1+ host, _ = bf._host_of(url or "")+ c = bf._categorize(bf_content._reg_domain(host)) if host else "other"+ cats["sensitive" if c in bf.SENSITIVE_CATS else c] += 1+ if not ts:+ return {"present": False}+ tot = sum(cats.values()) or 1+ return {"present": True, "visits": len(ts), "urls": urls[0][0], "first_visit": bf._iso(min(ts)),+ "last_visit": bf._iso(max(ts)), "active_days": len(days),+ "visits_per_active_day": round(len(ts) / len(days), 1), "hours": hours,+ "category_share": {k: round(v / tot, 3) for k, v in cats.most_common()}, "via": h.last_via}+++# ================================================================== comms_work++def _app_row(h, apps, data_dirs, activity=()):+ """installed/launched/last-used for one app. activity = files whose mtime means the app ran."""+ b = _app(h, *apps) if apps else None+ data = [p for p in data_dirs if _isdir(p)]+ if not (b or data):+ return None+ last = _newest_mtime([a for a in activity if a] + data)+ return {"installed": bool(b), "version": (b or {}).get("version"), "launched": bool(data), "last_used": _day(last),+ "recent_use": bool(last and time.time() - last < 30 * 86400)}+++def _comms_cands(h):+ return {+ "slack": (["Slack"], [_AS(h, "Slack")], [_AS(h, "Slack", "logs"), _AS(h, "Slack", "Local Storage")]),+ "telegram": (["Telegram", "Telegram Desktop"], [_LIB(h, "Group Containers", "6N38VWS5BX.ru.keepcoder.Telegram"),+ _AS(h, "Telegram Desktop")], []),+ "signal": (["Signal"], [_AS(h, "Signal")], [_AS(h, "Signal", "logs")]),+ "whatsapp": (["WhatsApp"], [_LIB(h, "Group Containers", "group.net.whatsapp.WhatsApp.shared")], []),+ "zoom": (["zoom.us"], [_AS(h, "zoom.us")], [_AS(h, "zoom.us", "data")]),+ "teams": (["Microsoft Teams", "Microsoft Teams (work or school)"], [_LIB(h, "Containers", "com.microsoft.teams2")], []),+ "element": (["Element"], [_AS(h, "Element")], []),+ "beeper": (["Beeper Desktop", "Beeper"], [_AS(h, "BeeperTexts")], []),+ "outlook": (["Microsoft Outlook"], [_LIB(h, "Group Containers", "UBF8T346G9.Office", "Outlook")], []),+ "apple_mail": (["Mail"], [_LIB(h, "Mail")], []),+ "messages": ([], [_LIB(h, "Messages")], []),+ "facetime": (["FaceTime"], [_AS(h, "FaceTime")], []),+ "spark": (["Spark", "Spark Desktop"], [_LIB(h, "Group Containers", "3L68KQB4HG.group.com.readdle.smartemail")], []),+ "superhuman": (["Superhuman"], [_AS(h, "Superhuman")], []),+ "webex": (["Webex"], [_AS(h, "Cisco Spark")], []),+ "around": (["Around"], [_AS(h, "Around")], []),+ "linear": (["Linear"], [_AS(h, "Linear")], []),+ "mattermost": (["Mattermost"], [_AS(h, "Mattermost")], []),+ "skype": (["Skype"], [_AS(h, "Microsoft", "Skype for Desktop")], []),+ }+++@_mp("comms.native_apps", level="L1", family=COMMS, tier="T0", collect="core")+def comms_native_apps(h, facts):+ """Native comms/mail apps: installed (bundle), launched (data dir exists), last-used day from data-dir mtimes."""+ rows = {}+ for app, (inst, data, act) in _comms_cands(h).items():+ r = _app_row(h, inst, data, act)+ if r:+ rows[app] = r+ if not rows:+ return {"present": False}+ return {"present": True, **rows}+++@_mp("comms.teams_launched", level="L2", family=COMMS, tier="T0", collect="core", gate="comms.native_apps")+def comms_teams_launched(h, facts):+ """New Teams for Mac actually started: com.microsoft.teams2 container with WebView profile dirs; tfw = work,+ tfl = personal."""+ b = _LIB(h, "Containers", "com.microsoft.teams2", "Data", "Library", "Application Support", "Microsoft", "MSTeams")+ if not _isdir(b):+ return {"present": False}+ prof = h.list_dir(os.path.join(b, "EBWebView"), 100) + h.list_dir(os.path.join(b, "WebView"), 100)+ work = sum(1 for p in prof if "tfw" in p.lower())+ return {"present": True, "work_profile": work > 0, "work_profiles": work,+ "personal_profiles": sum(1 for p in prof if "tfl" in p.lower()),+ "log_files": max(h.count_dir(os.path.join(b, "Logs"), 5000), 0)}+++@_mp("office.c2r", level="L1", family=COMMS, tier="T0", collect="core")+def office_c2r(h, facts):+ """Microsoft 365 for Mac: Word/Excel/PowerPoint/Outlook/OneNote bundles and versions (licence kind is not+ readable without opening the Office licensing store)."""+ rows = {}+ for n in ("Microsoft Word", "Microsoft Excel", "Microsoft PowerPoint", "Microsoft Outlook", "Microsoft OneNote"):+ b = _app(h, n)+ if b:+ rows[n.split()[-1].lower()] = b["version"]+ if not rows:+ return {"present": False}+ return {"present": True, "products": ",".join(sorted(rows)), "versions": rows, "platform": "mac",+ "mas": any(b["mas"] for b in _bundles(h) if b["name"].startswith("Microsoft ")), "license_kind": None}+++def _discord_dirs(h):+ return [d for d in (_AS(h, "discord"), _AS(h, "discordcanary"), _AS(h, "discordptb")) if _isdir(d)]+++@_mp("discord.present", level="L1", family=COMMS, tier="T0", collect="core")+def discord_present(h, facts):+ """Discord desktop: app bundle, profile dir, version dir."""+ b = _app(h, "Discord", "Discord Canary", "Discord PTB")+ dirs = _discord_dirs(h)+ if not (b or dirs):+ return {"present": False}+ vers = sorted(n for d in dirs for n in (_ls(d) or []) if re.fullmatch(r"\d+\.\d+\.\d+", n))+ return {"present": True, "installed": bool(b), "profile_dir": bool(dirs),+ "version": (b or {}).get("version") or (vers[-1] if vers else None)}+++@_mp("discord.usage", level="L2", family=COMMS, tier="T1", collect="extended", gate="discord.present", timeout_ms=3000)+def discord_usage(h, facts):+ """Signed-in and voice days from logs/renderer_js.log tags; last use from Local Storage mtime."""+ dirs = _discord_dirs(h)+ if not dirs:+ return {"present": False}+ days, gw, rtc = set(), set(), set()+ size = 0+ rx = re.compile(r"^\[(\d{4}-\d\d-\d\d) ([\d:.]+)\] \[\w+\]\s+\[?([A-Za-z_]+)")+ for d in dirs:+ for log in glob.glob(os.path.join(d, "logs", "renderer_js*.log"))[:5]:+ size += os.path.getsize(log)+ with open(log, encoding="utf-8", errors="replace") as fh:+ if os.path.getsize(log) > 16_000_000:+ fh.seek(os.path.getsize(log) - 16_000_000)+ for line in fh:+ m = rx.match(line)+ if not m:+ continue+ dd, _tm, tag = m.groups()+ days.add(dd)+ if tag == "GatewaySocket":+ gw.add(dd)+ elif tag.startswith("RTC"):+ rtc.add(dd)+ ls = _newest_mtime([os.path.join(d, "Local Storage", "leveldb") for d in dirs])+ used = bool(gw or rtc) or bool(ls and time.time() - ls < 90 * 86400)+ return {"present": used, "log_days": len(days), "first_day": min(days) if days else None,+ "last_day": max(days) if days else None, "gateway_days": len(gw), "rtc_days": len(rtc),+ "local_storage_last": _day(ls), "log_bytes": size}+++MESSAGES_DB = ("Library", "Messages", "chat.db")+NOTES_DB = ("Library", "Group Containers", "group.com.apple.notes", "NoteStore.sqlite")+++@_mp("comms.imessage", level="L2", family=COMMS, tier="T1", collect="extended", gate="comms.native_apps", timeout_ms=5000)+def comms_imessage(h, facts):+ """Messages chat.db record counts only: messages, chats, sent share, by service, first/last date, per-month+ counts. No text, no handles, no attachments. Needs Full Disk Access."""+ p = os.path.join(_U(h), *MESSAGES_DB)+ m = _fda_meta(p)+ if not m.get("present"):+ return {"present": False}+ if not m.get("readable"):+ return {"present": False, "needs_fda": True, "bytes": m.get("bytes")}+ r = h.sqlite(p, "select count(*), sum(is_from_me), min(date), max(date) from message", timeout_ms=4000)+ if not r:+ return {"present": False, "error": "query_failed"}+ n, mine, a, z = r[0]+ scale = 1e9 if (z or 0) > 1e12 else 1+ chats = (h.sqlite(p, "select count(*) from chat") or [[None]])[0][0]+ svc = dict(h.sqlite(p, "select coalesce(service,'?'), count(*) from message group by 1") or [])+ cut = (time.time() - MAC_EPOCH - 30 * 86400) * scale+ n30 = (h.sqlite(p, "select count(*) from message where date >= ?", (cut,)) or [[None]])[0][0]+ months = dict(h.sqlite(p, f"select strftime('%Y-%m', date / {scale} + {MAC_EPOCH}, 'unixepoch'), count(*) "+ "from message group by 1") or [])+ return {"present": True, "messages": n, "sent_share": round((mine or 0) / n, 3) if n else None, "chats": chats,+ "by_service": svc, "messages_30d": n30, "first": bf._iso(a / scale + MAC_EPOCH) if a else None,+ "last": bf._iso(z / scale + MAC_EPOCH) if z else None, "by_month": dict(sorted(months.items())[-24:]),+ "via": h.last_via}+++def _notes_cands(h):+ U = _U(h)+ return {+ "obsidian": (["Obsidian"], [_AS(h, "obsidian")], [_AS(h, "obsidian", "obsidian.json")]),+ "notion": (["Notion"], [_AS(h, "Notion")], []),+ "logseq": (["Logseq"], [os.path.join(U, ".logseq"), _AS(h, "Logseq")], []),+ "apple_notes": (["Notes"], [_LIB(h, "Group Containers", "group.com.apple.notes")], []),+ "bear": (["Bear"], [_LIB(h, "Group Containers", "9K33E3U3T4.net.shinyfrog.bear")], []),+ "craft": (["Craft"], [_LIB(h, "Containers", "com.lukilabs.lukiapp")], []),+ "joplin": (["Joplin"], [os.path.join(U, ".config", "joplin-desktop")], []),+ "evernote": (["Evernote"], [_LIB(h, "Containers", "com.evernote.Evernote")], []),+ "todoist": (["Todoist"], [_AS(h, "Todoist")], []),+ "zotero": (["Zotero"], [_AS(h, "Zotero"), os.path.join(U, "Zotero")], []),+ "granola": (["Granola"], [_AS(h, "Granola")], []),+ "anytype": (["Anytype"], [_AS(h, "anytype")], []),+ }+++@_mp("productivity.notes_apps", level="L1", family=COMMS, tier="T0", collect="core")+def notes_apps(h, facts):+ """Notes apps installed or launched: Obsidian, Notion, Logseq, Apple Notes, Bear, Craft, Zotero, ..."""+ rows = {}+ for app, (inst, data, act) in _notes_cands(h).items():+ r = _app_row(h, inst, data, act)+ if r:+ rows[app] = r+ return {"present": bool(rows), "apps": sorted(rows), "detail": rows}+++@_mp("obsidian.vaults", level="L2", family=COMMS, tier="T1", collect="extended", gate="productivity.notes_apps")+def obsidian_vaults(h, facts):+ """Obsidian vault count and note counts (vault names and paths are not emitted)."""+ j = _read_json(_AS(h, "obsidian", "obsidian.json"))+ vs = ((j or {}).get("vaults") or {}) if isinstance(j, dict) else {}+ if not vs:+ return {"present": False}+ notes, files, newest = 0, 0, 0++ def on_file(e, s, depth):+ nonlocal notes, newest+ if e.name.lower().endswith(".md"):+ notes += 1+ newest = max(newest, s.st_mtime)+ for v in list(vs.values())[:10]:+ p = v.get("path") if isinstance(v, dict) else None+ if p and _isdir(p) and p.startswith(_U(h)):+ st = bf._walk(p, max_depth=6, max_entries=30000, budget_s=1.5, on_file=on_file,+ skip_dir=lambda n, _p: n in (".obsidian", ".git", ".trash", "node_modules"))+ files += st["files"]+ return {"present": True, "vaults": len(vs), "open": sum(1 for v in vs.values() if isinstance(v, dict) and v.get("open")),+ "notes_md": notes, "files": files, "newest_note": bf._iso(newest) if newest else None}+++@_mp("productivity.apple_notes", level="L2", family=COMMS, tier="T1", collect="extended", gate="productivity.notes_apps",+ timeout_ms=4000)+def apple_notes(h, facts):+ """Apple Notes NoteStore.sqlite record counts only: notes, folders, accounts, created/modified range. No titles+ or bodies. Needs Full Disk Access."""+ p = os.path.join(_U(h), *NOTES_DB)+ m = _fda_meta(p)+ if not m.get("present"):+ return {"present": False}+ if not m.get("readable"):+ return {"present": False, "needs_fda": True, "bytes": m.get("bytes")}+ cols = {r[1] for r in (h.sqlite(p, "pragma table_info(ZICCLOUDSYNCINGOBJECT)") or [])}+ if not cols:+ return {"present": False, "error": "schema"}+ crt = "ZCREATIONDATE3" if "ZCREATIONDATE3" in cols else "ZCREATIONDATE1" if "ZCREATIONDATE1" in cols else None+ mod = "ZMODIFICATIONDATE1" if "ZMODIFICATIONDATE1" in cols else None+ note_where = "ZNOTEDATA is not null" if "ZNOTEDATA" in cols else "ZTITLE1 is not null"+ q = f"select count(*), min({crt or 'null'}), max({mod or 'null'}) from ZICCLOUDSYNCINGOBJECT where {note_where}"+ if "ZMARKEDFORDELETION" in cols:+ q += " and coalesce(ZMARKEDFORDELETION, 0) = 0"+ r = h.sqlite(p, q) or [[0, None, None]]+ folders = (h.sqlite(p, "select count(*) from ZICCLOUDSYNCINGOBJECT where ZTITLE2 is not null") or [[None]])[0][0] \+ if "ZTITLE2" in cols else None+ accts = (h.sqlite(p, "select count(*) from ZICCLOUDSYNCINGOBJECT where ZACCOUNTTYPE is not null") or [[None]])[0][0] \+ if "ZACCOUNTTYPE" in cols else None+ n, a, z = r[0]+ n30 = None+ if mod:+ n30 = (h.sqlite(p, f"select count(*) from ZICCLOUDSYNCINGOBJECT where {note_where} and {mod} >= ?",+ (time.time() - MAC_EPOCH - 30 * 86400,)) or [[None]])[0][0]+ return {"present": bool(n), "notes": n, "folders": folders, "accounts": accts, "modified_30d": n30,+ "first_created": bf._iso(a + MAC_EPOCH) if a else None, "last_modified": bf._iso(z + MAC_EPOCH) if z else None,+ "via": h.last_via}+++_EDR = {"crowdstrike": ["/Applications/Falcon.app", "/Library/CS"], "sentinelone": ["/Library/Sentinel", "/Applications/SentinelOne"],+ "defender": ["/Applications/Microsoft Defender.app"], "jamf_protect": ["/Applications/JamfProtect.app"],+ "jamf": ["/usr/local/jamf", "/Library/Application Support/JAMF"], "kandji": ["/Library/Kandji"],+ "mosyle": ["/Library/Application Support/Mosyle"], "addigy": ["/Library/Addigy"],+ "intune_agent": ["/Library/Intune", "/Applications/Company Portal.app"], "zscaler": ["/Applications/Zscaler"],+ "netskope": ["/Library/Application Support/Netskope"], "globalprotect": ["/Applications/GlobalProtect.app"],+ "cisco_secure_client": ["/opt/cisco/secureclient", "/opt/cisco/anyconnect"], "osquery": ["/private/var/osquery", "/opt/osquery"],+ "kolide": ["/usr/local/kolide-k2"], "fleetd": ["/opt/orbit"], "santa": ["/Applications/Santa.app"],+ "sophos": ["/Library/Sophos Anti-Virus"], "carbonblack": ["/Applications/VMware Carbon Black Cloud"],+ "tanium": ["/Library/Tanium"], "lulu": ["/Applications/LuLu.app"], "little_snitch": ["/Applications/Little Snitch.app"],+ "blockblock": ["/Applications/BlockBlock Helper.app"]}+++@_mp("work.security_agents", level="L1", family=COMMS, tier="T0", collect="core")+def work_security_agents(h, facts):+ """EDR/MDM/ZTNA agents and personal firewalls by install path (no launchctl queries)."""+ hits = sorted(k for k, ps in _EDR.items() if _ex(*ps))+ personal = {"lulu", "little_snitch", "blockblock"}+ return {"present": True, "agents": [a for a in hits if a not in personal],+ "personal_security_tools": [a for a in hits if a in personal], "checked": len(_EDR)}+++@_mp("work.mdm", level="L1", family=COMMS, tier="T0", collect="core")+def work_mdm(h, facts):+ """MDM enrollment: DEP activation record and enrollment markers under /var/db/ConfigurationProfiles, managed+ preference domains under /Library/Managed Preferences (counts only; no `profiles` spawn)."""+ cp = "/private/var/db/ConfigurationProfiles"+ dep = _ex(os.path.join(cp, "Settings", ".cloudConfigHasActivationRecord"), os.path.join(cp, "Settings", ".cloudConfigRecordFound"))+ enrolled = _ex(os.path.join(cp, "Settings", ".profilesAreInstalled"), os.path.join(cp, "Store", "ConfigProfiles.binary"))+ managed = [n for n in (_ls("/Library/Managed Preferences") or []) if n.endswith(".plist")]+ real = ["mdm"] if (enrolled and (dep or managed)) else []+ return {"present": True, "real_enrollments": len(real), "enrollments": real, "dep_activation_record": dep,+ "profiles_marker": enrolled, "managed_pref_domains": len(managed)}+++@_mp("work.join_state", level="L1", family=COMMS, tier="T0", collect="core")+def work_join_state(h, facts):+ """Directory binding: Active Directory plugin config, Kerberos SSO / Platform SSO extension presence."""+ ad_cfg = _ex("/Library/Preferences/OpenDirectory/Configurations/Active Directory")+ ad_bound = bool(_ls("/Library/Preferences/OpenDirectory/Configurations/Active Directory"))+ psso = _ex("/Library/Preferences/com.apple.extensiblesso.plist", "/Library/Managed Preferences/com.apple.extensiblesso.plist")+ return {"present": True, "state": "joined" if ad_bound else "workgroup", "domain_joined": ad_bound,+ "ad_plugin_config": ad_cfg, "azure_ad_joined": psso, "platform_sso": psso}+++@_mp("work.policies", level="L1", family=COMMS, tier="T0", collect="core")+def work_policies(h, facts):+ """Managed app policy plists (Chrome, Edge, Brave, Firefox, Office) under /Library/Managed Preferences: counts."""+ doms = {"chrome": "com.google.Chrome", "edge": "com.microsoft.Edge", "brave": "com.brave.Browser",+ "firefox": "org.mozilla.firefox", "office": "com.microsoft.office", "safari": "com.apple.Safari"}+ root = "/Library/Managed Preferences"+ names = _ls(root) or []+ user = _ls(os.path.join(root, os.environ.get("USER", ""))) or []+ configured = {k: {"values": sum(1 for n in names + user if n.startswith(d)), "subkeys": 0} for k, d in doms.items()+ if any(n.startswith(d) for n in names + user)}+ return {"present": True, "app_policies": configured, "app_policy_count": len(configured)}+++@_mp("onedrive.accounts", level="L1", family=COMMS, tier="T0", collect="core")+def onedrive_accounts(h, facts):+ """OneDrive for Mac: app bundle and File Provider roots under ~/Library/CloudStorage (OneDrive-Personal /+ OneDrive-TENANT). Folder names are not emitted."""+ b = _app(h, "OneDrive")+ roots = [n for n in (_ls(_LIB(h, "CloudStorage")) or []) if n.startswith("OneDrive")]+ if not (b or roots):+ return {"present": False}+ return {"present": True, "installed": bool(b), "accounts": len(roots), "signed_in": len(roots),+ "business": sum(1 for n in roots if n != "OneDrive-Personal")}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps_dev.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps_dev.pynew file mode 100644index 00000000000..f0cabda383b--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps_dev.py@@ -0,0 +1,573 @@+"""macOS user-level probes: dev.++Registration only at import time. Shared helpers and registration wrappers live in darwin_apps.+"""+from __future__ import annotations++import collections+import datetime as dt+import glob+import os+import re+import shutil+import time++from . import apps_dev as ad+from . import apps_dev_devenv as ad_devenv+from .darwin_apps import (DEV, _AS, _LIB, _U, _app, _brew_prefix, _cfg, _data, _day, _ex,+ _extra_bins, _fact, _is_op, _isdir, _ls, _mirror, _mp, _mtime, _newest_mtime, _npm_roots, _read_json,+ _spawn, _which)++# ================================================================== dev++@_mp("apps.pkg_managers", level="L1", family=DEV, tier="T0", collect="core")+def apps_pkg_managers(h, facts):+ """Package managers: Homebrew, MacPorts, nix, npm/pnpm/bun/yarn, cargo, go, uv, pipx, mas."""+ U = _U(h)+ b = {"brew": bool(_brew_prefix()), "macports": _ex("/opt/local/bin/port"),+ "nix": _ex("/nix", os.path.join(U, ".nix-profile")), "npm": bool(_which(h, "npm")), "pnpm": bool(_which(h, "pnpm")),+ "bun": bool(_which(h, "bun")), "yarn": bool(_which(h, "yarn")), "cargo": bool(_which(h, "cargo")),+ "go": bool(_which(h, "go")), "uv": bool(_which(h, "uv")), "pipx": bool(_which(h, "pipx")),+ "mas": bool(_which(h, "mas")), "fnm": bool(_which(h, "fnm")), "nvm": _isdir(os.path.join(U, ".nvm")),+ "pkgx": bool(_which(h, "pkgx")), "mise": bool(_which(h, "mise")), "asdf": _isdir(os.path.join(U, ".asdf"))}+ return {"present": True, **b, "managers": sorted(k for k, v in b.items() if v)}+++def _ls_pkgs(root, cap=500):+ names = _ls(root, cap)+ if names is None:+ return None+ pk = []+ for n in names:+ if n.startswith("@"):+ pk += [f"{n}/{s}" for s in (_ls(os.path.join(root, n), 100) or []) if not s.startswith(".")]+ elif not n.startswith("."):+ pk.append(n)+ return sorted(pk)+++@_mp("dev.npm_globals", level="L2", family=DEV, tier="T1", collect="core", gate="apps.pkg_managers")+def dev_npm_globals(h, facts):+ """Global JS packages by manager (npm roots incl. Homebrew/fnm/nvm, pnpm, bun, yarn); directory listings, no spawn."""+ U = _U(h)+ out, allp = {}, set()+ for r in _npm_roots(h):+ pk = [p for p in (_ls_pkgs(r) or []) if p not in ("npm", "corepack")]+ if pk:+ key = "npm_user" if r.startswith(U) else "npm_system"+ out.setdefault(key, []).extend(pk)+ allp.update(pk)+ for key, r in (("pnpm", os.path.join(U, "Library", "pnpm", "global", "5", "node_modules")),+ ("bun", os.path.join(U, ".bun", "install", "global", "node_modules")),+ ("yarn", _cfg(h, "yarn", "global", "node_modules"))):+ pk = _ls_pkgs(r)+ if pk:+ out[key] = pk+ allp.update(pk)+ if not out:+ return {"present": False}+ return {"present": True, "count": len(allp), "packages": sorted(allp)[:80],+ "by_manager": {k: len(set(v)) for k, v in out.items()}}+++@_mp("dev.lang_globals", level="L2", family=DEV, tier="T1", collect="core", gate="apps.pkg_managers")+def dev_lang_globals(h, facts):+ """cargo-installed crates (~/.cargo/.crates2.json) and ~/go/bin binaries; names only."""+ U = _U(h)+ out = {}+ cj = _read_json(os.path.join(U, ".cargo", ".crates2.json"))+ if isinstance(cj, dict) and isinstance(cj.get("installs"), dict):+ out["cargo"] = sorted({k.split(" ")[0] for k in cj["installs"]})[:60]+ elif _isdir(os.path.join(U, ".cargo", "bin")):+ out["cargo_bin"] = sorted(n for n in _ls(os.path.join(U, ".cargo", "bin")) or [] if not n.startswith("."))[:60]+ gb = _ls(os.path.join(os.environ.get("GOPATH") or os.path.join(U, "go"), "bin"))+ if gb:+ out["go_bin"] = sorted(gb)[:60]+ if not out:+ return {"present": False}+ return {"present": True, "count": sum(len(v) for v in out.values()), **out}+++@_mp("dev.uv_tools", level="L2", family=DEV, tier="T1", collect="core", gate="dev.toolchain_presence")+def dev_uv_tools(h, facts):+ """uv tools and uv-managed Pythons (~/.local/share/uv listing, equals `uv tool list`), ~/.local/bin entries."""+ tools = _ls(_data(h, "uv", "tools"), 200)+ py = _ls(_data(h, "uv", "python"), 200)+ lb = _ls(os.path.join(_U(h), ".local", "bin"), 300)+ if tools is None and py is None and lb is None:+ return {"present": False}+ return {"present": True, "tools": sorted(t for t in (tools or []) if not t.startswith("."))[:60],+ "pythons": sorted(p for p in (py or []) if p.startswith(("cpython", "pypy")))[:30],+ "local_bin_count": len(lb or []), "local_bin": sorted(lb or [])[:40]}+++@_mp("dev.git", level="L1", family=DEV, tier="T0", collect="core")+def dev_git(h, facts):+ """git binary (no spawn): Xcode Command Line Tools shim, Homebrew git or other."""+ exe = _which(h, "git")+ if not exe:+ return None+ rp = os.path.realpath(exe)+ kind = "homebrew" if "/homebrew/" in rp or "/Cellar/" in rp else "apple_clt" if exe == "/usr/bin/git" else \+ "user" if exe.startswith(_U(h)) else "other"+ return {"present": True, "on_path": bool(shutil.which("git")), "path_kind": kind,+ "clt_installed": _isdir("/Library/Developer/CommandLineTools"), "xdg_config": os.path.exists(_cfg(h, "git", "config"))}+++_mirror("dev.git_global_config", ad_devenv.dev_git_global_config)+++@_mp("dev.gh_auth_presence", level="L1", family=DEV, tier="T3", collect="core")+def dev_gh_auth_presence(h, facts):+ """GitHub CLI hosts.yml presence/size (means gh logged in; never opened)."""+ return h.meta(_cfg(h, "gh", "hosts.yml"))+++@_mp("dev.docker_config_presence", level="L1", family=DEV, tier="T3", collect="core")+def dev_docker_config_presence(h, facts):+ """~/.docker/config.json presence/size (may hold registry auths; never opened)."""+ return h.meta(os.path.join(_U(h), ".docker", "config.json"))+++_mirror("dev.npmrc_presence", ad_devenv.dev_npmrc_presence)++_PATH_TOOLS = [("homebrew", r"^/opt/homebrew/|^/usr/local/(s?bin)$"), ("local_bin", r"/\.local/bin$"), ("home_bin", r"^/Users/[^/]+/bin$"),+ ("bun", r"/\.bun/bin"), ("cargo", r"/\.cargo/bin"), ("go", r"/go/bin"), ("fnm", r"fnm"), ("nvm", r"\.nvm"),+ ("volta", r"\.volta"), ("pnpm", r"pnpm"), ("deno", r"\.deno"), ("nix", r"\.nix-profile|/nix/"),+ ("conda", r"conda|miniforge"), ("pyenv", r"\.pyenv"), ("rye", r"\.rye"), ("hermes", r"hermes"),+ ("lmstudio", r"\.lmstudio"), ("orbstack", r"orbstack"), ("docker", r"Docker\.app"), ("macports", r"^/opt/local/"),+ ("postgres_app", r"Postgres\.app"), ("vscode", r"Visual Studio Code\.app")]+++@_mp("dev.path_entries", level="L1", family=DEV, tier="T0", collect="core")+def dev_path_entries(h, facts):+ """PATH entry count and known-tool dir matches for this process (paths not emitted); user bin dirs off PATH."""+ ents = [e for e in os.environ.get("PATH", "").split(":") if e]+ tools = sorted({t for t, rx in _PATH_TOOLS for e in ents if re.search(rx, e)})+ U = _U(h)+ off = [os.path.relpath(d, U) for d in _extra_bins(h) if d.startswith(U) and _isdir(d) and d not in ents]+ helper = len(_ls("/etc/paths.d") or [])+ return {"present": True, "entries": len(ents), "user": sum(1 for e in ents if e.startswith(U)),+ "machine": sum(1 for e in ents if not e.startswith(U)), "tools": tools, "user_bin_dirs_off_path": off,+ "paths_d_entries": helper}+++_mirror("dev.ssh_config", ad_devenv.dev_ssh_config)++_TOOLCHAIN = ["node", "npm", "pnpm", "yarn", "bun", "deno", "fnm", "nvm", "volta", "uv", "pipx", "conda", "poetry",+ "rustc", "cargo", "rustup", "go", "dotnet", "java", "javac", "mvn", "gradle", "cmake", "ninja", "make", "clang",+ "gcc", "zig", "swift", "xcodebuild", "xcrun", "pod", "gh", "docker", "podman", "colima", "orb", "kubectl",+ "terraform", "tailscale", "claude", "codex", "hermes", "ollama", "code", "cursor", "windsurf", "zed", "nvim",+ "vim", "emacs", "python3", "python", "tmux", "zellij", "lazygit", "rg", "fd", "fzf", "zoxide", "mcfly",+ "atuin", "btop", "htop", "jq", "ssh", "mosh", "brew", "mas", "gcloud", "aws", "vercel", "wrangler", "flyctl"]+++@_mp("dev.toolchain_presence", level="L1", family=DEV, tier="T0", collect="core")+def dev_toolchain_presence(h, facts):+ """which() for language/infra/AI/editor CLIs over PATH plus Homebrew and user tool dirs; off-PATH install dirs."""+ U = _U(h)+ found, user_found = [], []+ for t in _TOOLCHAIN:+ p = _which(h, t)+ if p:+ found.append(t)+ if p.startswith(U):+ user_found.append(t)+ off = {k: _isdir(p) for k, p in [+ ("cargo_home", os.path.join(U, ".cargo")), ("rustup", os.path.join(U, ".rustup")), ("go_root", "/usr/local/go"),+ ("gopath", os.path.join(U, "go")), ("uv_pythons", _data(h, "uv", "python")), ("pyenv", os.path.join(U, ".pyenv")),+ ("miniconda", os.path.join(U, "miniconda3")), ("anaconda", os.path.join(U, "anaconda3")),+ ("miniforge", os.path.join(U, "miniforge3")), ("nvm", os.path.join(U, ".nvm")), ("sdkman", os.path.join(U, ".sdkman")),+ ("android_sdk", _LIB(h, "Android", "sdk")), ("xcode", "/Applications/Xcode.app"),+ ("xcode_derived_data", _LIB(h, "Developer", "Xcode", "DerivedData")), ("clt", "/Library/Developer/CommandLineTools"),+ ("dotnet", os.path.join(U, ".dotnet")), ("rye", os.path.join(U, ".rye"))]}+ return {"present": True, "on_path": found, "user_installed": user_found, "off_path": sorted(k for k, v in off.items() if v)}+++@_mp("dev.toolchain_versions", level="L2", family=DEV, tier="T0", collect="extended", gate="dev.toolchain_presence",+ timeout_ms=12000)+def dev_toolchain_versions(h, facts):+ """--version spawns (parallel, gated on which) for runtimes, package managers, AI CLIs and infra CLIs.+ `hermes --version` and `brew --version` are excluded (both start slow interpreters); versions come from files."""+ from concurrent.futures import ThreadPoolExecutor+ specs = [("node", ["--version"]), ("npm", ["--version"]), ("uv", ["--version"]), ("gh", ["--version"]),+ ("git", ["--version"]), ("docker", ["--version"]), ("bun", ["--version"]), ("pnpm", ["--version"]),+ ("deno", ["--version"]), ("rustc", ["--version"]), ("cargo", ["--version"]), ("go", ["version"]),+ ("python3", ["--version"]), ("claude", ["--version"]), ("codex", ["--version"]), ("ollama", ["--version"]),+ ("tmux", ["-V"]), ("nvim", ["--version"]), ("swift", ["--version"]), ("tailscale", ["version"])]+ todo = [(n, [_which(h, n)] + a) for n, a in specs if _which(h, n)]+ if "git" in dict(todo) and not _isdir("/Library/Developer/CommandLineTools") and not _isdir("/Applications/Xcode.app"):+ todo = [t for t in todo if t[0] != "git"]++ def one(item):+ name, args = item+ rc, txt, ms = _spawn(h, args, timeout=3)+ line = next((l.strip() for l in txt.splitlines() if l.strip()), None)+ return name, {"version": ad._redact(line, 90) if line else None, "rc": rc, "ms": ms}+ out = {}+ with ThreadPoolExecutor(max_workers=6) as ex:+ for name, r in ex.map(one, todo):+ out[name] = r+ return {"present": bool(out), "tools": out}+++_EDITORS = {+ # name: (app bundle names, extension dir(s), Application Support user dir)+ "vscode": (["Visual Studio Code"], [".vscode/extensions"], "Code"),+ "vscode_insiders": (["Visual Studio Code - Insiders"], [".vscode-insiders/extensions"], "Code - Insiders"),+ "cursor": (["Cursor"], [".cursor/extensions"], "Cursor"),+ "windsurf": (["Windsurf"], [".windsurf/extensions"], "Windsurf"),+ "vscodium": (["VSCodium"], [".vscode-oss/extensions"], "VSCodium"),+ "kiro": (["Kiro"], [".kiro/extensions"], "Kiro"),+ "trae": (["Trae"], [".trae/extensions"], "Trae"),+}+++@_mp("editor.vscode", level="L2", family=DEV, tier="T2", collect="core", gate="dev.toolchain_presence")+def editor_vscode(h, facts):+ """VS Code family: extension ids (AI flagged), workspaces opened, MCP/chat; other editors (JetBrains, Zed, Xcode...)."""+ U = _U(h)+ out = {}+ for name, (apps, extds, userd) in _EDITORS.items():+ b = _app(h, *apps)+ extd = next((os.path.join(U, e) for e in extds if _isdir(os.path.join(U, e))), None)+ user = _AS(h, userd, "User") if userd else None+ if not (b or extd or (user and _isdir(user))):+ continue+ ids = ad_devenv._ext_ids(extd) if extd else []+ e = {"installed": bool(b), "version": (b or {}).get("version"), "extensions": len(ids), "extension_ids": ids[:80],+ "ai_extensions": [i for i in ids if ad_devenv._AI_EXT.search(i)]}+ if user and _isdir(user):+ ws = _ls(os.path.join(user, "workspaceStorage"), 5000)+ e["workspaces_opened"] = len(ws) if ws is not None else 0+ e["settings_json"] = os.path.exists(os.path.join(user, "settings.json"))+ e["keybindings_json"] = os.path.exists(os.path.join(user, "keybindings.json"))+ e["profiles"] = len(_ls(os.path.join(user, "profiles")) or [])+ mj = _read_json(os.path.join(user, "mcp.json"), jsonc=True)+ e["mcp_servers"] = len((mj.get("servers") or mj.get("mcpServers") or {})) if isinstance(mj, dict) else 0+ e["chat_sessions"] = len(glob.glob(os.path.join(user, "workspaceStorage", "*", "chatSessions", "*"))[:5000])+ e["user_mtime"] = _mtime(user)+ out[name] = e+ other = {"jetbrains": [x for x in (_ls(_AS(h, "JetBrains")) or []) if re.match(r"^[A-Za-z]+\d{4}\.\d", x)],+ "zed": bool(_app(h, "Zed")) or _isdir(_cfg(h, "zed")), "xcode": bool(_app(h, "Xcode")),+ "neovim_config": _isdir(_cfg(h, "nvim")), "vimrc": _ex(os.path.join(U, ".vimrc"), os.path.join(U, ".vim")),+ "emacs": _ex(os.path.join(U, ".emacs.d"), os.path.join(U, ".emacs"), _cfg(h, "emacs")),+ "helix": _isdir(_cfg(h, "helix")), "sublime": _isdir(_AS(h, "Sublime Text")) or bool(_app(h, "Sublime Text")),+ "nova": bool(_app(h, "Nova")), "bbedit": bool(_app(h, "BBEdit"))}+ other = {k: v for k, v in other.items() if v}+ customised = any(e["extensions"] or e.get("settings_json") or e.get("keybindings_json") for e in out.values()) or \+ bool(other.get("neovim_config") or other.get("emacs"))+ return {"present": bool(out or other), "extensions": sum(e["extensions"] for e in out.values()),+ "customised": customised, "editors": out, "other": other}+++# ---------------- repos (deep)++_REPO_SKIP = {"node_modules", ".cache", "__pycache__", ".venv", "venv", "site-packages", ".npm", ".rustup", ".cargo",+ ".bun", ".vscode", ".cursor", ".trash", "target", "dist", "build", ".next", ".git", "go", ".gradle", ".m2",+ ".nvm", ".pyenv", "miniconda3", "anaconda3", ".docker", ".ollama", ".orbstack", "library", "applications",+ "movies", "music", "pictures", ".rye", ".lmstudio", ".colima"}+++def _repos_mac(h):+ """Bounded repo walk: home depth 5, 60k dirs, 8 s; ~/Library and media folders skipped;+ classes user_area / tool_managed (dot dirs) / operator."""+ def build():+ deadline = time.perf_counter() + 8.0+ U = _U(h)+ hits, seen, visited = [], set(), [0]+ stack = [(U, 0)]+ while stack and time.perf_counter() < deadline and visited[0] < 60000:+ d, depth = stack.pop()+ visited[0] += 1+ try:+ with os.scandir(d) as it:+ ents = list(zip(range(3000), it))+ except OSError:+ continue+ names = {e.name for _, e in ents}+ if ".git" in names and (os.path.exists(os.path.join(d, ".git", "HEAD")) or os.path.isfile(os.path.join(d, ".git"))):+ rp = os.path.realpath(d)+ if rp not in seen:+ seen.add(rp)+ hits.append(d)+ continue+ if depth >= 5:+ continue+ for _, e in ents:+ if e.name.lower() in _REPO_SKIP or e.name.startswith(".Trash"):+ continue+ try:+ if not e.is_dir(follow_symlinks=False):+ continue+ except OSError:+ continue+ stack.append((e.path, depth + 1))+ repos = []+ for d in hits[:300]:+ rel = os.path.relpath(d, U)+ cls = "operator" if _is_op(h, d) else "tool_managed" if rel.startswith(".") else "user_area"+ gd = os.path.join(d, ".git")+ remotes, branch, head_mtime, local_email = [], None, None, None+ if os.path.isdir(gd):+ try:+ with open(os.path.join(gd, "HEAD"), encoding="utf-8", errors="replace") as f:+ hd = f.read(200).strip()+ branch = hd[16:] if hd.startswith("ref: refs/heads/") else "detached"+ except OSError:+ pass+ head_mtime = _mtime(os.path.join(gd, "logs", "HEAD")) or _mtime(os.path.join(gd, "index"))+ try:+ with open(os.path.join(gd, "config"), encoding="utf-8", errors="replace") as f:+ cfg = f.read(100_000)+ remotes = re.findall(r"^\s*url\s*=\s*(\S+)", cfg, re.M)+ m = re.search(r"^\s*email\s*=\s*(\S+)", cfg, re.M)+ local_email = m.group(1).lower() if m else None+ except OSError:+ pass+ markers = [m for m in ("package.json", "pyproject.toml", "uv.lock", "Cargo.toml", "go.mod", "pom.xml",+ "build.gradle", "Dockerfile", "flake.nix", "Package.swift", "AGENTS.md", "CLAUDE.md", ".mcp.json")+ if os.path.exists(os.path.join(d, m))]+ if any(n.endswith(".xcodeproj") for n in (_ls(d, 300) or [])):+ markers.append("xcodeproj")+ repos.append({"path": d, "class": cls, "branch": branch, "head_mtime": head_mtime, "remotes": remotes,+ "local_email": local_email, "markers": markers})+ return {"repos": repos, "visited_dirs": visited[0], "timed_out": time.perf_counter() >= deadline}+ return build+++def _commits_mac(h):+ def build():+ git = _which(h, "git")+ if not git:+ return None+ env_ids = {x.strip().lower() for x in os.environ.get("UIL_GIT_IDENTITY", "").split(",") if x.strip()}+ ids = set(env_ids)+ for gc in (os.path.join(_U(h), ".gitconfig"), _cfg(h, "git", "config")):+ try:+ with open(gc, encoding="utf-8", errors="replace") as f:+ ids |= {m.lower() for m in re.findall(r"^\s*email\s*=\s*(\S+)", f.read(100_000), re.M)}+ except OSError:+ pass+ res = {"identity_sources": {"env": bool(env_ids), "global": bool(ids - env_ids), "repo_local": 0}, "by_class": {},+ "hours_local": collections.Counter(), "tz_offsets": collections.Counter(), "weekday": collections.Counter(),+ "month": collections.Counter(), "repos_with_own": {}}+ # Newest HEAD first, so when the deadline cuts the scan it drops the stalest repos, not a random set.+ deadline = time.perf_counter() + 10.0+ res["repos_scanned"], res["timed_out"] = 0, False+ for x in sorted(ad_devenv._repos(h)["repos"], key=lambda r: str(r.get("head_mtime") or ""), reverse=True):+ if x["class"] == "operator":+ continue+ if time.perf_counter() > deadline:+ res["timed_out"] = True+ break+ rid = set(ids)+ if x["local_email"]:+ rid.add(x["local_email"])+ res["identity_sources"]["repo_local"] += 1+ rc, txt, _ms = _spawn(h, [git, "-C", x["path"], "log", "--all", "--no-merges",+ "--format=%ae%x09%an%x09%at%x09%ai", "-n", "100000"], timeout=max(0.5, deadline - time.perf_counter()))+ if rc != 0:+ continue+ res["repos_scanned"] += 1+ mine = total = 0+ for line in txt.splitlines():+ parts = line.split("\t")+ if len(parts) < 4:+ continue+ total += 1+ if parts[0].lower() in rid or parts[1].lower() in rid:+ mine += 1+ try:+ t = dt.datetime.fromtimestamp(int(parts[2]))+ res["hours_local"][t.hour] += 1+ res["weekday"][t.strftime("%a")] += 1+ res["month"][t.strftime("%Y-%m")] += 1+ except (ValueError, OSError):+ pass+ res["tz_offsets"][parts[3].strip()[-5:]] += 1+ c = res["by_class"].setdefault(x["class"], [0, 0])+ c[0] += mine+ c[1] += total+ if mine:+ res["repos_with_own"][x["class"]] = res["repos_with_own"].get(x["class"], 0) + 1+ return res+ return build+++def _prime_repos(h):+ ad._memo(h, "repos", _repos_mac(h))+++def _prime_commits(h):+ _prime_repos(h)+ ad._memo(h, "commits", _commits_mac(h))+++# dev.repos and dev.repos.remotes need only the walk; priming commits there made them wait for git log on every repo.+_mirror("dev.repos", ad_devenv.dev_repos, _prime_repos)+_mirror("dev.repos.remotes", ad_devenv.dev_repos_remotes, _prime_repos)+_mirror("dev.repos.my_commits", ad_devenv.dev_repos_my_commits, _prime_commits)+_mirror("dev.repos.commit_hours", ad_devenv.dev_repos_commit_hours, _prime_commits)++_BUILTINS = {"cd", "export", "source", ".", "alias", "unalias", "echo", "exit", "history", "set", "unset", "eval", "exec",+ "type", "which", "for", "if", "while", "sudo", "time", "nohup", "env", "clear", "pwd", "ls", "ll", "la", "fg",+ "bg", "jobs", "kill", "z", "zi", "man", "help", "open", "defaults", "killall"}+++def _cmd_name(line, known):+ t = line.strip().split()+ while t and (t[0] in ("sudo", "time", "nohup", "env", "exec") or "=" in t[0]):+ t = t[1:]+ if not t:+ return None+ c = os.path.basename(t[0])+ if not re.fullmatch(r"[A-Za-z0-9._+\-]{1,32}", c):+ return None+ return c if c in _BUILTINS or c in known else None+++@_mp("dev.shell_history", level="L2", family=DEV, tier="T1", collect="extended", gate="dev.path_entries")+def dev_shell_history(h, facts):+ """zsh/bash/fish/python/node history: line counts, last write, top command names (resolved executables or+ builtins only), Apple Terminal ~/.zsh_sessions count. Command lines, arguments and paths are never emitted."""+ U = _U(h)+ files = [("zsh", os.environ.get("HISTFILE") or os.path.join(U, ".zsh_history")), ("bash", os.path.join(U, ".bash_history")),+ ("fish", _data(h, "fish", "fish_history")), ("python", os.path.join(U, ".python_history")),+ ("node", os.path.join(U, ".node_repl_history")), ("mcfly_db", _AS(h, "McFly", "history.db")),+ ("atuin_db", _data(h, "atuin", "history.db"))]+ known = set()+ for d in os.environ.get("PATH", "").split(":") + _extra_bins(h):+ known.update(_ls(d, 20000) or [])+ out, cmds, total = {}, collections.Counter(), 0+ seen = set()+ for label, p in files:+ try:+ rp = os.path.realpath(p)+ if rp in seen:+ continue+ st = os.stat(p)+ except OSError:+ continue+ seen.add(rp)+ if label.endswith("_db"):+ out[label] = {"bytes": st.st_size, "mtime": _day(st.st_mtime)}+ continue+ if st.st_size > 50_000_000:+ out[label] = {"bytes": st.st_size, "lines": None, "mtime": _day(st.st_mtime)}+ continue+ n = 0+ with open(p, "rb") as f:+ for raw in f:+ line = raw.decode("utf-8", "replace").strip()+ if not line:+ continue+ if label == "fish":+ if not line.startswith("- cmd: "):+ continue+ line = line[7:]+ elif label == "zsh":+ line = re.sub(r"^: \d+:\d+;", "", line)+ n += 1+ if label in ("bash", "zsh", "fish"):+ c = _cmd_name(line, known)+ if c:+ cmds[c] += 1+ out[label] = {"lines": n, "bytes": st.st_size, "mtime": _day(st.st_mtime)}+ if label in ("bash", "zsh", "fish"):+ total += n+ zs = _ls(os.path.join(U, ".zsh_sessions"), 20000)+ if zs:+ out["zsh_sessions"] = {"files": sum(1 for x in zs if x.endswith(".history")), "mtime": _day(_newest_mtime([os.path.join(U, ".zsh_sessions")]))}+ if not out:+ return {"present": False}+ return {"present": True, "lines": total, "files": out, "top_commands": dict(cmds.most_common(15)),+ "distinct_commands": len(cmds), "login_shell": os.path.basename(os.environ.get("SHELL", ""))}+++def _docker_sock(h):+ for p in (os.path.join(_U(h), ".docker", "run", "docker.sock"), "/var/run/docker.sock",+ os.path.join(_U(h), ".orbstack", "run", "docker.sock"), os.path.join(_U(h), ".colima", "default", "docker.sock")):+ try:+ import stat as _st+ if _st.S_ISSOCK(os.stat(p).st_mode):+ return p+ except OSError:+ continue+ return None+++@_mp("dev.docker", level="L1", family=DEV, tier="T0", collect="core")+def dev_docker(h, facts):+ """Docker on macOS: CLI, Docker Desktop / OrbStack / Colima installs, live engine socket (daemon running)."""+ cli = _which(h, "docker")+ desktop = bool(_app(h, "Docker")) or _isdir(_LIB(h, "Group Containers", "group.com.docker"))+ orb = bool(_app(h, "OrbStack")) or _isdir(os.path.join(_U(h), ".orbstack"))+ colima = _isdir(os.path.join(_U(h), ".colima"))+ if not (cli or desktop or orb or colima):+ return None+ sock = _docker_sock(h)+ return {"present": True, "cli": bool(cli), "docker_desktop": desktop, "orbstack": orb, "colima": colima,+ "engine_socket": bool(sock), "socket_access": bool(sock and os.access(sock, os.R_OK | os.W_OK)),+ "podman": bool(_which(h, "podman"))}+++def _gb(s):+ m = re.match(r"([\d.]+)\s*([kKMGT]?B)", s or "")+ if not m:+ return 0.0+ return float(m.group(1)) * {"B": 1e-9, "kB": 1e-6, "KB": 1e-6, "MB": 1e-3, "GB": 1.0, "TB": 1e3}.get(m.group(2), 0)+++@_mp("dev.docker_runtime", level="L2", family=DEV, tier="T2", collect="extended", gate="dev.docker", timeout_ms=8000)+def dev_docker_runtime(h, facts):+ """`docker ps` names/images and `docker images` repos/sizes only, only when an engine socket is live."""+ d = _fact(facts, "dev.docker") or {}+ cli = _which(h, "docker")+ if not cli or not d.get("socket_access"):+ return {"present": True, "accessible": False, "count": 0}+ rc, ps, ms1 = _spawn(h, [cli, "ps", "--format", "{{.Names}}\t{{.Image}}\t{{.RunningFor}}"], timeout=5)+ rc2, im, ms2 = _spawn(h, [cli, "images", "--format", "{{.Repository}}:{{.Tag}}\t{{.Size}}"], timeout=5)+ if rc != 0 and rc2 != 0:+ return {"present": True, "accessible": False, "count": 0}+ running = [dict(zip(("name", "image", "up"), l.split("\t"))) for l in ps.splitlines() if l.strip()]+ images = [l.split("\t") for l in im.splitlines() if l.strip()]+ return {"present": True, "accessible": True, "count": len(running),+ "running": [{"name": r.get("name"), "image": (r.get("image") or "").split("@")[0][:80], "up": r.get("up")}+ for r in running[:40]],+ "images": len(images), "images_gb": round(sum(_gb(x[1]) for x in images if len(x) > 1), 2),+ "image_repos": sorted({x[0].rsplit(":", 1)[0] for x in images})[:40], "ms": round(ms1 + ms2, 1)}+++@_mp("dev.multiplexers", level="L2", family=DEV, tier="T1", collect="core", gate="dev.toolchain_presence")+def dev_multiplexers(h, facts):+ """tmux / zellij / screen session counts for this user (session names not emitted); terminal apps installed."""+ uid = os.getuid()+ out = {}+ tdir = os.path.join(os.environ.get("TMUX_TMPDIR", "/private/tmp"), f"tmux-{uid}")+ socks = [os.path.join(tdir, n) for n in (_ls(tdir) or [])]+ tm = _which(h, "tmux")+ if socks or tm:+ n = 0+ for s in socks[:10]:+ rc, txt, _ = _spawn(h, [tm, "-S", s, "ls"], timeout=2) if tm else (None, "", 0)+ if rc == 0:+ n += len([l for l in txt.splitlines() if l.strip()])+ out["tmux"] = {"installed": bool(tm), "sockets": len(socks), "sessions": n,+ "config": _ex(os.path.join(_U(h), ".tmux.conf"), _cfg(h, "tmux", "tmux.conf"))}+ zj = _which(h, "zellij")+ # no-tmp: ok — zellij puts its sockets under TMPDIR, which falls back to /tmp+ tmp = os.environ.get("TMPDIR") or "/tmp"+ zsocks = [p for p in glob.glob(os.path.join(tmp, "zellij-*", "*", "*")) if not os.path.isdir(p)]+ zres = glob.glob(_LIB(h, "Caches", "org.Zellij-Contributors.Zellij", "*", "session_info", "*"))+ if zj or zsocks or zres:+ out["zellij"] = {"installed": bool(zj), "live_sessions": len(zsocks), "resurrectable": len(zres),+ "config": _isdir(_cfg(h, "zellij"))}+ terms = [n for n in ("iTerm", "Ghostty", "WezTerm", "Alacritty", "kitty", "Warp", "cmux", "Hyper", "Tabby")+ if _app(h, n)]+ if terms:+ out["terminal_apps"] = terms+ if not out:+ return {"present": False}+ return {"present": True, "count": sum(v.get("sessions", 0) + v.get("live_sessions", 0) for v in out.values()+ if isinstance(v, dict)), **out}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps_files.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps_files.pynew file mode 100644index 00000000000..1c7897e7071--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps_files.py@@ -0,0 +1,515 @@+"""macOS user-level probes: files, gaming, media.++Registration only at import time. Shared helpers and registration wrappers live in darwin_apps.+"""+from __future__ import annotations++import collections+import ctypes+import ctypes.util+import glob+import os+import plistlib+import re+import time++from . import browser_files as bf+from . import usage_gaming as ug+from . import browser_files_content as bf_content+from . import usage_gaming_games as ug_games+from .darwin_apps import (FILES, GAMING, MAC_EPOCH, MEDIA, _AS, _LIB, _OP_DEEP, _OP_TOP, _U,+ _app, _day, _dir_readable, _ex, _first, _isdir, _ls, _mirror, _mp, _mtime, _newest_mtime, _plist,+ _read_json, _which)++# ================================================================== files++def _known_folders_mac(h):+ U = _U(h)+ out = {n: os.path.join(U, n) for n in ("Desktop", "Documents", "Downloads", "Pictures", "Music")}+ out["Videos"] = os.path.join(U, "Movies")+ sc = _plist(_LIB(h, "Preferences", "com.apple.screencapture.plist")) or {}+ loc = sc.get("location") if isinstance(sc, dict) else None+ out["Screenshots"] = os.path.expanduser(loc) if isinstance(loc, str) and loc else out["Desktop"]+ return out+++def _prime_kf(h):+ bf._cached(h, "kf", _known_folders_mac)+++_STANDARD = {"desktop", "documents", "downloads", "pictures", "movies", "music", "public", "applications", "library"}+++def _home_root(h):+ U = _U(h)+ cls, loose = collections.Counter(), 0+ try:+ ents = list(zip(range(5000), os.scandir(U)))+ except OSError:+ return None+ for _, e in ents:+ try:+ is_dir = e.is_dir(follow_symlinks=False)+ except OSError:+ continue+ if not is_dir:+ loose += 0 if e.name.startswith(".") else 1+ continue+ low = e.name.lower()+ cls["operator" if _OP_TOP.match(e.name) else "dot" if low.startswith(".") else+ "standard" if low in _STANDARD else "custom"] += 1+ return {"dirs_by_class": dict(cls), "loose_visible_files": loose}+++@_mp("files.known_folders", level="L1", family=FILES, tier="T0", collect="core")+def files_known_folders(h, facts):+ """Home folders (Desktop, Documents, Downloads, Pictures, Movies, Music) and the screenshot location;+ whether Desktop & Documents sync to iCloud Drive."""+ kf = bf._cached(h, "kf", _known_folders_mac)+ U = _U(h)+ icloud_dd = _isdir(_LIB(h, "Mobile Documents", "com~apple~CloudDocs", "Desktop"))+ rows = {n: {"path": ("~" + p[len(U):]) if p and p.startswith(U) else p, "exists": bool(p and _isdir(p)),+ "under_profile": bool(p and p.startswith(U)), "under_onedrive": False} for n, p in kf.items()}+ return {"present": any(r["exists"] for r in rows.values()), "folders": rows, "icloud_desktop_documents": icloud_dd,+ "screenshot_location_custom": kf["Screenshots"] != kf["Desktop"]}+++@_mp("files.composition", level="L2", family=FILES, tier="T1", collect="extended", gate="files.known_folders",+ timeout_ms=9000)+def files_composition(h, facts):+ """Per home folder: files, bytes, extension/kind/age histograms (depth <= 6, 100k entries), plus home-root dir+ classes (dot/standard/custom/operator). No file names."""+ _prime_kf(h)+ v = bf_content.files_composition(h, facts)+ if isinstance(v, dict):+ v["home_root"] = _home_root(h)+ return v+++_mirror("files.screenshots", bf_content.files_screenshots, _prime_kf)+++@_mp("files.recent_lnk", level="L2", family=FILES, tier="T1", collect="core", gate="files.known_folders")+def files_recent_lnk(h, facts):+ """Recent-document lists (com.apple.sharedfilelist *.sfl3): number of apps with a recent list, list file dates.+ The lists themselves are not parsed. The directory is TCC-protected (Full Disk Access)."""+ d = _AS(h, "com.apple.sharedfilelist", "com.apple.LSSharedFileList.ApplicationRecentDocuments")+ if not _isdir(_AS(h, "com.apple.sharedfilelist")):+ return {"present": False}+ names = _ls(d, 2000)+ if names is None:+ return {"present": False, "needs_fda": True}+ mts = [m for m in (_newest_mtime([os.path.join(d, n)]) for n in names if n.endswith((".sfl2", ".sfl3"))) if m]+ now = time.time()+ return {"present": bool(mts), "count": len(mts), "apps_with_recents": len(mts),+ "oldest": bf._iso(min(mts)) if mts else None, "newest": bf._iso(max(mts)) if mts else None,+ "active_days_30d": len({time.strftime("%Y-%m-%d", time.localtime(t)) for t in mts if now - t < 30 * 86400})}+++@_mp("files.clutter", level="L2", family=FILES, tier="T1", collect="extended", gate="files.known_folders", timeout_ms=6000)+def files_clutter(h, facts):+ """Trash (needs FDA), ~/Library/Caches size, this user's files in TMPDIR, Desktop item count (bounded walks)."""+ _prime_kf(h)+ out = {"present": True}+ tr = os.path.join(_U(h), ".Trash")+ if _dir_readable(tr):+ st = bf._walk(tr, max_depth=6, max_entries=100000, budget_s=1.5)+ out["recycle_bin"] = {"items": len(_ls(tr, 100000) or []), "files": st["files"], "bytes": st["bytes"],+ "truncated": st["truncated"]}+ else:+ out["recycle_bin"] = {"needs_fda": _isdir(tr)}+ st = bf._walk(_LIB(h, "Caches"), max_depth=6, max_entries=150000, budget_s=1.5)+ out["cache_bytes"], out["cache_files"], out["cache_truncated"] = st["bytes"], st["files"], st["truncated"]+ me, n, b = os.getuid(), [0], [0]++ def mine(e, s, depth):+ if s.st_uid == me:+ n[0] += 1+ b[0] += s.st_size+ # no-tmp: ok — measures the user's own temp dir, which falls back to /tmp+ tmp = os.environ.get("TMPDIR") or "/tmp"+ st = bf._walk(tmp, max_depth=3, max_entries=50000, budget_s=1.0, on_file=mine,+ skip_dir=lambda nm, p: nm == "userscan" or bool(_OP_DEEP.search(p)))+ out["temp_files"], out["temp_bytes"], out["temp_truncated"] = n[0], b[0], st["truncated"]+ desk = bf_content._kf(h, "Desktop")+ names = [x for x in h.list_dir(desk, 5000) if not x.startswith(".")]+ out["desktop_items"] = len(names)+ out["desktop_screenshots"] = sum(1 for x in names if bf_content.SHOT_NAME.match(x))+ return out+++def _where_froms(path):+ """kMDItemWhereFroms xattr (binary plist of source URLs) via getxattr(2); None when absent."""+ try:+ lib = _where_froms.lib+ except AttributeError:+ lib = _where_froms.lib = ctypes.CDLL(ctypes.util.find_library("c"), use_errno=True)+ lib.getxattr.restype = ctypes.c_ssize_t+ lib.getxattr.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_int]+ name = b"com.apple.metadata:kMDItemWhereFroms"+ p = os.fsencode(path)+ n = lib.getxattr(p, name, None, 0, 0, 1) # XATTR_NOFOLLOW+ if n <= 0 or n > 65536:+ return None+ buf = ctypes.create_string_buffer(n)+ n = lib.getxattr(p, name, buf, n, 0, 1)+ if n <= 0:+ return None+ try:+ v = plistlib.loads(buf.raw[:n])+ except Exception:+ return None+ return [x for x in v if isinstance(x, str)] if isinstance(v, list) else None+++QUARANTINE = ("Library", "Preferences", "com.apple.LaunchServices.QuarantineEventsV2")+++@_mp("files.download_sources", level="L2", family=FILES, tier="T1", collect="extended", gate="files.known_folders",+ timeout_ms=6000)+def files_download_sources(h, facts):+ """Where downloads come from, as counts: LaunchServices QuarantineEventsV2 (events by downloading app, by month,+ source-site categories when a URL was recorded) and kMDItemWhereFroms xattrs on files in Downloads (depth <= 2):+ source-site category counts and distinct host count. No hosts, URLs or file names are emitted."""+ _prime_kf(h)+ out = {"present": False}+ q = os.path.join(_U(h), *QUARANTINE)+ if os.path.exists(q):+ rows = h.sqlite(q, "select LSQuarantineTimeStamp, LSQuarantineAgentName, LSQuarantineOriginURLString, "+ "LSQuarantineDataURLString from LSQuarantineEvent")+ if rows is not None:+ agents, months, cats, hosts = collections.Counter(), collections.Counter(), collections.Counter(), set()+ ts = []+ for t, agent, origin, data in rows:+ if t:+ ts.append(t + MAC_EPOCH)+ months[_day(t + MAC_EPOCH)[:7]] += 1+ agents[(agent or "?")[:40]] += 1+ url = origin or data+ if url:+ host, _ = bf._host_of(url)+ if host:+ hosts.add(host)+ c = bf._categorize(bf_content._reg_domain(host))+ cats["sensitive" if c in bf.SENSITIVE_CATS else c] += 1+ out.update({"present": bool(rows), "quarantine": {+ "events": len(rows), "first": bf._iso(min(ts)) if ts else None, "last": bf._iso(max(ts)) if ts else None,+ "by_agent": dict(agents.most_common(10)), "by_month": dict(sorted(months.items())[-24:]),+ "with_url": sum(cats.values()), "distinct_hosts": len(hosts), "source_categories": dict(cats.most_common())}})+ root = bf_content._kf(h, "Downloads")+ if _isdir(root):+ cats, ext_cat, hosts = collections.Counter(), collections.Counter(), set()+ n = with_x = 0+ deadline = time.perf_counter() + 3.0+ stack, trunc = [(root, 0)], None+ while stack:+ d, depth = stack.pop()+ try:+ entries = list(os.scandir(d))+ except OSError:+ continue+ for e in entries:+ try:+ if e.is_dir(follow_symlinks=False):+ if depth + 1 < 2 and not _OP_DEEP.search(e.path) and not e.name.endswith((".app", ".photoslibrary")):+ stack.append((e.path, depth + 1))+ continue+ except OSError:+ continue+ n += 1+ if n > 5000 or time.perf_counter() > deadline:+ trunc = "cap"+ stack.clear()+ break+ urls = _where_froms(e.path)+ if not urls:+ continue+ with_x += 1+ host, _ = bf._host_of(urls[0])+ if host:+ hosts.add(host)+ c = bf._categorize(bf_content._reg_domain(host)) if host else "other"+ c = "sensitive" if c in bf.SENSITIVE_CATS else c+ cats[c] += 1+ ext_cat[f"{c}:{os.path.splitext(e.name)[1].lower() or '(none)'}"] += 1+ out["downloads_folder"] = {"files_scanned": n, "depth": 2, "truncated": trunc, "with_origin_xattr": with_x,+ "distinct_hosts": len(hosts), "source_categories": dict(cats.most_common()),+ "category_ext_top": dict(ext_cat.most_common(10))}+ out["present"] = out["present"] or n > 0+ return out+++@_mp("files.profile_size_walk", level="L2", family=FILES, tier="T2", collect="deep", gate="files.known_folders",+ timeout_ms=30000)+def files_profile_size_walk(h, facts):+ """Size of each top-level home dir (depth <= 10, 300k entries/dir, 25 s total); operator dirs excluded."""+ U = _U(h)+ deadline = time.perf_counter() + 25.0+ rows, loose = [], 0+ try:+ entries = list(os.scandir(U))+ except OSError:+ return {"present": False}+ for e in entries:+ try:+ if not e.is_dir(follow_symlinks=False):+ loose += 1+ continue+ except OSError:+ continue+ low = e.name.lower()+ cls = ("operator" if _OP_TOP.match(e.name) else "dot" if low.startswith(".") else+ "standard" if low in _STANDARD else "custom")+ if cls == "operator":+ rows.append({"name": e.name, "class": cls, "bytes": 0, "skipped": "operator"})+ continue+ remain = deadline - time.perf_counter()+ if remain <= 0:+ rows.append({"name": e.name, "class": cls, "bytes": 0, "skipped": "budget"})+ continue+ st = bf._walk(e.path, max_depth=10, max_entries=300000, budget_s=min(4.0, remain))+ rows.append({"name": e.name, "class": cls, "bytes": st["bytes"], "files": st["files"], "truncated": st["truncated"]})+ rows.sort(key=lambda r: -r["bytes"])+ shown = 0+ for r in rows:+ if r["class"] == "custom":+ shown += 1+ if shown > 5:+ r["name"] = f"custom#{shown}"+ cls = collections.Counter(r["class"] for r in rows)+ return {"present": True, "top_dirs": [r for r in rows if r["class"] != "operator"][:12], "class_counts": dict(cls),+ "custom_root_dirs": cls.get("custom", 0), "operator_dirs_excluded": cls.get("operator", 0),+ "custom_bytes": sum(r["bytes"] for r in rows if r["class"] == "custom"),+ "total_bytes": sum(r["bytes"] for r in rows), "loose_root_files": loose,+ "truncated_dirs": sum(1 for r in rows if r.get("truncated") or r.get("skipped") == "budget")}+++@_mp("sync.other", level="L1", family=FILES, tier="T0", collect="core")+def sync_other(h, facts):+ """Sync clients: iCloud Drive, Dropbox, Google Drive, Box, pCloud, Syncthing, MEGA, Proton Drive, Nextcloud+ (File Provider roots under ~/Library/CloudStorage plus app data dirs). OneDrive is onedrive.accounts."""+ cs = _ls(_LIB(h, "CloudStorage")) or []++ def root(prefix):+ return any(n.startswith(prefix) for n in cs)+ cands = {"icloud_drive": _isdir(_LIB(h, "Mobile Documents", "com~apple~CloudDocs")),+ "dropbox": root("Dropbox") or _isdir(os.path.join(_U(h), ".dropbox")),+ "google_drive": root("GoogleDrive") or _isdir(_AS(h, "Google", "DriveFS")),+ "box": root("Box") or _isdir(_AS(h, "Box")), "pcloud": root("pCloud"),+ "syncthing": _isdir(_AS(h, "Syncthing")) or _isdir(_LIB(h, "Application Support", "Syncthing")),+ "mega": _isdir(_AS(h, "Mega Limited")), "proton_drive": root("ProtonDrive"),+ "nextcloud": _isdir(_AS(h, "Nextcloud")) or root("Nextcloud")}+ found = sorted(k for k, v in cands.items() if v)+ return {"present": bool(found), "clients": found, "cloudstorage_roots": len(cs)}+++# ================================================================== gaming++def _steam_root(h):+ p = _AS(h, "Steam")+ if _isdir(os.path.join(p, "steamapps")) or _isdir(os.path.join(p, "userdata")):+ return p+ return None+++def _steam_mac(h):+ def load():+ sp = _steam_root(h)+ if not sp:+ return None+ libs = []+ txt = ug._read(os.path.join(sp, "steamapps", "libraryfolders.vdf"))+ if txt:+ for _k, v in (ug_games._ci(ug_games._vdf(txt), "libraryfolders") or {}).items():+ if isinstance(v, dict) and v.get("path"):+ libs.append(os.path.normpath(v["path"]))+ libs = libs or [sp]+ installed = []+ for lib in libs[:20]:+ sa = os.path.join(lib, "steamapps")+ for n in h.list_dir(sa, 2000):+ if n.startswith("appmanifest_") and n.endswith(".acf"):+ st = ug_games._ci(ug_games._vdf(ug._read(os.path.join(sa, n)) or ""), "AppState") or {}+ installed.append({"appid": int(st.get("appid", 0) or 0), "name": st.get("name"),+ "size_gb": round(int(st.get("SizeOnDisk", 0) or 0) / 1e9, 1),+ "drive": "home" if lib.startswith(_U(h)) else "other",+ "last_played": int(st.get("LastPlayed", 0) or 0)})+ ud = os.path.join(sp, "userdata")+ uids = [u for u in h.list_dir(ud, 50) if u.isdigit()]+ users = {}+ for uid in uids:+ apps = {}+ t = ug._read(os.path.join(ud, uid, "config", "localconfig.vdf"))+ if t:+ node = ug_games._ci(ug_games._vdf(t), "UserLocalConfigStore", "Software", "Valve", "Steam", "apps") or {}+ for aid, v in node.items():+ if isinstance(v, dict) and aid.isdigit() and ("Playtime" in v or "LastPlayed" in v):+ apps[int(aid)] = {"min": int(v.get("Playtime", 0) or 0), "min2wk": int(v.get("Playtime2wks", 0) or 0),+ "last": int(v.get("LastPlayed", 0) or 0)}+ users[uid] = apps+ return {"path": sp, "libs": libs, "installed": installed, "uids": uids, "users": users,+ "appinfo_path": os.path.join(sp, "appcache", "appinfo.vdf")}+ return load+++def _prime_steam(h):+ ug._cached(("steam", h.l0.get("run_id")), _steam_mac(h))+++@_mp("steam.present", level="L1", family=GAMING, tier="T0", collect="core")+def steam_present(h, facts):+ """Steam client data dir (~/Library/Application Support/Steam) and app bundle; gates the Steam subtree."""+ sp = _steam_root(h)+ if not sp:+ return None+ b = _app(h, "Steam")+ return {"present": True, "via": "native", "app": bool(b), "userdata_accounts": len([u for u in (_ls(os.path.join(sp, "userdata")) or [])+ if u.isdigit()])}+++for _id, _fn in (("steam.installed", ug_games.steam_installed), ("steam.playtime", ug_games.steam_playtime),+ ("steam.appinfo_genres", ug_games.steam_appinfo_genres), ("steam.local_sessions", ug_games.steam_local_sessions),+ ("steam.non_steam_shortcuts", ug_games.steam_non_steam_shortcuts), ("steam.screenshots", ug_games.steam_screenshots),+ ("steam.login_users", ug_games.steam_login_users), ("steam.remote_clients", ug_games.steam_remote_clients)):+ _mirror(_id, _fn, _prime_steam)+++def _epic_manifests(h):+ return _first(_AS(h, "Epic", "EpicGamesLauncher", "Data", "Manifests"))+++@_mp("epic.present", level="L1", family=GAMING, tier="T0", collect="core")+def epic_present(h, facts):+ """Epic Games Launcher for Mac (app bundle, ~/Library/Application Support/Epic) or Heroic."""+ b = _app(h, "Epic Games Launcher")+ d = _AS(h, "Epic")+ heroic = _AS(h, "heroic")+ if not (b or _isdir(d) or _isdir(heroic)):+ return None+ return {"present": True, "via": "epic" if (b or _isdir(d)) else "heroic", "mtime": _mtime(d if _isdir(d) else heroic)}+++@_mp("epic.installs", level="L2", family=GAMING, tier="T0", collect="core", gate="epic.present")+def epic_installs(h, facts):+ """Epic installs from launcher .item manifests: titles and GB."""+ d = _epic_manifests(h)+ rows = []+ for f in glob.glob(os.path.join(d, "*.item"))[:200] if d else []:+ j = _read_json(f) or {}+ if isinstance(j, dict):+ rows.append([j.get("DisplayName") or os.path.basename(f), round((j.get("InstallSize") or 0) / 1e9, 1)])+ if not rows:+ return {"present": False}+ rows.sort(key=lambda r: -r[1])+ return {"present": True, "count": len(rows), "total_gb": round(sum(r[1] for r in rows), 1), "manifests": rows[:20]}+++@_mp("launchers.other", level="L1", family=GAMING, tier="T0", collect="core")+def launchers_other(h, facts):+ """macOS game launchers and compatibility layers: Battle.net, GOG Galaxy, Heroic, CrossOver, Whisky, Game+ Porting Toolkit, Parallels, Prism/Minecraft, itch, Porting Kit, Apple Games."""+ U = _U(h)+ apps = {"battlenet": ["Battle.net"], "gog": ["GOG Galaxy"], "heroic": ["Heroic"], "crossover": ["CrossOver"],+ "whisky": ["Whisky"], "parallels": ["Parallels Desktop"], "prismlauncher": ["PrismLauncher", "Prism Launcher"],+ "itch": ["itch"], "porting_kit": ["Porting Kit"], "apple_games": ["Games"], "minecraft_launcher": ["Minecraft"],+ "ea": ["EA app"], "ubisoft": ["Ubisoft Connect"], "moonlight": ["Moonlight"], "geforce_now": ["GeForceNOW"]}+ hits = {k for k, names in apps.items() if _app(h, *names)}+ for k, p in (("minecraft", _AS(h, "minecraft")), ("prismlauncher", _AS(h, "PrismLauncher")),+ ("heroic", _AS(h, "heroic")), ("gptk", "/usr/local/opt/game-porting-toolkit"), ("wine", os.path.join(U, ".wine"))):+ if _ex(p):+ hits.add(k)+ return {"present": True, "launchers": sorted(hits)} if hits else None+++@_mp("emulators", level="L1", family=GAMING, tier="T0", collect="core")+def emulators(h, facts):+ """Emulators: OpenEmu, RetroArch, Dolphin, PPSSPP, Ryujinx, PCSX2, RPCS3, Cemu, DuckStation, melonDS, UTM."""+ c = {"OpenEmu": ["OpenEmu"], "RetroArch": ["RetroArch"], "Dolphin": ["Dolphin"], "PPSSPP": ["PPSSPPSDL", "PPSSPP"],+ "Ryujinx": ["Ryujinx"], "PCSX2": ["PCSX2"], "RPCS3": ["RPCS3"], "Cemu": ["Cemu"], "DuckStation": ["DuckStation"],+ "melonDS": ["melonDS"], "UTM": ["UTM"], "Provenance": ["Provenance"]}+ hits = sorted(k for k, names in c.items() if _app(h, *names))+ if _isdir(_AS(h, "OpenEmu")) and "OpenEmu" not in hits:+ hits.append("OpenEmu")+ return {"present": True, "found": hits} if hits else None+++# ================================================================== media++@_mp("media.libraries", level="L1", family=MEDIA, tier="T1", collect="core")+def media_libraries(h, facts):+ """Music/Movies/Pictures file counts by type and size (bounded walk; Photos/Music library packages not+ entered), Apple Photos and Music library package sizes (stat only), screenshot count."""+ kf = bf._cached(h, "kf", _known_folders_mac)+ out = {}+ for short in ("Music", "Videos", "Pictures"):+ p = kf.get(short) or os.path.join(_U(h), short)+ s = ug_games._walk_media(p, budget_s=0.6)+ s["gb"] = round(s.pop("bytes") / 1e9, 2)+ s["onedrive"] = False+ out[short] = s+ photos = [n for n in (_ls(kf.get("Pictures") or "") or []) if n.endswith(".photoslibrary")]+ out["photos_libraries"] = len(photos)+ out["apple_music_library"] = _ex(os.path.join(kf.get("Music") or "", "Music", "Music Library.musiclibrary"))+ out["screenshots"] = sum(1 for n in (_ls(kf.get("Screenshots") or "", 20000) or []) if bf_content.SHOT_NAME.match(n))+ return {"present": True, **out}+++@_mp("media.obs", level="L1", family=MEDIA, tier="T0", collect="core")+def media_obs(h, facts):+ """OBS Studio app bundle and whether a config dir exists (launched at least once); other recorders."""+ b = _app(h, "OBS")+ cfg = _isdir(_AS(h, "obs-studio"))+ others = [n for n in ("Screen Studio", "Loom", "CleanShot X", "Cap", "Kap", "ScreenFlow", "Descript") if _app(h, n)]+ if not (b or cfg):+ return None+ return {"present": True, "obs_installs": ["app"] if b else [], "obs_configs": ["native"] if cfg else [],+ "config_dir": cfg, "version": (b or {}).get("version"), "obs_config_in_agent_container": 0,+ "streamlabs": bool(_app(h, "Streamlabs Desktop")), "streamlabs_config": False, "other_recorders": others}+++@_mp("media.players", level="L1", family=MEDIA, tier="T0", collect="core")+def media_players(h, facts):+ """Music/video players and streaming apps: Spotify, Apple Music/TV/Podcasts (library present), IINA, VLC, mpv,+ Infuse, Plex, Jellyfin, TIDAL, ..."""+ kf = bf._cached(h, "kf", _known_folders_mac)+ found = {"spotify": bool(_app(h, "Spotify")) or _isdir(_AS(h, "Spotify")),+ "apple_music": _ex(os.path.join(kf.get("Music") or "", "Music", "Music Library.musiclibrary")),+ "apple_tv": _isdir(_AS(h, "TV")) or _ex(os.path.join(kf.get("Videos") or "", "TV")),+ "podcasts": _isdir(_LIB(h, "Group Containers", "243LU875E5.groups.com.apple.podcasts")),+ "iina": bool(_app(h, "IINA")), "vlc": bool(_app(h, "VLC")), "mpv": bool(_which(h, "mpv")) or bool(_app(h, "mpv")),+ "infuse": bool(_app(h, "Infuse 7", "Infuse")), "plex": bool(_app(h, "Plex", "Plexamp")),+ "jellyfin": bool(_app(h, "Jellyfin Media Player")), "tidal": bool(_app(h, "TIDAL")),+ "youtube_music": bool(_app(h, "YouTube Music")), "audirvana": bool(_app(h, "Audirvana Studio"))}+ hits = sorted(k for k, v in found.items() if v)+ return {"present": True, "players": hits} if hits else None+++VLC_PREFS = ("Library", "Preferences", "org.videolan.vlc.plist")+++@_mp("media.vlc", level="L1", family=MEDIA, tier="T0", collect="core")+def media_vlc(h, facts):+ """VLC app bundle and whether its preferences exist (launched)."""+ b = _app(h, "VLC")+ cfg = _ex(os.path.join(_U(h), *VLC_PREFS), _AS(h, "org.videolan.vlc"))+ return {"present": True, "installed": bool(b), "version": (b or {}).get("version"), "user_config": cfg} \+ if (b or cfg) else None+++@_mp("media.vlc_recents", level="L2", family=MEDIA, tier="T2", collect="extended", gate="media.vlc")+def media_vlc_recents(h, facts):+ """VLC recent-media count, local vs stream split and extension histogram; the list itself is not emitted."""+ d = _plist(os.path.join(_U(h), *VLC_PREFS)) or {}+ items = d.get("recentlyPlayedMedia") or d.get("NSRecentDocuments") or []+ if isinstance(items, dict):+ items = list(items.keys())+ items = [str(x) for x in items if isinstance(x, (str, bytes))][:500] if isinstance(items, list) else []+ if not items:+ return {"present": False}+ kinds = collections.Counter("local" if x.startswith(("file:", "/")) else "stream" for x in items)+ exts = collections.Counter()+ for x in items:+ m2 = re.search(r"\.([A-Za-z0-9]{1,5})$", x.split("?")[0])+ exts["." + m2.group(1).lower() if m2 else ""] += 1+ return {"present": True, "count": len(items), "kinds": dict(kinds), "ext": dict(exts),+ "ini_mtime": _mtime(os.path.join(_U(h), *VLC_PREFS))}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_system.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_system.pyindex 665da85702d..f5f390bd7e2 100644--- a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_system.py+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_system.py@@ -25,7 +25,7 @@ import sqlite3import threadingimport time-from userscan.registry import probe+from ..registry import probeOS = "darwin"MAC_EPOCH = 978307200 # 2001-01-01 UTC, Core Data / Cocoa absolute timediff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/derive.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/derive.pyindex ed24a05536a..3392a890272 100644--- a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/derive.py+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/derive.py@@ -11,7 +11,7 @@ import jsonimport refrom datetime import datetime, timedelta, timezone-from userscan.registry import insight+from ..registry import insightOPERATOR_TOKENS = ("hn-e2e", "ns960", "ns923", "\\lhm", "/lhm", "\\shots", "user-insights-lab","\\hermes-", "/hermes-", ".hermes-test")diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/host_identity.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/host_identity.pyindex 4bbf06f919d..0c9d1e54cdc 100644--- a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/host_identity.py+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/host_identity.py@@ -11,7 +11,7 @@ import osimport reimport sys-from userscan.registry import probe, ps_probe+from ..registry import probe, ps_probe# ---------------------------------------------------------------- helpersdiff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_apps.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_apps.pyindex 6b6b4411804..a469d2f205a 100644--- a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_apps.py+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_apps.py@@ -1,4 +1,5 @@-"""Linux user-level probes: apps, ai_agents, dev, browser, comms_work, files, gaming, media.+"""Linux user-level probes: apps, ai_agents. The dev, browser/comms_work and files/gaming/media families live+in linux_apps_dev, linux_apps_browser and linux_apps_files and share this module's helpers.Registration only at import time. Signal ids match the Windows modules wherever Linux has a source, soderive.py rules fire unchanged. Where a Windows extractor is path-agnostic (Claude/Codex JSONL scans,@@ -23,10 +24,10 @@ import shutilimport subprocessimport time-from userscan.registry import REGISTRY, probe-from userscan.specs import apps_dev as ad-from userscan.specs import browser_files as bf-from userscan.specs import usage_gaming as ug+from ..registry import REGISTRY, probe+from . import apps_dev as ad+from . import browser_files as bf+from . import apps_dev_agents as ad_agentsLX = "linux"APPS, AI, DEV, BROWSER, COMMS, FILES, GAMING, MEDIA = (@@ -167,14 +168,14 @@ def _which(h, name):_SPAWN_PATH = None-def _spawn(args, timeout=5.0):+def _spawn(h, args, timeout=5.0):"""(rc, stdout, ms) with stdin closed; stderr dropped. PATH gains the user's tool dirs so #!/usr/bin/env nodeshims (npm, pnpm) resolve their interpreter."""t = time.perf_counter()try:- path = os.environ.get("PATH", "") + ":" + ":".join(_extra_bins_static())+ path = h.child_env().get("PATH", "") + ":" + ":".join(_extra_bins_static())r = subprocess.run(args, capture_output=True, timeout=timeout, stdin=subprocess.DEVNULL,- env=dict(os.environ, PATH=path, NO_COLOR="1", HERMES_NO_UPDATE_CHECK="1", LC_ALL="C"))+ env=h.child_env(PATH=path, NO_COLOR="1", HERMES_NO_UPDATE_CHECK="1", LC_ALL="C"))return r.returncode, (r.stdout or b"").decode("utf-8", "replace").strip(), round((time.perf_counter() - t) * 1000, 1)except Exception:return None, "", round((time.perf_counter() - t) * 1000, 1)@@ -615,7 +616,7 @@ _PROC_INTEREST = re.compile(r"claude|codex|hermes|ollama|lm ?studio|cursor|windsdef tasks_nonms(h, facts):"""This user's scheduled jobs: `crontab -l` entry count and command names, systemd --user timers; lab jobs countedseparately."""- rc, txt, _ms = _spawn(["crontab", "-l"], timeout=2) if shutil.which("crontab") else (None, "", 0)+ rc, txt, _ms = _spawn(h, ["crontab", "-l"], timeout=2) if shutil.which("crontab") else (None, "", 0)jobs = [l for l in txt.splitlines() if l.strip() and not l.lstrip().startswith("#") and not re.match(r"^\w+=", l.strip())]names, op = collections.Counter(), 0for j in jobs:@@ -714,7 +715,7 @@ def browser_automation(h, facts):return {"present": bool(out), **out}-_mirror("browser_harness.present", ad.browser_harness_present)+_mirror("browser_harness.present", ad_agents.browser_harness_present)@_lp("claude_code.present", level="L1", family=AI, tier="T0", collect="core")@@ -737,10 +738,10 @@ def claude_code_present(h, facts):"home_mtime": _mtime(home), "running": sum(_running(h, r"^claude$|claude-code").values())}-_mirror("claude_code.config", ad.claude_code_config)-_mirror("claude_code.claude_json", ad.claude_code_claude_json)-_mirror("claude_code.sessions", ad.claude_code_sessions)-_mirror("claude_code.titles", ad.claude_code_titles)+_mirror("claude_code.config", ad_agents.claude_code_config)+_mirror("claude_code.claude_json", ad_agents.claude_code_claude_json)+_mirror("claude_code.sessions", ad_agents.claude_code_sessions)+_mirror("claude_code.titles", ad_agents.claude_code_titles)@_lp("claude_desktop.present", level="L1", family=AI, tier="T0", collect="core")@@ -757,7 +758,7 @@ def claude_desktop_present(h, facts):@_lp("codex.present", level="L1", family=AI, tier="T0", collect="core")def codex_present(h, facts):"""OpenAI Codex CLI: ~/.codex home (or CODEX_HOME), npm global, binary on PATH."""- home = ad._codex_home(h)+ home = ad_agents._codex_home(h)npm = _npm_pkg(h, "@openai/codex")exe = _which(h, "codex")if not (_isdir(home) or npm or exe):@@ -769,15 +770,15 @@ def codex_present(h, facts):@_lp("codex.auth_presence", level="L1", family=AI, tier="T3", collect="core")def codex_auth_presence(h, facts):"""Codex auth.json presence/size/mtime (never opened)."""- return h.meta(os.path.join(ad._codex_home(h), "auth.json"))+ return h.meta(os.path.join(ad_agents._codex_home(h), "auth.json"))-_mirror("codex.config", ad.codex_config)-_mirror("codex.usage", ad.codex_usage)-_mirror("codex.extras", ad.codex_extras)-_mirror("codex.chatgpt_catalog", ad.codex_chatgpt_catalog)-_mirror("copilot_cli.present", ad.copilot_cli_present)-_mirror("docker.model_runner", ad.docker_model_runner)+_mirror("codex.config", ad_agents.codex_config)+_mirror("codex.usage", ad_agents.codex_usage)+_mirror("codex.extras", ad_agents.codex_extras)+_mirror("codex.chatgpt_catalog", ad_agents.codex_chatgpt_catalog)+_mirror("copilot_cli.present", ad_agents.copilot_cli_present)+_mirror("docker.model_runner", ad_agents.docker_model_runner)@_lp("cua_driver.present", level="L1", family=AI, tier="T0", collect="core")@@ -816,7 +817,7 @@ def _prime_hermes(h):def hermes_present(h, facts):"""Hermes Agent: HERMES_HOME / ~/.hermes, install method, agent version, gateway unit, running processes."""_prime_hermes(h)- hh = ad._hermes_homes(h)+ hh = ad_agents._hermes_homes(h)homes = []for c in hh["cands"]:p = c["path"]@@ -848,11 +849,11 @@ def hermes_present(h, facts):"running": sum(_running(h, r"hermes").values())}-_mirror("hermes.auth_presence", ad.hermes_auth_presence, _prime_hermes)-_mirror("hermes.config", ad.hermes_config, _prime_hermes)-_mirror("hermes.skills", ad.hermes_skills, _prime_hermes)-_mirror("hermes.usage", ad.hermes_usage, _prime_hermes)-_mirror("hermes.titles", ad.hermes_titles, _prime_hermes)+_mirror("hermes.auth_presence", ad_agents.hermes_auth_presence, _prime_hermes)+_mirror("hermes.config", ad_agents.hermes_config, _prime_hermes)+_mirror("hermes.skills", ad_agents.hermes_skills, _prime_hermes)+_mirror("hermes.usage", ad_agents.hermes_usage, _prime_hermes)+_mirror("hermes.titles", ad_agents.hermes_titles, _prime_hermes)@_lp("l3.mcp_inventory", level="L2", family=AI, tier="T0", collect="core", gate="ai.catalog_absent_checks")@@ -861,10 +862,10 @@ def l3_mcp_inventory(h, facts):_prime_hermes(h)U = _U(h)by = {}- cj = ad._claude_json(h)+ cj = ad_agents._claude_json(h)if cj:by["claude_code"] = sorted(set(cj["global_mcp_servers"]) | set(cj["project_mcp_servers"]))- cp = os.path.join(ad._codex_home(h), "config.toml")+ cp = os.path.join(ad_agents._codex_home(h), "config.toml")if ad.tomllib and os.path.exists(cp):try:with open(cp, "rb") as f:@@ -883,15 +884,15 @@ def l3_mcp_inventory(h, facts):if isinstance(j.get(k), dict):by[label] = sorted(j[k].keys())break- p = ad._hermes_homes(h)["primary"]+ p = ad_agents._hermes_homes(h)["primary"]if p and os.path.exists(os.path.join(p["path"], "config.yaml")):try:- by["hermes"] = ad._parse_hermes_yaml(os.path.join(p["path"], "config.yaml"))["mcp_servers"]+ by["hermes"] = ad_agents._parse_hermes_yaml(os.path.join(p["path"], "config.yaml"))["mcp_servers"]except OSError:pass- user = sorted({n for v in by.values() for n in v if n not in ad.BUNDLED_MCP})+ user = sorted({n for v in by.values() for n in v if n not in ad_agents.BUNDLED_MCP})return {"present": True, "by_agent": {k: v for k, v in by.items() if v}, "user_configured": user,- "user_configured_total": len(user), "vendor_bundled": sorted({n for v in by.values() for n in v if n in ad.BUNDLED_MCP})}+ "user_configured_total": len(user), "vendor_bundled": sorted({n for v in by.values() for n in v if n in ad_agents.BUNDLED_MCP})}@_lp("ollama.present", level="L1", family=AI, tier="T0", collect="core")@@ -899,7 +900,7 @@ def ollama_present(h, facts):"""Ollama: binary, systemd unit, per-user models dir; the service account's home is stat'ed, never listed."""exe = _which(h, "ollama")unit = _first("/etc/systemd/system/ollama.service", "/usr/lib/systemd/system/ollama.service")- mroot = ad._ollama_models_root(h)+ mroot = ad_agents._ollama_models_root(h)svc_home = _isdir("/usr/share/ollama")if not (exe or unit or _isdir(os.path.join(_U(h), ".ollama")) or svc_home):return None@@ -908,1425 +909,4 @@ def ollama_present(h, facts):"running": _running(h, r"^ollama")}-_mirror("ollama.models", ad.ollama_models)---# ================================================================== dev--@_lp("apps.pkg_managers", level="L1", family=DEV, tier="T0", collect="core")-def apps_pkg_managers(h, facts):- """Package managers: apt (inbox), snap, flatpak, brew, nix, npm/pnpm/bun/yarn, cargo, go, uv, pipx."""- U = _U(h)- b = {"apt": os.path.exists("/usr/bin/apt"), "snap": os.path.exists("/usr/bin/snap"),- "flatpak": os.path.exists("/usr/bin/flatpak"), "brew": _ex("/home/linuxbrew/.linuxbrew/bin/brew", os.path.join(U, ".linuxbrew")),- "nix": _ex("/nix", os.path.join(U, ".nix-profile")), "npm": bool(_which(h, "npm")), "pnpm": bool(_which(h, "pnpm")),- "bun": bool(_which(h, "bun")), "yarn": bool(_which(h, "yarn")), "cargo": bool(_which(h, "cargo")),- "go": bool(_which(h, "go")), "uv": bool(_which(h, "uv")), "pipx": bool(_which(h, "pipx")),- "fnm": bool(_which(h, "fnm")) or _isdir(_data(h, "fnm")), "nvm": _isdir(os.path.join(U, ".nvm"))}- inbox = {"apt", "snap"}- return {"present": True, **b, "managers": sorted(k for k, v in b.items() if v and k not in inbox)}---def _ls_pkgs(root, cap=500):- names = _ls(root, cap)- if names is None:- return None- pk = []- for n in names:- if n.startswith("@"):- pk += [f"{n}/{s}" for s in (_ls(os.path.join(root, n), 100) or [])]- elif not n.startswith("."):- pk.append(n)- return sorted(pk)---@_lp("dev.npm_globals", level="L2", family=DEV, tier="T1", collect="core", gate="apps.pkg_managers")-def dev_npm_globals(h, facts):- """Global JS packages by manager (npm roots incl. fnm/nvm, pnpm, bun, yarn); directory listings, no spawn."""- U = _U(h)- out, allp = {}, set()- for r in _npm_roots(h):- pk = [p for p in (_ls_pkgs(r) or []) if p not in ("npm", "corepack")]- if pk:- key = "npm_user" if r.startswith(U) else "npm_system"- out.setdefault(key, []).extend(pk)- allp.update(pk)- for key, r in (("pnpm", _data(h, "pnpm", "global", "5", "node_modules")),- ("bun", os.path.join(U, ".bun", "install", "global", "node_modules")),- ("yarn", _cfg(h, "yarn", "global", "node_modules"))):- pk = _ls_pkgs(r)- if pk:- out[key] = pk- allp.update(pk)- if not out:- return {"present": False}- return {"present": True, "count": len(allp), "packages": sorted(allp)[:80],- "by_manager": {k: len(set(v)) for k, v in out.items()}}---@_lp("dev.lang_globals", level="L2", family=DEV, tier="T1", collect="core", gate="apps.pkg_managers")-def dev_lang_globals(h, facts):- """cargo-installed crates (~/.cargo/.crates2.json) and ~/go/bin binaries; names only."""- U = _U(h)- out = {}- cj = _read_json(os.path.join(U, ".cargo", ".crates2.json"))- if isinstance(cj, dict) and isinstance(cj.get("installs"), dict):- out["cargo"] = sorted({k.split(" ")[0] for k in cj["installs"]})[:60]- elif _isdir(os.path.join(U, ".cargo", "bin")):- out["cargo_bin"] = sorted(n for n in _ls(os.path.join(U, ".cargo", "bin")) or [] if not n.startswith("."))[:60]- gb = _ls(os.path.join(os.environ.get("GOPATH") or os.path.join(U, "go"), "bin"))- if gb:- out["go_bin"] = sorted(gb)[:60]- if not out:- return {"present": False}- return {"present": True, "count": sum(len(v) for v in out.values()), **out}---@_lp("dev.uv_tools", level="L2", family=DEV, tier="T1", collect="core", gate="dev.toolchain_presence")-def dev_uv_tools(h, facts):- """uv tools and uv-managed Pythons (~/.local/share/uv listing, equals `uv tool list`), ~/.local/bin entries."""- tools = _ls(_data(h, "uv", "tools"), 200)- py = _ls(_data(h, "uv", "python"), 200)- lb = _ls(os.path.join(_U(h), ".local", "bin"), 300)- if tools is None and py is None and lb is None:- return {"present": False}- return {"present": True, "tools": sorted(t for t in (tools or []) if not t.startswith("."))[:60],- "pythons": sorted(p for p in (py or []) if p.startswith(("cpython", "pypy")))[:30],- "local_bin_count": len(lb or []), "local_bin": sorted(lb or [])[:40]}---@_lp("dev.git", level="L1", family=DEV, tier="T0", collect="core")-def dev_git(h, facts):- """git binary on PATH (no spawn); version comes from dev.toolchain_versions."""- exe = _which(h, "git")- if not exe:- return None- return {"present": True, "on_path": bool(shutil.which("git")), "path_kind": "user" if exe.startswith(_U(h)) else "system",- "xdg_config": os.path.exists(_cfg(h, "git", "config"))}---_mirror("dev.git_global_config", ad.dev_git_global_config)---@_lp("dev.gh_auth_presence", level="L1", family=DEV, tier="T3", collect="core")-def dev_gh_auth_presence(h, facts):- """GitHub CLI hosts.yml presence/size (means gh logged in; never opened)."""- return h.meta(_cfg(h, "gh", "hosts.yml"))---@_lp("dev.docker_config_presence", level="L1", family=DEV, tier="T3", collect="core")-def dev_docker_config_presence(h, facts):- """~/.docker/config.json presence/size (may hold registry auths; never opened)."""- return h.meta(os.path.join(_U(h), ".docker", "config.json"))---_mirror("dev.npmrc_presence", ad.dev_npmrc_presence)--_PATH_TOOLS = [("local_bin", r"/\.local/bin$"), ("home_bin", r"^/home/[^/]+/bin$"), ("bun", r"/\.bun/bin"),- ("cargo", r"/\.cargo/bin"), ("go", r"/go/bin"), ("fnm", r"fnm"), ("nvm", r"\.nvm"), ("volta", r"\.volta"),- ("pnpm", r"pnpm"), ("deno", r"\.deno"), ("snap", r"^/snap/bin"), ("flatpak", r"flatpak/exports/bin"),- ("linuxbrew", r"linuxbrew"), ("nix", r"\.nix-profile|/nix/"), ("cuda", r"cuda"), ("conda", r"conda|miniforge"),- ("pyenv", r"\.pyenv"), ("hermes", r"hermes"), ("games", r"^/usr(/local)?/games$"), ("opt", r"^/opt/")]---@_lp("dev.path_entries", level="L1", family=DEV, tier="T0", collect="core")-def dev_path_entries(h, facts):- """PATH entry count and known-tool dir matches for this process (paths not emitted); user bin dirs off PATH."""- ents = [e for e in os.environ.get("PATH", "").split(":") if e]- tools = sorted({t for t, rx in _PATH_TOOLS for e in ents if re.search(rx, e)})- off = [os.path.relpath(d, _U(h)) for d in _extra_bins(h)- if d.startswith(_U(h)) and _isdir(d) and d not in ents]- return {"present": True, "entries": len(ents), "user": sum(1 for e in ents if e.startswith(_U(h))),- "machine": sum(1 for e in ents if not e.startswith(_U(h))), "tools": tools, "user_bin_dirs_off_path": off}---_mirror("dev.ssh_config", ad.dev_ssh_config)--_TOOLCHAIN = ["node", "npm", "pnpm", "yarn", "bun", "deno", "fnm", "nvm", "volta", "uv", "pipx", "conda", "poetry",- "rustc", "cargo", "rustup", "go", "dotnet", "java", "javac", "mvn", "gradle", "cmake", "ninja", "make", "clang",- "gcc", "zig", "nvcc", "gh", "docker", "podman", "kubectl", "terraform", "tailscale", "claude", "codex",- "hermes", "ollama", "code", "cursor", "windsurf", "zed", "nvim", "vim", "emacs", "kate", "python3", "python",- "tmux", "zellij", "lazygit", "rg", "fd", "fzf", "zoxide", "mcfly", "btop", "htop", "jq", "ssh", "mosh"]---@_lp("dev.toolchain_presence", level="L1", family=DEV, tier="T0", collect="core")-def dev_toolchain_presence(h, facts):- """which() for language/infra/AI/editor CLIs over PATH plus user tool dirs; off-PATH install dirs."""- U = _U(h)- found, user_found = [], []- for t in _TOOLCHAIN:- p = _which(h, t)- if p:- found.append(t)- if p.startswith(U):- user_found.append(t)- off = {k: _isdir(p) for k, p in [- ("cargo_home", os.path.join(U, ".cargo")), ("rustup", os.path.join(U, ".rustup")), ("go_root", "/usr/local/go"),- ("gopath", os.path.join(U, "go")), ("uv_pythons", _data(h, "uv", "python")), ("pyenv", os.path.join(U, ".pyenv")),- ("miniconda", os.path.join(U, "miniconda3")), ("anaconda", os.path.join(U, "anaconda3")),- ("miniforge", os.path.join(U, "miniforge3")), ("fnm_nodes", _data(h, "fnm", "node-versions")),- ("nvm", os.path.join(U, ".nvm")), ("cuda", "/usr/local/cuda"), ("sdkman", os.path.join(U, ".sdkman")),- ("android_sdk", os.path.join(U, "Android", "Sdk")), ("dotnet", os.path.join(U, ".dotnet"))]}- return {"present": True, "on_path": found, "user_installed": user_found, "off_path": sorted(k for k, v in off.items() if v)}---@_lp("dev.toolchain_versions", level="L2", family=DEV, tier="T0", collect="extended", gate="dev.toolchain_presence",- timeout_ms=12000)-def dev_toolchain_versions(h, facts):- """--version spawns (parallel, gated on which) for runtimes, package managers, AI CLIs and infra CLIs.- `hermes --version` is excluded: it blocked > 10 s; hermes.present reads the version from pyproject."""- from concurrent.futures import ThreadPoolExecutor- specs = [("node", ["--version"]), ("npm", ["--version"]), ("uv", ["--version"]), ("gh", ["--version"]),- ("git", ["--version"]), ("docker", ["--version"]), ("bun", ["--version"]), ("pnpm", ["--version"]),- ("deno", ["--version"]), ("rustc", ["--version"]), ("cargo", ["--version"]), ("go", ["version"]),- ("python3", ["--version"]), ("claude", ["--version"]), ("codex", ["--version"]), ("ollama", ["--version"]),- ("tmux", ["-V"]), ("nvim", ["--version"]), ("kubectl", ["version", "--client=true"]),- ("tailscale", ["version"]), ("java", ["-version"])]- todo = [(n, [_which(h, n)] + a) for n, a in specs if _which(h, n)]-- def one(item):- name, args = item- rc, txt, ms = _spawn(args, timeout=3)- line = next((l.strip() for l in txt.splitlines() if l.strip()), None)- return name, {"version": ad._redact(line, 90) if line else None, "rc": rc, "ms": ms}- out = {}- with ThreadPoolExecutor(max_workers=6) as ex:- for name, r in ex.map(one, todo):- out[name] = r- return {"present": bool(out), "tools": out}---_EDITORS = {- # name: (install paths, extension dir(s), user dir)- "vscode": (["/usr/share/code", "/usr/bin/code", "/snap/code", "/var/lib/flatpak/app/com.visualstudio.code"],- [".vscode/extensions"], "Code"),- "vscode_insiders": (["/usr/share/code-insiders"], [".vscode-insiders/extensions"], "Code - Insiders"),- "vscode_server": ([], [".vscode-server/extensions"], None),- "cursor": (["/opt/Cursor", "/usr/share/cursor", "/usr/bin/cursor"], [".cursor/extensions"], "Cursor"),- "cursor_server": ([], [".cursor-server/extensions"], None),- "windsurf": (["/usr/share/windsurf", "/opt/Windsurf"], [".windsurf/extensions"], "Windsurf"),- "windsurf_server": ([], [".windsurf-server/extensions"], None),- "vscodium": (["/usr/share/codium", "/snap/codium"], [".vscode-oss/extensions"], "VSCodium"),- "kiro": (["/usr/share/kiro", "/opt/Kiro"], [".kiro/extensions"], "Kiro"),-}---@_lp("editor.vscode", level="L2", family=DEV, tier="T2", collect="core", gate="dev.toolchain_presence")-def editor_vscode(h, facts):- """VS Code family incl. Remote-SSH server dirs: extension ids (AI flagged), workspaces, MCP/chat; other editors."""- U = _U(h)- out = {}- for name, (inst, extds, userd) in _EDITORS.items():- installed = any(os.path.exists(p) for p in inst)- extd = next((os.path.join(U, e) for e in extds if _isdir(os.path.join(U, e))), None)- user = _cfg(h, userd, "User") if userd else None- if not (installed or extd or (user and _isdir(user))):- continue- ids = ad._ext_ids(extd) if extd else []- e = {"installed": installed, "extensions": len(ids), "extension_ids": ids[:80],- "ai_extensions": [i for i in ids if ad._AI_EXT.search(i)]}- if user and _isdir(user):- ws = _ls(os.path.join(user, "workspaceStorage"), 5000)- e["workspaces_opened"] = len(ws) if ws is not None else 0- e["settings_json"] = os.path.exists(os.path.join(user, "settings.json"))- e["keybindings_json"] = os.path.exists(os.path.join(user, "keybindings.json"))- e["profiles"] = len(_ls(os.path.join(user, "profiles")) or [])- mj = _read_json(os.path.join(user, "mcp.json"), jsonc=True)- e["mcp_servers"] = len((mj.get("servers") or mj.get("mcpServers") or {})) if isinstance(mj, dict) else 0- e["chat_sessions"] = len(glob.glob(os.path.join(user, "workspaceStorage", "*", "chatSessions", "*"))[:5000])- e["user_mtime"] = _mtime(user)- if name.endswith("_server"):- e["remote_target"] = True- e["user_mtime"] = _mtime(extd) if extd else None- out[name] = e- other = {"jetbrains": [x for x in (_ls(_cfg(h, "JetBrains")) or []) if re.match(r"^[A-Za-z]+\d{4}\.\d", x)],- "zed": _isdir(_cfg(h, "zed")) or _isdir(_data(h, "zed")),- "neovim_config": _isdir(_cfg(h, "nvim")), "vimrc": _ex(os.path.join(U, ".vimrc"), os.path.join(U, ".vim")),- "emacs": _ex(os.path.join(U, ".emacs.d"), os.path.join(U, ".emacs"), _cfg(h, "emacs")),- "helix": _isdir(_cfg(h, "helix")), "sublime": _isdir(_cfg(h, "sublime-text")),- "kate": _ex(_cfg(h, "katerc")), "kwrite": _ex(_cfg(h, "kwriterc"))}- other = {k: v for k, v in other.items() if v}- customised = any(e["extensions"] or e.get("settings_json") or e.get("keybindings_json") for e in out.values()) or \- bool(other.get("neovim_config") or other.get("emacs"))- return {"present": bool(out or other), "extensions": sum(e["extensions"] for e in out.values()),- "customised": customised, "editors": out, "other": other}---# ---------------- repos (deep)--_REPO_SKIP = {"node_modules", ".cache", "__pycache__", ".venv", "venv", "site-packages", ".npm", ".rustup", "snap",- ".cargo", ".bun", ".vscode-server", ".cursor-server", ".mozilla", "trash", ".local/share/trash",- "target", "dist", "build", ".next", ".git", "go", ".gradle", ".m2", ".nvm", ".pyenv", "miniconda3",- "anaconda3", ".docker", ".ollama", ".var", ".steam"}---def _repos_lx(h):- """Bounded repo walk: home depth 5, 60k dirs, 8 s; classes user_area / tool_managed (dot dirs) / operator."""- def build():- deadline = time.perf_counter() + 8.0- U = _U(h)- hits, seen, visited = [], set(), [0]- stack = [(U, 0)]- while stack and time.perf_counter() < deadline and visited[0] < 60000:- d, depth = stack.pop()- visited[0] += 1- try:- with os.scandir(d) as it:- ents = list(zip(range(3000), it))- except OSError:- continue- names = {e.name for _, e in ents}- if ".git" in names and (os.path.exists(os.path.join(d, ".git", "HEAD")) or os.path.isfile(os.path.join(d, ".git"))):- rp = os.path.realpath(d)- if rp not in seen:- seen.add(rp)- hits.append(d)- continue- if depth >= 5:- continue- for _, e in ents:- if e.name.lower() in _REPO_SKIP:- continue- try:- if not e.is_dir(follow_symlinks=False):- continue- except OSError:- continue- stack.append((e.path, depth + 1))- repos = []- for d in hits[:200]:- rel = os.path.relpath(d, U)- cls = "operator" if _is_op(h, d) else "tool_managed" if rel.startswith(".") else "user_area"- gd = os.path.join(d, ".git")- remotes, branch, head_mtime, local_email = [], None, None, None- if os.path.isdir(gd):- try:- with open(os.path.join(gd, "HEAD"), encoding="utf-8", errors="replace") as f:- hd = f.read(200).strip()- branch = hd[16:] if hd.startswith("ref: refs/heads/") else "detached"- except OSError:- pass- head_mtime = _mtime(os.path.join(gd, "logs", "HEAD")) or _mtime(os.path.join(gd, "index"))- try:- with open(os.path.join(gd, "config"), encoding="utf-8", errors="replace") as f:- cfg = f.read(100_000)- remotes = re.findall(r"^\s*url\s*=\s*(\S+)", cfg, re.M)- m = re.search(r"^\s*email\s*=\s*(\S+)", cfg, re.M)- local_email = m.group(1).lower() if m else None- except OSError:- pass- markers = [m for m in ("package.json", "pyproject.toml", "uv.lock", "Cargo.toml", "go.mod", "pom.xml",- "build.gradle", "Dockerfile", "flake.nix", "AGENTS.md", "CLAUDE.md", ".mcp.json")- if os.path.exists(os.path.join(d, m))]- repos.append({"path": d, "class": cls, "branch": branch, "head_mtime": head_mtime, "remotes": remotes,- "local_email": local_email, "markers": markers})- return {"repos": repos, "visited_dirs": visited[0], "timed_out": time.perf_counter() >= deadline}- return build---def _commits_lx(h):- def build():- git = _which(h, "git")- if not git:- return None- env_ids = {x.strip().lower() for x in os.environ.get("UIL_GIT_IDENTITY", "").split(",") if x.strip()}- ids = set(env_ids)- for gc in (os.path.join(_U(h), ".gitconfig"), _cfg(h, "git", "config")):- try:- with open(gc, encoding="utf-8", errors="replace") as f:- ids |= {m.lower() for m in re.findall(r"^\s*email\s*=\s*(\S+)", f.read(100_000), re.M)}- except OSError:- pass- res = {"identity_sources": {"env": bool(env_ids), "global": bool(ids - env_ids), "repo_local": 0}, "by_class": {},- "hours_local": collections.Counter(), "tz_offsets": collections.Counter(), "weekday": collections.Counter(),- "month": collections.Counter(), "repos_with_own": {}}- # Newest HEAD first, so when the deadline cuts the scan it drops the stalest repos, not a random set.- deadline = time.perf_counter() + 10.0- res["repos_scanned"], res["timed_out"] = 0, False- for x in sorted(ad._repos(h)["repos"], key=lambda r: str(r.get("head_mtime") or ""), reverse=True):- if x["class"] == "operator":- continue- if time.perf_counter() > deadline:- res["timed_out"] = True- break- rid = set(ids)- if x["local_email"]:- rid.add(x["local_email"])- res["identity_sources"]["repo_local"] += 1- rc, txt, _ms = _spawn([git, "-C", x["path"], "log", "--all", "--no-merges",- "--format=%ae%x09%an%x09%at%x09%ai", "-n", "100000"], timeout=max(0.5, deadline - time.perf_counter()))- if rc != 0:- continue- res["repos_scanned"] += 1- mine = total = 0- for line in txt.splitlines():- parts = line.split("\t")- if len(parts) < 4:- continue- total += 1- if parts[0].lower() in rid or parts[1].lower() in rid:- mine += 1- try:- t = dt.datetime.fromtimestamp(int(parts[2]))- res["hours_local"][t.hour] += 1- res["weekday"][t.strftime("%a")] += 1- res["month"][t.strftime("%Y-%m")] += 1- except (ValueError, OSError):- pass- res["tz_offsets"][parts[3].strip()[-5:]] += 1- c = res["by_class"].setdefault(x["class"], [0, 0])- c[0] += mine- c[1] += total- if mine:- res["repos_with_own"][x["class"]] = res["repos_with_own"].get(x["class"], 0) + 1- return res- return build---def _prime_repos(h):- ad._memo(h, "repos", _repos_lx(h))---def _prime_commits(h):- _prime_repos(h)- ad._memo(h, "commits", _commits_lx(h))---# dev.repos and dev.repos.remotes need only the walk; priming commits there made them wait for git log on every repo.-_mirror("dev.repos", ad.dev_repos, _prime_repos)-_mirror("dev.repos.remotes", ad.dev_repos_remotes, _prime_repos)-_mirror("dev.repos.my_commits", ad.dev_repos_my_commits, _prime_commits)-_mirror("dev.repos.commit_hours", ad.dev_repos_commit_hours, _prime_commits)--_BUILTINS = {"cd", "export", "source", ".", "alias", "unalias", "echo", "exit", "history", "set", "unset", "eval", "exec",- "type", "which", "for", "if", "while", "sudo", "time", "nohup", "env", "clear", "pwd", "ls", "ll", "la", "fg",- "bg", "jobs", "kill", "z", "zi", "man", "help"}---def _cmd_name(line, known):- t = line.strip().split()- while t and (t[0] in ("sudo", "time", "nohup", "env", "exec") or "=" in t[0]):- t = t[1:]- if not t:- return None- c = os.path.basename(t[0])- if not re.fullmatch(r"[A-Za-z0-9._+\-]{1,32}", c):- return None- return c if c in _BUILTINS or c in known else None---@_lp("dev.shell_history", level="L2", family=DEV, tier="T1", collect="extended", gate="dev.path_entries")-def dev_shell_history(h, facts):- """bash/zsh/fish/python/node history: line counts, last write, top command names (resolved executables or- builtins only). Command lines, arguments and paths are never emitted."""- U = _U(h)- files = [("bash", os.path.join(U, ".bash_history")), ("zsh", os.environ.get("HISTFILE") or os.path.join(U, ".zsh_history")),- ("zsh_histfile", os.path.join(U, ".histfile")), ("fish", _data(h, "fish", "fish_history")),- ("python", os.path.join(U, ".python_history")), ("node", os.path.join(U, ".node_repl_history")),- ("mcfly_db", _data(h, "mcfly", "history.db")), ("atuin_db", _data(h, "atuin", "history.db"))]- known = set()- for d in os.environ.get("PATH", "").split(":") + _extra_bins(h):- known.update(_ls(d, 20000) or [])- out, cmds, total = {}, collections.Counter(), 0- seen = set()- for label, p in files:- try:- rp = os.path.realpath(p)- if rp in seen:- continue- st = os.stat(p)- except OSError:- continue- seen.add(rp)- if label.endswith("_db"):- out[label] = {"bytes": st.st_size, "mtime": _day(st.st_mtime)}- continue- if st.st_size > 50_000_000:- out[label] = {"bytes": st.st_size, "lines": None, "mtime": _day(st.st_mtime)}- continue- n = 0- with open(p, "rb") as f:- for raw in f:- line = raw.decode("utf-8", "replace").strip()- if not line:- continue- if label == "fish":- if not line.startswith("- cmd: "):- continue- line = line[7:]- elif label.startswith("zsh"):- line = re.sub(r"^: \d+:\d+;", "", line)- n += 1- if label in ("bash", "zsh", "zsh_histfile", "fish"):- c = _cmd_name(line, known)- if c:- cmds[c] += 1- out[label] = {"lines": n, "bytes": st.st_size, "mtime": _day(st.st_mtime)}- if label in ("bash", "zsh", "zsh_histfile", "fish"):- total += n- if not out:- return {"present": False}- return {"present": True, "lines": total, "files": out, "top_commands": dict(cmds.most_common(15)),- "distinct_commands": len(cmds)}---@_lp("dev.docker", level="L1", family=DEV, tier="T0", collect="core")-def dev_docker(h, facts):- """Docker engine/CLI: binary, socket access for this user, docker group, rootless or Desktop-for-Linux dirs."""- cli = _which(h, "docker")- sock = "/var/run/docker.sock"- rootless = os.path.join(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"), "docker.sock")- desktop = _isdir(os.path.join(_U(h), ".docker", "desktop"))- if not (cli or os.path.exists(sock) or desktop):- return None- try:- import grp- in_group = "docker" in {grp.getgrgid(g).gr_name for g in os.getgroups()}- except Exception:- in_group = None- return {"present": True, "cli": bool(cli), "engine_socket": os.path.exists(sock),- "socket_access": os.access(sock, os.R_OK | os.W_OK), "docker_group": in_group,- "rootless_socket": os.path.exists(rootless), "desktop_for_linux": desktop,- "podman": bool(_which(h, "podman")), "compose_plugin": _ex("/usr/libexec/docker/cli-plugins/docker-compose",- "/usr/lib/docker/cli-plugins/docker-compose")}---def _gb(s):- m = re.match(r"([\d.]+)\s*([kKMGT]?B)", s or "")- if not m:- return 0.0- return float(m.group(1)) * {"B": 1e-9, "kB": 1e-6, "KB": 1e-6, "MB": 1e-3, "GB": 1.0, "TB": 1e3}.get(m.group(2), 0)---@_lp("dev.docker_runtime", level="L2", family=DEV, tier="T2", collect="extended", gate="dev.docker", timeout_ms=8000)-def dev_docker_runtime(h, facts):- """`docker ps` names/images and `docker images` repos/sizes only; never exec, inspect or logs."""- d = _fact(facts, "dev.docker") or {}- cli = _which(h, "docker")- if not cli or not (d.get("socket_access") or d.get("rootless_socket")):- return {"present": True, "accessible": False, "count": 0}- rc, ps, ms1 = _spawn([cli, "ps", "--format", "{{.Names}}\t{{.Image}}\t{{.RunningFor}}"], timeout=5)- rc2, im, ms2 = _spawn([cli, "images", "--format", "{{.Repository}}:{{.Tag}}\t{{.Size}}"], timeout=5)- if rc != 0 and rc2 != 0:- return {"present": True, "accessible": False, "count": 0}- running = [dict(zip(("name", "image", "up"), l.split("\t"))) for l in ps.splitlines() if l.strip()]- images = [l.split("\t") for l in im.splitlines() if l.strip()]- return {"present": True, "accessible": True, "count": len(running),- "running": [{"name": r.get("name"), "image": (r.get("image") or "").split("@")[0][:80], "up": r.get("up")}- for r in running[:40]],- "images": len(images), "images_gb": round(sum(_gb(x[1]) for x in images if len(x) > 1), 2),- "image_repos": sorted({x[0].rsplit(":", 1)[0] for x in images})[:40], "ms": round(ms1 + ms2, 1)}---@_lp("dev.multiplexers", level="L2", family=DEV, tier="T1", collect="core", gate="dev.toolchain_presence")-def dev_multiplexers(h, facts):- """tmux / zellij / screen session counts for this user (session names not emitted)."""- uid = os.getuid()- out = {}- tdir = os.path.join(os.environ.get("TMUX_TMPDIR", "/tmp"), f"tmux-{uid}")- socks = [os.path.join(tdir, n) for n in (_ls(tdir) or [])]- tm = _which(h, "tmux")- if socks or tm:- n = 0- for s in socks[:10]:- rc, txt, _ = _spawn([tm, "-S", s, "ls"], timeout=2) if tm else (None, "", 0)- if rc == 0:- n += len([l for l in txt.splitlines() if l.strip()])- out["tmux"] = {"installed": bool(tm), "sockets": len(socks), "sessions": n,- "config": _ex(os.path.join(_U(h), ".tmux.conf"), _cfg(h, "tmux", "tmux.conf"))}- zj = _which(h, "zellij")- rt = os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{uid}")- zsocks = [p for p in glob.glob(os.path.join(rt, "zellij", "*", "*")) + glob.glob(os.path.join(tempfile_dir(), f"zellij-{uid}", "*", "*"))- if not os.path.isdir(p)]- zres = glob.glob(_cachedir(h, "zellij", "*", "session_info", "*"))- if zj or zsocks or zres:- out["zellij"] = {"installed": bool(zj), "live_sessions": len(zsocks), "resurrectable": len(zres),- "config": _isdir(_cfg(h, "zellij"))}- sd = _first(f"/run/screen/S-{os.environ.get('USER', '')}", os.path.join(_U(h), ".screen"))- if sd:- out["screen"] = {"sessions": len(_ls(sd) or [])}- if not out:- return {"present": False}- return {"present": True, "count": sum(v.get("sessions", 0) + v.get("live_sessions", 0) for v in out.values()), **out}---def tempfile_dir():- return os.environ.get("TMPDIR") or "/tmp"---# ================================================================== browser--_CHROMIUM = [("chrome", "google-chrome"), ("chrome_beta", "google-chrome-beta"), ("chrome_dev", "google-chrome-unstable"),- ("chromium", "chromium"), ("brave", "BraveSoftware/Brave-Browser"), ("brave_beta", "BraveSoftware/Brave-Browser-Beta"),- ("brave_nightly", "BraveSoftware/Brave-Browser-Nightly"), ("edge", "microsoft-edge"), ("edge_beta", "microsoft-edge-beta"),- ("edge_dev", "microsoft-edge-dev"), ("vivaldi", "vivaldi"), ("opera", "opera"), ("thorium", "thorium"),- ("yandex", "yandex-browser"), ("helium", "net.imput.helium")]-_CHROMIUM_EXTRA = [("chromium", "snap", ("chromium", "common", "chromium")),- ("brave", "snap", ("brave", "current", ".config", "BraveSoftware", "Brave-Browser")),- ("chrome", "flatpak", ("com.google.Chrome", "config", "google-chrome")),- ("brave", "flatpak", ("com.brave.Browser", "config", "BraveSoftware", "Brave-Browser")),- ("chromium", "flatpak", ("org.chromium.Chromium", "config", "chromium")),- ("edge", "flatpak", ("com.microsoft.Edge", "config", "microsoft-edge")),- ("vivaldi", "flatpak", ("com.vivaldi.Vivaldi", "config", "vivaldi"))]---def _gecko_roots(h):- U = _U(h)- return [("firefox", os.path.join(U, ".mozilla", "firefox")), ("firefox", _snapu(h, "firefox", "common", ".mozilla", "firefox")),- ("firefox", _flat(h, "org.mozilla.firefox", ".mozilla", "firefox")), ("librewolf", os.path.join(U, ".librewolf")),- ("librewolf", _flat(h, "io.gitlab.librewolf-community", ".librewolf")), ("zen", os.path.join(U, ".zen")),- ("floorp", os.path.join(U, ".floorp")), ("waterfox", os.path.join(U, ".waterfox")),- ("thunderbird_gecko", os.path.join(U, ".thunderbird")), ("tor", os.path.join(U, ".local", "share", "torbrowser"))]---def _catalog_lx(h):- found_c, found_g = {}, {}- n = 0- for bid, rel in _CHROMIUM:- n += 1- p = _cfg(h, *rel.split("/"))- if _isdir(p) and os.path.exists(os.path.join(p, "Local State")) and bid not in found_c:- found_c[bid] = p- for bid, kind, parts in _CHROMIUM_EXTRA:- n += 1- p = _snapu(h, *parts) if kind == "snap" else _flat(h, *parts)- key = bid if bid not in found_c else f"{bid}_{kind}"- if _isdir(p) and os.path.exists(os.path.join(p, "Local State")):- found_c[key] = p- for bid, root in _gecko_roots(h):- n += 1- if bid == "thunderbird_gecko":- continue- ok = _isdir(root) if bid == "tor" else os.path.isfile(os.path.join(root, "profiles.ini"))- if ok:- found_g[bid if bid not in found_g else f"{bid}_{len(found_g)}"] = root- return {"chromium": found_c, "gecko": found_g, "checked": n}---def _prime_browser(h):- bf._cached(h, "catalog", _catalog_lx)---@_lp("browser.catalog", level="L1", family=BROWSER, tier="T0", collect="core")-def browser_catalog(h, facts):- """Chromium (native/snap/flatpak under ~/.config, ~/snap, ~/.var) and Gecko (~/.mozilla...) user-data roots."""- c = bf._cached(h, "catalog", _catalog_lx)- return {"present": bool(c["chromium"] or c["gecko"]), "chromium": sorted(c["chromium"]), "gecko": sorted(c["gecko"]),- "checked": c["checked"]}---@_lp("browser.brave.present", level="L1", family=BROWSER, tier="T0", collect="core")-def brave_present(h, facts):- """Brave user-data dir exists (native, snap or flatpak)."""- for p in (_cfg(h, "BraveSoftware", "Brave-Browser"), _snapu(h, "brave", "current", ".config", "BraveSoftware", "Brave-Browser"),- _flat(h, "com.brave.Browser", "config", "BraveSoftware", "Brave-Browser")):- if _isdir(p):- m = h.meta(os.path.join(p, "Local State"))- return {"present": True, "local_state_mtime": bf._iso(m.get("mtime"))}- return {"present": False}---@_lp("browser.edge.present", level="L1", family=BROWSER, tier="T0", collect="core")-def edge_present(h, facts):- """Microsoft Edge user-data dir exists (native or flatpak); on Linux it is never preinstalled."""- for p in (_cfg(h, "microsoft-edge"), _flat(h, "com.microsoft.Edge", "config", "microsoft-edge")):- if _isdir(p):- return {"present": True, "local_state_mtime": bf._iso(h.meta(os.path.join(p, "Local State")).get("mtime"))}- return {"present": False}---def _mimeapps(h):- """Merged [Default Applications] from the XDG mimeapps.list chain (user files first). {mime: (desktop_id, scope)}."""- files = [("user", _cfg(h, "kde-mimeapps.list")), ("user", _cfg(h, "mimeapps.list")),- ("user", _data(h, "applications", "mimeapps.list")), ("system", "/etc/xdg/kde-mimeapps.list"),- ("system", "/etc/xdg/mimeapps.list"), ("system", "/usr/share/applications/kde-mimeapps.list"),- ("system", "/usr/share/applications/mimeapps.list"), ("system", "/usr/share/applications/defaults.list")]- out = {}- for scope, p in files:- t = _open_text(p, 2_000_000)- if not t:- continue- sec = None- for line in t.splitlines():- line = line.strip()- if line.startswith("["):- sec = line- continue- if sec in ("[Default Applications]",) and "=" in line:- k, v = line.split("=", 1)- first = next((x for x in v.split(";") if x), None)- if first and k.strip() not in out:- out[k.strip()] = (first, scope)- return out---_BROWSER_IDS = [("brave", r"brave"), ("chrome", r"google-chrome|com\.google\.chrome"), ("chromium", r"chromium"),- ("firefox", r"firefox"), ("edge", r"microsoft-edge"), ("vivaldi", r"vivaldi"), ("opera", r"opera"),- ("librewolf", r"librewolf"), ("zen", r"zen"), ("floorp", r"floorp"), ("falkon", r"falkon"),- ("konqueror", r"konqueror"), ("epiphany", r"epiphany")]---def _browser_of(desktop_id):- d = (desktop_id or "").lower()- return next((b for b, rx in _BROWSER_IDS if re.search(rx, d)), desktop_id)---@_lp("browser.default", level="L1", family=BROWSER, tier="T0", collect="core")-def browser_default(h, facts):- """Default browser from mimeapps.list (x-scheme-handler/https, http, text/html) or KDE BrowserApplication."""- m = _mimeapps(h)- got = {k: m[k] for k in ("x-scheme-handler/https", "x-scheme-handler/http", "text/html", "application/pdf") if k in m}- kde = None- t = _open_text(_cfg(h, "kdeglobals"), 2_000_000) or ""- km = re.search(r"^BrowserApplication=(.+)$", t, re.M)- if km:- kde = km.group(1).strip().lstrip("!")- pid = (got.get("x-scheme-handler/https") or got.get("x-scheme-handler/http") or got.get("text/html") or (None,))[0] or kde- if not pid:- return {"present": False}- src = got.get("x-scheme-handler/https") or got.get("x-scheme-handler/http") or got.get("text/html")- return {"present": True, "browser": _browser_of(pid), "prog_id": pid,- "set_by_user": bool(src and src[1] == "user") or bool(kde),- "handlers": {k: _browser_of(v[0]) for k, v in got.items()}, "kde_browser_application": _browser_of(kde) if kde else None}---@_lp("defaults.mailto_pdf_media", level="L1", family=BROWSER, tier="T0", collect="core")-def defaults_mailto_pdf_media(h, facts):- """Default handlers (desktop ids) for mailto, PDF, video, audio, images, text."""- m = _mimeapps(h)- keys = {"mailto": "x-scheme-handler/mailto", ".pdf": "application/pdf", ".mp4": "video/mp4", ".mkv": "video/x-matroska",- ".mp3": "audio/mpeg", ".jpg": "image/jpeg", ".png": "image/png", ".txt": "text/plain", ".md": "text/markdown",- ".py": "text/x-python"}- got = {k: m[v][0] for k, v in keys.items() if v in m}- return {"present": bool(got), "handlers": got}---@_lp("browser.registered", level="L2", family=BROWSER, tier="T0", collect="core", gate="apps.dpkg")-def browser_registered(h, facts):- """Browsers with a launchable .desktop entry that handles x-scheme-handler/http(s)."""- names = sorted({_browser_of(e["id"]) for e in _desktop(h) if "x-scheme-handler/http" in e["mime"]- and ("WebBrowser" in e["categories"] or "Network" in e["categories"])})- return {"present": bool(names), "browsers": names}---_T3_CHROMIUM = ("Cookies", "Network/Cookies", "Login Data", "Login Data For Account", "Web Data", "Account Web Data")-_T3_GECKO = ("cookies.sqlite", "logins.json", "key4.db", "formhistory.sqlite")---@_lp("browser.t3_presence", level="L1", family=BROWSER, tier="T3", collect="core")-def browser_t3_presence(h, facts):- """Credential/cookie stores per profile: stat only (size), never opened."""- _prime_browser(h)- rows = {}- for bid, ud, pdir, _i in bf._profiles(h):- base = os.path.join(ud, pdir) if pdir else ud- sizes = {f.replace("Network/", ""): m["bytes"] for f in _T3_CHROMIUM- for m in [h.meta(os.path.join(base, f))] if m.get("present")}- if sizes:- rows[bf._pkey(bid, pdir)] = sizes- for bid, root in bf._cached(h, "catalog", _catalog_lx)["gecko"].items():- for pd in glob.glob(os.path.join(root, "*"))[:30]:- sizes = {f: m["bytes"] for f in _T3_GECKO for m in [h.meta(os.path.join(pd, f))] if m.get("present")}- if sizes:- rows[f"{bid}:{len(rows)}"] = sizes- return {"present": bool(rows), "profiles": rows}---@_lp("browser.generic_sweep", level="L1", family=BROWSER, tier="T0", collect="extended")-def browser_generic_sweep(h, facts):- """Chromium-style user-data dirs under ~/.config not in the catalog (Local State + Default)."""- known = {os.path.realpath(p) for p in bf._cached(h, "catalog", _catalog_lx)["chromium"].values()}- unknown = []- for pat in (_cfg(h, "*", "Local State"), _cfg(h, "*", "*", "Local State")):- for p in glob.glob(pat)[:200]:- d = os.path.dirname(p)- if os.path.realpath(d) not in known and _isdir(os.path.join(d, "Default")) and not _is_op(h, d):- unknown.append(os.path.relpath(d, _U(h)))- return {"present": True, "unknown_forks": len(unknown), "roots": unknown[:10]}---for _id, _fn in (("browser.local_state", bf.browser_local_state), ("browser.tab_stats", bf.browser_tab_stats),- ("browser.profile_prefs", bf.browser_profile_prefs), ("browser.extensions", bf.browser_extensions),- ("browser.bookmarks", bf.browser_bookmarks), ("browser.history.copy", bf.history_copy),- ("browser.history.stats", bf.history_stats), ("browser.history.hour_weekday", bf.history_hour_weekday),- ("browser.history.top_domains", bf.history_top_domains),- ("browser.history.top_domains_named", bf.history_top_domains_named),- ("browser.history.localhost", bf.history_localhost), ("browser.history.downloads", bf.history_downloads),- ("browser.history.search_terms", bf.history_search_terms),- ("browser.history.github_repos", bf.history_github_repos), ("browser.firefox.history", bf.firefox_history),- ("l3.browser_category_share", bf.l3_browser_category_share), ("l3.primary_browser", bf.l3_primary_browser),- ("l3.browser_rhythm", bf.l3_browser_rhythm), ("l3.browser_persona_hints", bf.l3_browser_persona_hints),- ("browser.history.workspaces", bf.history_workspaces), ("browser.history.work_hosts", bf.history_work_hosts)):- _mirror(_id, _fn, _prime_browser)---# ================================================================== comms_work--def _app_row(h, installs, data_dirs, activity):- """installed/launched/last-used for one app. activity = files whose mtime means the app ran."""- inst = [p for p in installs if os.path.exists(p)]- data = [p for p in data_dirs if _isdir(p)]- if not (inst or data):- return None- last = _newest_mtime([a for a in activity if a] + data)- return {"installed": bool(inst), "launched": bool(data), "last_used": _day(last),- "recent_use": bool(last and time.time() - last < 30 * 86400)}---def _comms_cands(h):- U = _U(h)- return {- "slack": (["/usr/bin/slack", "/usr/lib/slack", "/snap/slack", "/var/lib/flatpak/app/com.slack.Slack"],- [_cfg(h, "Slack"), _snapu(h, "slack", "current", ".config", "Slack"), _flat(h, "com.slack.Slack", "config", "Slack")],- [_cfg(h, "Slack", "logs"), _cfg(h, "Slack", "Local Storage")]),- "telegram": (["/usr/bin/telegram-desktop", "/opt/telegram", "/snap/telegram-desktop", "/var/lib/flatpak/app/org.telegram.desktop"],- [_data(h, "TelegramDesktop"), _flat(h, "org.telegram.desktop", "data", "TelegramDesktop"),- _snapu(h, "telegram-desktop", "current", ".local", "share", "TelegramDesktop")],- [_data(h, "TelegramDesktop", "tdata", "settingss")]),- "signal": (["/usr/bin/signal-desktop", "/opt/Signal", "/var/lib/flatpak/app/org.signal.Signal"],- [_cfg(h, "Signal"), _flat(h, "org.signal.Signal", "config", "Signal")],- [_cfg(h, "Signal", "logs"), _cfg(h, "Signal", "sql")]),- "zoom": (["/usr/bin/zoom", "/opt/zoom", "/var/lib/flatpak/app/us.zoom.Zoom"],- [os.path.join(U, ".zoom"), _flat(h, "us.zoom.Zoom", ".zoom")],- [_cfg(h, "zoomus.conf"), os.path.join(U, ".zoom", "logs")]),- "teams_for_linux": (["/usr/bin/teams-for-linux", "/opt/teams-for-linux"], [_cfg(h, "teams-for-linux")], []),- "element": (["/usr/bin/element-desktop", "/opt/Element"], [_cfg(h, "Element")], []),- "whatsapp": (["/usr/bin/whatsapp-for-linux", "/usr/bin/zapzap"], [_cfg(h, "whatsapp-for-linux"), _flat(h, "com.rtosta.zapzap")], []),- "thunderbird": (["/usr/bin/thunderbird", "/snap/thunderbird"], [os.path.join(U, ".thunderbird"),- _snapu(h, "thunderbird", "common", ".thunderbird")], []),- "evolution": (["/usr/bin/evolution"], [_cfg(h, "evolution"), _data(h, "evolution")], []),- "kmail": (["/usr/bin/kmail"], [_data(h, "kmail2"), _cfg(h, "kmail2rc")], [_cfg(h, "kmail2rc")]),- "mattermost": (["/opt/Mattermost"], [_cfg(h, "Mattermost")], []),- "skype": (["/usr/bin/skypeforlinux", "/snap/skype"], [_cfg(h, "skypeforlinux")], []),- }---@_lp("comms.native_apps", level="L1", family=COMMS, tier="T0", collect="core")-def comms_native_apps(h, facts):- """Native comms/mail apps: installed, launched (profile dir exists), last-used day from profile mtimes."""- rows = {}- for app, (inst, data, act) in _comms_cands(h).items():- r = _app_row(h, inst, data, act)- if r:- rows[app] = r- if not rows:- return {"present": False}- return {"present": True, **rows}---def _discord_dirs(h):- return [d for d in (_cfg(h, "discord"), _cfg(h, "discordcanary"), _cfg(h, "discordptb"),- _flat(h, "com.discordapp.Discord", "config", "discord"), _snapu(h, "discord", "current", ".config", "discord"))- if _isdir(d)]---@_lp("discord.present", level="L1", family=COMMS, tier="T0", collect="core")-def discord_present(h, facts):- """Discord desktop: install dirs, profile dir, version dir, autostart entry."""- inst = _first("/usr/share/discord", "/opt/discord", "/usr/lib/discord", "/var/lib/flatpak/app/com.discordapp.Discord", "/snap/discord")- dirs = _discord_dirs(h)- if not (inst or dirs):- return {"present": False}- vers = sorted(n for d in dirs for n in (_ls(d) or []) if re.fullmatch(r"\d+\.\d+\.\d+", n))- auto = any("discord" in n.lower() for n in (_ls(_cfg(h, "autostart")) or []))- return {"present": True, "installed": bool(inst), "profile_dir": bool(dirs), "version": vers[-1] if vers else None,- "autostart": auto}---@_lp("discord.usage", level="L2", family=COMMS, tier="T1", collect="extended", gate="discord.present", timeout_ms=3000)-def discord_usage(h, facts):- """Signed-in and voice days from logs/renderer_js.log tags; last use from Local Storage mtime."""- dirs = _discord_dirs(h)- if not dirs:- return {"present": False}- days, gw, rtc = set(), set(), set()- size = 0- rx = re.compile(r"^\[(\d{4}-\d\d-\d\d) ([\d:.]+)\] \[\w+\]\s+\[?([A-Za-z_]+)")- for d in dirs:- log = os.path.join(d, "logs", "renderer_js.log")- if not os.path.isfile(log):- continue- size += os.path.getsize(log)- with open(log, encoding="utf-8", errors="replace") as fh:- if os.path.getsize(log) > 16_000_000:- fh.seek(os.path.getsize(log) - 16_000_000)- for line in fh:- m = rx.match(line)- if not m:- continue- dd, _tm, tag = m.groups()- days.add(dd)- if tag == "GatewaySocket":- gw.add(dd)- elif tag.startswith("RTC"):- rtc.add(dd)- ls = _newest_mtime([os.path.join(d, "Local Storage", "leveldb") for d in dirs])- used = bool(gw or rtc) or bool(ls and time.time() - ls < 90 * 86400)- return {"present": used, "log_days": len(days), "first_day": min(days) if days else None,- "last_day": max(days) if days else None, "gateway_days": len(gw), "rtc_days": len(rtc),- "local_storage_last": _day(ls), "log_bytes": size}---def _notes_cands(h):- U = _U(h)- return {- "obsidian": (["/usr/bin/obsidian", "/opt/Obsidian", "/snap/obsidian", "/var/lib/flatpak/app/md.obsidian.Obsidian"],- [_cfg(h, "obsidian"), _flat(h, "md.obsidian.Obsidian", "config", "obsidian")],- [_cfg(h, "obsidian", "obsidian.json")]),- "notion": (["/opt/Notion", "/usr/bin/notion-app"], [_cfg(h, "Notion"), _cfg(h, "notion-app")], []),- "logseq": (["/opt/Logseq", "/var/lib/flatpak/app/com.logseq.Logseq"], [os.path.join(U, ".logseq"), _cfg(h, "Logseq")], []),- "joplin": ([os.path.join(U, ".joplin")], [_cfg(h, "joplin-desktop"), _cfg(h, "Joplin")], []),- "standard_notes": ([], [_cfg(h, "Standard Notes")], []),- "zim": (["/usr/bin/zim"], [_cfg(h, "zim")], []),- "knotes": (["/usr/bin/knotes"], [_data(h, "knotes")], []),- "anytype": ([], [_cfg(h, "anytype")], []),- "trilium": ([], [_cfg(h, "trilium-data"), os.path.join(U, "trilium-data")], []),- }---@_lp("productivity.notes_apps", level="L1", family=COMMS, tier="T0", collect="core")-def notes_apps(h, facts):- """Notes apps installed or launched: Obsidian, Notion, Logseq, Joplin, Zim, KNotes, ..."""- rows = {}- for app, (inst, data, act) in _notes_cands(h).items():- r = _app_row(h, inst, data, act)- if r:- rows[app] = r- return {"present": bool(rows), "apps": sorted(rows), "detail": rows}---@_lp("obsidian.vaults", level="L2", family=COMMS, tier="T1", collect="extended", gate="productivity.notes_apps")-def obsidian_vaults(h, facts):- """Obsidian vault count and note counts (vault names and paths are not emitted)."""- j = _read_json(_cfg(h, "obsidian", "obsidian.json")) or _read_json(_flat(h, "md.obsidian.Obsidian", "config", "obsidian", "obsidian.json"))- vs = (j or {}).get("vaults") or {} if isinstance(j, dict) else {}- if not vs:- return {"present": False}- notes, files, newest = 0, 0, 0-- def on_file(e, s, depth):- nonlocal notes, newest- if e.name.lower().endswith(".md"):- notes += 1- newest = max(newest, s.st_mtime)- for v in list(vs.values())[:10]:- p = v.get("path") if isinstance(v, dict) else None- if p and _isdir(p) and p.startswith(_U(h)):- st = bf._walk(p, max_depth=6, max_entries=30000, budget_s=1.5, on_file=on_file,- skip_dir=lambda n, _p: n in (".obsidian", ".git", ".trash", "node_modules"))- files += st["files"]- return {"present": True, "vaults": len(vs), "open": sum(1 for v in vs.values() if isinstance(v, dict) and v.get("open")),- "notes_md": notes, "files": files, "newest_note": bf._iso(newest)}---_EDR = {"crowdstrike": ["/opt/CrowdStrike"], "sentinelone": ["/opt/sentinelone"], "defender_mdatp": ["/opt/microsoft/mdatp", "/etc/opt/microsoft/mdatp"],- "tanium": ["/opt/Tanium"], "wazuh": ["/var/ossec"], "elastic_agent": ["/opt/Elastic"], "osquery": ["/etc/osquery", "/opt/osquery"],- "sophos": ["/opt/sophos-spl"], "carbonblack": ["/opt/carbonblack"], "qualys": ["/usr/local/qualys"],- "rapid7": ["/opt/rapid7"], "trendmicro": ["/opt/ds_agent"], "jamf_protect": ["/opt/jamf"], "kolide": ["/usr/local/kolide-k2"],- "zscaler": ["/opt/zscaler"], "globalprotect": ["/opt/paloaltonetworks"], "netskope": ["/opt/netskope"]}---@_lp("work.security_agents", level="L1", family=COMMS, tier="T0", collect="core")-def work_security_agents(h, facts):- """EDR/ZTNA/RMM agents by install path (no service queries)."""- hits = sorted(k for k, ps in _EDR.items() if _ex(*ps))- return {"present": True, "agents": hits, "checked": len(_EDR)}---@_lp("work.mdm", level="L1", family=COMMS, tier="T0", collect="core")-def work_mdm(h, facts):- """Device management on Linux: Intune for Linux, Canonical Landscape, Ubuntu Pro attach, Puppet/Chef/Salt agents."""- found = {"intune": _ex("/opt/microsoft/intune", "/usr/bin/intune-portal"),- "landscape": _ex("/etc/landscape/client.conf"), "ubuntu_pro_attached": _ex("/var/lib/ubuntu-advantage/private/machine-token.json"),- "puppet": _ex("/etc/puppetlabs"), "chef": _ex("/etc/chef"), "salt_minion": _ex("/etc/salt/minion"),- "fleetd": _ex("/opt/orbit")}- real = [k for k, v in found.items() if v and k != "ubuntu_pro_attached"]- return {"present": True, "real_enrollments": len(real), "enrollments": real, "ubuntu_pro_attached": found["ubuntu_pro_attached"]}---@_lp("work.join_state", level="L1", family=COMMS, tier="T0", collect="core")-def work_join_state(h, facts):- """Directory join: sssd/realmd/winbind config presence and krb5 default realm set (realm name not emitted)."""- krb = _open_text("/etc/krb5.conf", 200_000) or ""- sssd = _ex("/etc/sssd/sssd.conf")- winbind = "winbind" in (_open_text("/etc/nsswitch.conf", 100_000) or "")- joined = sssd or winbind- return {"present": True, "sssd": sssd, "winbind": winbind, "realmd": _ex("/etc/realmd.conf"),- "krb5_default_realm_set": bool(re.search(r"^\s*default_realm\s*=", krb, re.M)),- "state": "joined" if joined else "workgroup", "domain_joined": joined, "azure_ad_joined": _ex("/opt/microsoft/intune")}---@_lp("work.policies", level="L1", family=COMMS, tier="T0", collect="core")-def work_policies(h, facts):- """Managed browser policy files (Chrome, Chromium, Brave, Edge, Firefox): file counts only."""- dirs = {"chrome": "/etc/opt/chrome/policies/managed", "chromium": "/etc/chromium/policies/managed",- "brave": "/etc/brave/policies/managed", "edge": "/etc/opt/edge/policies/managed"}- apps = {k: len([n for n in (_ls(d) or []) if n.endswith(".json")]) for k, d in dirs.items()}- if _ex("/etc/firefox/policies/policies.json", "/usr/lib/firefox/distribution/policies.json"):- apps["firefox"] = 1- configured = {k: {"values": v, "subkeys": 0} for k, v in apps.items() if v}- return {"present": True, "app_policies": configured, "app_policy_count": len(configured)}---# ================================================================== files--_XDG_DEFAULTS = {"DESKTOP": "Desktop", "DOCUMENTS": "Documents", "DOWNLOAD": "Downloads", "PICTURES": "Pictures",- "VIDEOS": "Videos", "MUSIC": "Music", "TEMPLATES": "Templates", "PUBLICSHARE": "Public"}-_KF_NAME = {"DESKTOP": "Desktop", "DOCUMENTS": "Documents", "DOWNLOAD": "Downloads", "PICTURES": "Pictures",- "VIDEOS": "Videos", "MUSIC": "Music", "TEMPLATES": "Templates", "PUBLICSHARE": "Public"}---def _known_folders_lx(h):- U = _U(h)- out = {v: os.path.join(U, d) for k, d in _XDG_DEFAULTS.items() for v in [_KF_NAME[k]]}- t = _open_text(_cfg(h, "user-dirs.dirs"), 100_000) or ""- for m in re.finditer(r'^XDG_(\w+)_DIR="([^"]*)"', t, re.M):- k, v = m.group(1), m.group(2).replace("$HOME", U)- if k in _KF_NAME:- out[_KF_NAME[k]] = v if v.rstrip("/") != U.rstrip("/") else None- pics = out.get("Pictures") or os.path.join(U, "Pictures")- out["Screenshots"] = os.path.join(pics, "Screenshots")- return out---def _prime_kf(h):- bf._cached(h, "kf", _known_folders_lx)---_STANDARD = {"desktop", "documents", "downloads", "pictures", "videos", "music", "templates", "public", "snap"}---def _home_root(h):- U = _U(h)- cls, loose = collections.Counter(), 0- try:- ents = list(zip(range(5000), os.scandir(U)))- except OSError:- return None- for _, e in ents:- try:- is_dir = e.is_dir(follow_symlinks=False)- except OSError:- continue- if not is_dir:- loose += 0 if e.name.startswith(".") else 1- continue- low = e.name.lower()- cls["operator" if _OP_TOP.match(e.name) else "dot" if low.startswith(".") else- "standard" if low in _STANDARD else "custom"] += 1- return {"dirs_by_class": dict(cls), "loose_visible_files": loose}---@_lp("files.known_folders", level="L1", family=FILES, tier="T0", collect="core")-def files_known_folders(h, facts):- """XDG user dirs (user-dirs.dirs): path under home, exists."""- kf = bf._cached(h, "kf", _known_folders_lx)- U = _U(h)- rows = {n: {"path": ("~" + p[len(U):]) if p and p.startswith(U) else p, "exists": bool(p and _isdir(p)),- "under_profile": bool(p and p.startswith(U)), "under_onedrive": False} for n, p in kf.items()}- return {"present": any(r["exists"] for r in rows.values()), "folders": rows,- "user_dirs_file": os.path.exists(_cfg(h, "user-dirs.dirs"))}---@_lp("files.composition", level="L2", family=FILES, tier="T1", collect="extended", gate="files.known_folders",- timeout_ms=9000)-def files_composition(h, facts):- """Per XDG folder: files, bytes, extension/kind/age histograms (depth <= 6, 100k entries), plus home-root dir- classes (dot/standard/custom/operator). No file names."""- _prime_kf(h)- v = bf.files_composition(h, facts)- if isinstance(v, dict):- v["home_root"] = _home_root(h)- return v-_mirror("files.screenshots", bf.files_screenshots, _prime_kf)---@_lp("files.recent_lnk", level="L2", family=FILES, tier="T1", collect="core", gate="files.known_folders")-def files_recent_lnk(h, facts):- """Recent files: recently-used.xbel + KDE RecentDocuments (counts, ext histogram, date range) and the KDE- activity-manager score cache (row count, top agent apps, range). File names and paths are never emitted."""- now = time.time()- mts, ext, ages = [], collections.Counter(), collections.Counter()- op = 0- xb = _open_text(_data(h, "recently-used.xbel"), 20_000_000)- if xb:- for m in re.finditer(r'<bookmark href="([^"]+)"[^>]*?modified="([^"]+)"', xb):- href, mod = m.group(1), m.group(2)- if _OP_DEEP.search(href):- op += 1- continue- try:- t = dt.datetime.fromisoformat(mod.replace("Z", "+00:00")).timestamp()- except ValueError:- continue- mts.append(t)- ages[_age_bucket(now - t)] += 1- x = os.path.splitext(href.split("?")[0])[1].lower()- ext[x if re.fullmatch(r"\.[a-z0-9]{1,5}", x or "") else "(folder_or_none)"] += 1- rd = _data(h, "RecentDocuments")- for n in (_ls(rd, 5000) or []):- try:- t = os.stat(os.path.join(rd, n)).st_mtime- except OSError:- continue- mts.append(t)- ages[_age_bucket(now - t)] += 1- x = os.path.splitext(n[:-8] if n.endswith(".desktop") else n)[1].lower()- ext[x if re.fullmatch(r"\.[a-z0-9]{1,5}", x or "") else "(folder_or_none)"] += 1- ka = None- db = _data(h, "kactivitymanagerd", "resources", "database")- if os.path.exists(db):- rows = h.sqlite(db, "select initiatingAgent, count(*), min(firstUpdate), max(lastUpdate) from ResourceScoreCache group by 1")- if rows:- agents = collections.Counter({(a or "?"): n for a, n, _f, _l in rows})- ka = {"rows": sum(agents.values()), "agents": len(agents), "top_agents": dict(agents.most_common(10)),- "first": bf._iso(min((r[2] or 0) for r in rows)), "last": bf._iso(max((r[3] or 0) for r in rows))}- if not mts and not ka:- return {"present": False}- folders = ext.get("(folder_or_none)", 0)- return {"present": True, "count": len(mts), "operator_filtered": op, "oldest": bf._iso(min(mts)) if mts else None,- "newest": bf._iso(max(mts)) if mts else None, "folder_or_none": folders, "files": len(mts) - folders,- "target_ext_top": dict(ext.most_common(10)), "age_mtime": {k: ages.get(k, 0) for k in bf.AGE_KEYS},- "active_days_30d": len({time.strftime("%Y-%m-%d", time.localtime(t)) for t in mts if now - t < 30 * 86400}),- "kactivity": ka}---@_lp("files.clutter", level="L2", family=FILES, tier="T1", collect="extended", gate="files.known_folders", timeout_ms=6000)-def files_clutter(h, facts):- """Trash, ~/.cache and thumbnail sizes, this user's files in TMPDIR, Desktop item count (bounded walks)."""- _prime_kf(h)- out = {"present": True}- tr = _data(h, "Trash")- if _isdir(tr):- st = bf._walk(os.path.join(tr, "files"), max_depth=6, max_entries=100000, budget_s=1.5)- out["recycle_bin"] = {"items": len(_ls(os.path.join(tr, "info"), 100000) or []), "files": st["files"],- "bytes": st["bytes"], "truncated": st["truncated"]}- c = _cachedir(h)- if _isdir(c):- st = bf._walk(c, max_depth=6, max_entries=150000, budget_s=1.5)- out["cache_bytes"], out["cache_files"], out["cache_truncated"] = st["bytes"], st["files"], st["truncated"]- th = bf._walk(_cachedir(h, "thumbnails"), max_depth=3, max_entries=100000, budget_s=0.8)- out["thumbcache_bytes"] = th["bytes"]- me, n, b = os.getuid(), [0], [0]-- def mine(e, s, depth):- if s.st_uid == me:- n[0] += 1- b[0] += s.st_size- tmp = tempfile_dir()- st = bf._walk(tmp, max_depth=3, max_entries=50000, budget_s=1.0, on_file=mine,- skip_dir=lambda nm, p: nm == "userscan" or bool(_OP_DEEP.search(p)))- out["temp_files"], out["temp_bytes"], out["temp_truncated"] = n[0], b[0], st["truncated"]- desk = bf._kf(h, "Desktop")- names = [x for x in h.list_dir(desk, 5000) if not x.startswith(".")]- out["desktop_items"] = len(names)- out["desktop_shortcuts"] = sum(1 for x in names if x.endswith(".desktop"))- out["baloo_index_bytes"] = h.meta(_data(h, "baloo", "index")).get("bytes")- return out---@_lp("files.download_sources", level="L2", family=FILES, tier="T1", collect="deep", gate="files.known_folders",- timeout_ms=6000)-def files_download_sources(h, facts):- """user.xdg.origin.url xattrs in Downloads (depth <= 2; written by Chrome/Firefox): source-site category counts- (no hosts, no file names). The Linux counterpart of Zone.Identifier."""- _prime_kf(h)- root = bf._kf(h, "Downloads")- if not _isdir(root):- return {"present": False}- cats, ext_cat = collections.Counter(), collections.Counter()- n = with_x = 0- deadline = time.perf_counter() + 4.0- stack, trunc = [(root, 0)], None- while stack:- d, depth = stack.pop()- try:- entries = list(os.scandir(d))- except OSError:- continue- for e in entries:- if e.is_dir(follow_symlinks=False):- if depth + 1 < 2 and not _OP_DEEP.search(e.path):- stack.append((e.path, depth + 1))- continue- n += 1- if n > 5000 or time.perf_counter() > deadline:- trunc = "cap"- stack.clear()- break- try:- url = os.getxattr(e.path, "user.xdg.origin.url", follow_symlinks=False).decode("utf-8", "replace")- except (OSError, AttributeError):- continue- with_x += 1- host, _ = bf._host_of(url)- c = bf._categorize(bf._reg_domain(host)) if host else "other"- c = "sensitive" if c in bf.SENSITIVE_CATS else c- cats[c] += 1- ext_cat[f"{c}:{os.path.splitext(e.name)[1].lower() or '(none)'}"] += 1- return {"present": n > 0, "files_scanned": n, "depth": 2, "truncated": trunc, "with_origin_xattr": with_x,- "source_categories": dict(cats.most_common()), "category_ext_top": dict(ext_cat.most_common(10))}---@_lp("files.profile_size_walk", level="L2", family=FILES, tier="T2", collect="deep", gate="files.known_folders",- timeout_ms=30000)-def files_profile_size_walk(h, facts):- """Size of each top-level home dir (depth <= 10, 300k entries/dir, 25 s total); operator dirs excluded."""- U = _U(h)- deadline = time.perf_counter() + 25.0- rows, loose = [], 0- try:- entries = list(os.scandir(U))- except OSError:- return {"present": False}- for e in entries:- try:- if not e.is_dir(follow_symlinks=False):- loose += 1- continue- except OSError:- continue- low = e.name.lower()- cls = ("operator" if _OP_TOP.match(e.name) else "dot" if low.startswith(".") else- "standard" if low in _STANDARD else "custom")- if cls == "operator":- rows.append({"name": e.name, "class": cls, "bytes": 0, "skipped": "operator"})- continue- remain = deadline - time.perf_counter()- if remain <= 0:- rows.append({"name": e.name, "class": cls, "bytes": 0, "skipped": "budget"})- continue- st = bf._walk(e.path, max_depth=10, max_entries=300000, budget_s=min(4.0, remain))- rows.append({"name": e.name, "class": cls, "bytes": st["bytes"], "files": st["files"], "truncated": st["truncated"]})- rows.sort(key=lambda r: -r["bytes"])- shown = 0- for r in rows:- if r["class"] == "custom":- shown += 1- if shown > 5:- r["name"] = f"custom#{shown}"- cls = collections.Counter(r["class"] for r in rows)- return {"present": True, "top_dirs": [r for r in rows if r["class"] != "operator"][:12], "class_counts": dict(cls),- "custom_root_dirs": cls.get("custom", 0), "operator_dirs_excluded": cls.get("operator", 0),- "custom_bytes": sum(r["bytes"] for r in rows if r["class"] == "custom"),- "total_bytes": sum(r["bytes"] for r in rows), "loose_root_files": loose,- "truncated_dirs": sum(1 for r in rows if r.get("truncated") or r.get("skipped") == "budget")}---@_lp("sync.other", level="L1", family=FILES, tier="T0", collect="core")-def sync_other(h, facts):- """Sync clients: Dropbox, Nextcloud, ownCloud, Syncthing, MEGA, pCloud, Insync, onedrive (abraunegg), rclone, GOA."""- U = _U(h)- cands = {"dropbox": [os.path.join(U, ".dropbox")], "nextcloud": [_cfg(h, "Nextcloud")], "owncloud": [_cfg(h, "ownCloud")],- "syncthing": [_state(h, "syncthing"), _cfg(h, "syncthing")], "mega": [_data(h, "data", "Mega Limited")],- "pcloud": [os.path.join(U, ".pcloud")], "insync": [_data(h, "Insync"), _cfg(h, "Insync")],- "onedrive": [_cfg(h, "onedrive")], "rclone": [_cfg(h, "rclone", "rclone.conf")],- "gnome_online_accounts": [_cfg(h, "goa-1.0", "accounts.conf")], "kde_accounts": [_cfg(h, "libaccounts-glib", "accounts.db")],- "google_drive_ocamlfuse": [os.path.join(U, ".gdfuse")], "proton_drive": [_cfg(h, "Proton Drive")]}- found = [k for k, ps in cands.items() if _ex(*ps)]- if "kde_accounts" in found:- rows = h.sqlite(_cfg(h, "libaccounts-glib", "accounts.db"), "select count(*) from Accounts")- if not rows or not rows[0][0]:- found.remove("kde_accounts")- return {"present": bool(found), "clients": found}---# ================================================================== gaming--def _steam_root(h):- for p in (_data(h, "Steam"), os.path.join(_U(h), ".steam", "steam"), os.path.join(_U(h), ".steam", "debian-installation"),- _flat(h, "com.valvesoftware.Steam", ".local", "share", "Steam"), _snapu(h, "steam", "common", ".local", "share", "Steam")):- if _isdir(os.path.join(p, "steamapps")) or os.path.isfile(os.path.join(p, "steam.sh")):- return os.path.realpath(p)- return None---def _steam_lx(h):- def load():- sp = _steam_root(h)- if not sp:- return None- libs = []- txt = ug._read(os.path.join(sp, "steamapps", "libraryfolders.vdf"))- if txt:- for _k, v in (ug._ci(ug._vdf(txt), "libraryfolders") or {}).items():- if isinstance(v, dict) and v.get("path"):- libs.append(os.path.normpath(v["path"]))- libs = libs or [sp]- installed = []- for lib in libs[:20]:- sa = os.path.join(lib, "steamapps")- for n in h.list_dir(sa, 2000):- if n.startswith("appmanifest_") and n.endswith(".acf"):- st = ug._ci(ug._vdf(ug._read(os.path.join(sa, n)) or ""), "AppState") or {}- installed.append({"appid": int(st.get("appid", 0) or 0), "name": st.get("name"),- "size_gb": round(int(st.get("SizeOnDisk", 0) or 0) / 1e9, 1),- "drive": "home" if lib.startswith(_U(h)) else "other",- "last_played": int(st.get("LastPlayed", 0) or 0)})- ud = os.path.join(sp, "userdata")- uids = [u for u in h.list_dir(ud, 50) if u.isdigit()]- users = {}- for uid in uids:- apps = {}- t = ug._read(os.path.join(ud, uid, "config", "localconfig.vdf"))- if t:- node = ug._ci(ug._vdf(t), "UserLocalConfigStore", "Software", "Valve", "Steam", "apps") or {}- for aid, v in node.items():- if isinstance(v, dict) and aid.isdigit() and ("Playtime" in v or "LastPlayed" in v):- apps[int(aid)] = {"min": int(v.get("Playtime", 0) or 0), "min2wk": int(v.get("Playtime2wks", 0) or 0),- "last": int(v.get("LastPlayed", 0) or 0)}- users[uid] = apps- return {"path": sp, "libs": libs, "installed": installed, "uids": uids, "users": users,- "appinfo_path": os.path.join(sp, "appcache", "appinfo.vdf")}- return load---def _prime_steam(h):- ug._cached(("steam", h.l0.get("run_id")), _steam_lx(h))---@_lp("steam.present", level="L1", family=GAMING, tier="T0", collect="core")-def steam_present(h, facts):- """Steam client data dir (native ~/.local/share/Steam, ~/.steam, flatpak, snap); gates the Steam subtree."""- sp = _steam_root(h)- if not sp:- return None- via = "flatpak" if "/.var/app/" in sp else "snap" if "/snap/" in sp else "native"- return {"present": True, "via": via, "proton_prefixes": len(_ls(os.path.join(sp, "steamapps", "compatdata"), 5000) or [])}---for _id, _fn in (("steam.installed", ug.steam_installed), ("steam.playtime", ug.steam_playtime),- ("steam.appinfo_genres", ug.steam_appinfo_genres), ("steam.local_sessions", ug.steam_local_sessions),- ("steam.non_steam_shortcuts", ug.steam_non_steam_shortcuts), ("steam.screenshots", ug.steam_screenshots),- ("steam.login_users", ug.steam_login_users), ("steam.remote_clients", ug.steam_remote_clients)):- _mirror(_id, _fn, _prime_steam)---def _legendary_dir(h):- return _first(_cfg(h, "heroic", "legendaryConfig", "legendary"), _cfg(h, "legendary"),- _flat(h, "com.heroicgameslauncher.hgl", "config", "heroic", "legendaryConfig", "legendary"))---@_lp("epic.present", level="L1", family=GAMING, tier="T0", collect="core")-def epic_present(h, facts):- """Epic Games library via Heroic/legendary config (the Linux route to Epic)."""- d = _legendary_dir(h)- if not d:- return None- return {"present": True, "via": "heroic" if "heroic" in d else "legendary", "mtime": _mtime(d)}---@_lp("epic.installs", level="L2", family=GAMING, tier="T0", collect="core", gate="epic.present")-def epic_installs(h, facts):- """Epic installs from legendary installed.json: titles and GB."""- d = _legendary_dir(h)- j = _read_json(os.path.join(d, "installed.json")) if d else None- if not isinstance(j, dict) or not j:- return {"present": False}- rows = [[v.get("title") or k, round((v.get("install_size") or 0) / 1e9, 1)] for k, v in j.items() if isinstance(v, dict)]- rows.sort(key=lambda r: -r[1])- return {"present": True, "count": len(rows), "total_gb": round(sum(r[1] for r in rows), 1), "manifests": rows[:20]}---@_lp("launchers.other", level="L1", family=GAMING, tier="T0", collect="core")-def launchers_other(h, facts):- """Linux game launchers: Heroic, Lutris, Bottles, itch, Minigalaxy, Prism/Minecraft, Wine prefix, ProtonUp-Qt."""- U = _U(h)- cands = {"heroic": [_cfg(h, "heroic"), _flat(h, "com.heroicgameslauncher.hgl")],- "lutris": [_data(h, "lutris"), _cfg(h, "lutris"), _flat(h, "net.lutris.Lutris")],- "bottles": [_data(h, "bottles"), _flat(h, "com.usebottles.bottles")], "itch": [_cfg(h, "itch")],- "minigalaxy": [_cfg(h, "minigalaxy")], "gog_via_heroic": [_cfg(h, "heroic", "gog_store")],- "prismlauncher": [_data(h, "PrismLauncher"), _flat(h, "org.prismlauncher.PrismLauncher")],- "minecraft": [os.path.join(U, ".minecraft")], "wine": [os.path.join(U, ".wine")],- "protonup_qt": [_flat(h, "net.davidotek.pupgui2"), _cfg(h, "pupgui")], "gamemode": ["/usr/bin/gamemoderun"],- "mangohud": [_cfg(h, "MangoHud")]}- hits = sorted(k for k, ps in cands.items() if _ex(*ps))- return {"present": True, "launchers": hits} if hits else None---@_lp("emulators", level="L1", family=GAMING, tier="T0", collect="core")-def emulators(h, facts):- """Emulator config dirs (RetroArch, Ryujinx, Dolphin, PCSX2, RPCS3, Cemu, DuckStation, PPSSPP, ...), native or flatpak."""- c = {"RetroArch": [_cfg(h, "retroarch"), _flat(h, "org.libretro.RetroArch")], "Ryujinx": [_cfg(h, "Ryujinx"), _flat(h, "org.ryujinx.Ryujinx")],- "yuzu/suyu": [_data(h, "yuzu"), _data(h, "suyu")], "Dolphin": [_data(h, "dolphin-emu"), _flat(h, "org.DolphinEmu.dolphin-emu")],- "PCSX2": [_cfg(h, "PCSX2"), _flat(h, "net.pcsx2.PCSX2")], "RPCS3": [_cfg(h, "rpcs3"), _flat(h, "net.rpcs3.RPCS3")],- "Cemu": [_data(h, "Cemu"), _flat(h, "info.cemu.Cemu")], "DuckStation": [_data(h, "duckstation"), _flat(h, "org.duckstation.DuckStation")],- "PPSSPP": [_cfg(h, "ppsspp"), _flat(h, "org.ppsspp.PPSSPP")], "xemu": [_data(h, "xemu")], "melonDS": [_cfg(h, "melonDS")]}- hits = sorted(k for k, ps in c.items() if _ex(*ps))- return {"present": True, "found": hits} if hits else None---# ================================================================== media--@_lp("media.libraries", level="L1", family=MEDIA, tier="T1", collect="core")-def media_libraries(h, facts):- """XDG Music/Videos/Pictures file counts by type and size (bounded walk), plus Screenshots count."""- kf = bf._cached(h, "kf", _known_folders_lx)- out = {}- for short in ("Music", "Videos", "Pictures"):- p = kf.get(short) or os.path.join(_U(h), short)- s = ug._walk_media(p)- s["gb"] = round(s.pop("bytes") / 1e9, 2)- s["onedrive"] = False- out[short] = s- out["screenshots"] = max(h.count_dir(kf.get("Screenshots") or "", 20000), 0)- return {"present": True, **out}---@_lp("media.obs", level="L1", family=MEDIA, tier="T0", collect="core")-def media_obs(h, facts):- """OBS Studio: package/flatpak install and whether a config dir exists (launched at least once)."""- inst = [k for k, p in (("deb", "/usr/bin/obs"), ("flatpak", "/var/lib/flatpak/app/com.obsproject.Studio"),- ("snap", "/snap/obs-studio")) if os.path.exists(p)]- cfgs = [k for k, p in (("native", _cfg(h, "obs-studio")), ("flatpak", _flat(h, "com.obsproject.Studio", "config", "obs-studio")))- if _isdir(p)]- if not (inst or cfgs):- return None- return {"present": True, "obs_installs": inst, "obs_configs": cfgs, "config_dir": bool(cfgs),- "obs_config_in_agent_container": 0, "streamlabs": False, "streamlabs_config": False}---@_lp("media.players", level="L1", family=MEDIA, tier="T0", collect="core")-def media_players(h, facts):- """Music/video players and streaming apps (Spotify, Elisa, mpv, Strawberry, Kodi, Haruna, ...), native/snap/flatpak."""- U = _U(h)- c = {"spotify": [_cfg(h, "spotify"), "/snap/spotify", _flat(h, "com.spotify.Client"), "/usr/share/spotify"],- "elisa": [_cfg(h, "elisarc"), "/usr/bin/elisa"], "mpv": [_cfg(h, "mpv"), "/usr/bin/mpv"],- "strawberry": [_cfg(h, "strawberry")], "clementine": [_cfg(h, "Clementine")], "rhythmbox": [_data(h, "rhythmbox")],- "audacious": [_cfg(h, "audacious")], "kodi": [os.path.join(U, ".kodi")], "plex": [_data(h, "plex"), "/snap/plex-desktop"],- "jellyfin": [_data(h, "jellyfinmediaplayer"), _flat(h, "com.github.iwalton3.jellyfin-media-player")],- "haruna": [_cfg(h, "haruna"), "/usr/bin/haruna"], "celluloid": [_cfg(h, "celluloid")], "tidal": [_cfg(h, "tidal-hifi")],- "youtube_music": [_cfg(h, "YouTube Music")], "smplayer": [_cfg(h, "smplayer")]}- hits = sorted(k for k, ps in c.items() if _ex(*ps))- return {"present": True, "players": hits} if hits else None---def _vlc_cfg(h):- return _first(_cfg(h, "vlc"), _snapu(h, "vlc", "common", ".config", "vlc"), _flat(h, "org.videolan.VLC", "config", "vlc"))---@_lp("media.vlc", level="L1", family=MEDIA, tier="T0", collect="core")-def media_vlc(h, facts):- """VLC installed (deb/snap/flatpak) and whether a user config exists."""- inst = _ex("/usr/bin/vlc", "/snap/vlc", "/var/lib/flatpak/app/org.videolan.VLC")- cfg = _vlc_cfg(h)- return {"present": True, "installed": inst, "user_config": bool(cfg)} if (inst or cfg) else None---@_lp("media.vlc_recents", level="L2", family=MEDIA, tier="T2", collect="extended", gate="media.vlc")-def media_vlc_recents(h, facts):- """VLC recent-media count, local vs stream split and extension histogram; the MRL list itself is not emitted."""- d = _vlc_cfg(h)- qi = os.path.join(d, "vlc-qt-interface.conf") if d else None- t = ug._read(qi, 2_000_000) if qi else None- if not t:- return {"present": False}- m = re.search(r"^\[RecentsMRL\][^\[]*?^list=(.*)$", t, re.M | re.S)- items = [x.strip().strip('"') for x in m.group(1).split(",") if x.strip()] if m else []- kinds = collections.Counter("local" if x.startswith("file:") else "stream" for x in items)- exts = collections.Counter()- for x in items:- if x.startswith("file:"):- m2 = re.search(r"\.([A-Za-z0-9]{1,5})$", x.split("?")[0])- exts["." + m2.group(1).lower() if m2 else ""] += 1- return {"present": bool(items), "count": len(items), "kinds": dict(kinds), "ext": dict(exts), "ini_mtime": _mtime(qi)}+_mirror("ollama.models", ad_agents.ollama_models)diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_apps_browser.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_apps_browser.pynew file mode 100644index 00000000000..ea85cbcfb8a--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_apps_browser.py@@ -0,0 +1,428 @@+"""Linux user-level probes: browser, comms_work.++Registration only at import time. Shared helpers and registration wrappers live in linux_apps.+"""+from __future__ import annotations++import glob+import os+import re+import time++from . import browser_files as bf+from . import browser_files_comms as bf_comms+from .linux_apps import (BROWSER, COMMS, _U, _cfg, _data, _day, _desktop, _ex, _first, _flat,+ _is_op, _isdir, _lp, _ls, _mirror, _newest_mtime, _open_text, _read_json, _snapu)++# ================================================================== browser++_CHROMIUM = [("chrome", "google-chrome"), ("chrome_beta", "google-chrome-beta"), ("chrome_dev", "google-chrome-unstable"),+ ("chromium", "chromium"), ("brave", "BraveSoftware/Brave-Browser"), ("brave_beta", "BraveSoftware/Brave-Browser-Beta"),+ ("brave_nightly", "BraveSoftware/Brave-Browser-Nightly"), ("edge", "microsoft-edge"), ("edge_beta", "microsoft-edge-beta"),+ ("edge_dev", "microsoft-edge-dev"), ("vivaldi", "vivaldi"), ("opera", "opera"), ("thorium", "thorium"),+ ("yandex", "yandex-browser"), ("helium", "net.imput.helium")]+_CHROMIUM_EXTRA = [("chromium", "snap", ("chromium", "common", "chromium")),+ ("brave", "snap", ("brave", "current", ".config", "BraveSoftware", "Brave-Browser")),+ ("chrome", "flatpak", ("com.google.Chrome", "config", "google-chrome")),+ ("brave", "flatpak", ("com.brave.Browser", "config", "BraveSoftware", "Brave-Browser")),+ ("chromium", "flatpak", ("org.chromium.Chromium", "config", "chromium")),+ ("edge", "flatpak", ("com.microsoft.Edge", "config", "microsoft-edge")),+ ("vivaldi", "flatpak", ("com.vivaldi.Vivaldi", "config", "vivaldi"))]+++def _gecko_roots(h):+ U = _U(h)+ return [("firefox", os.path.join(U, ".mozilla", "firefox")), ("firefox", _snapu(h, "firefox", "common", ".mozilla", "firefox")),+ ("firefox", _flat(h, "org.mozilla.firefox", ".mozilla", "firefox")), ("librewolf", os.path.join(U, ".librewolf")),+ ("librewolf", _flat(h, "io.gitlab.librewolf-community", ".librewolf")), ("zen", os.path.join(U, ".zen")),+ ("floorp", os.path.join(U, ".floorp")), ("waterfox", os.path.join(U, ".waterfox")),+ ("thunderbird_gecko", os.path.join(U, ".thunderbird")), ("tor", os.path.join(U, ".local", "share", "torbrowser"))]+++def _catalog_lx(h):+ found_c, found_g = {}, {}+ n = 0+ for bid, rel in _CHROMIUM:+ n += 1+ p = _cfg(h, *rel.split("/"))+ if _isdir(p) and os.path.exists(os.path.join(p, "Local State")) and bid not in found_c:+ found_c[bid] = p+ for bid, kind, parts in _CHROMIUM_EXTRA:+ n += 1+ p = _snapu(h, *parts) if kind == "snap" else _flat(h, *parts)+ key = bid if bid not in found_c else f"{bid}_{kind}"+ if _isdir(p) and os.path.exists(os.path.join(p, "Local State")):+ found_c[key] = p+ for bid, root in _gecko_roots(h):+ n += 1+ if bid == "thunderbird_gecko":+ continue+ ok = _isdir(root) if bid == "tor" else os.path.isfile(os.path.join(root, "profiles.ini"))+ if ok:+ found_g[bid if bid not in found_g else f"{bid}_{len(found_g)}"] = root+ return {"chromium": found_c, "gecko": found_g, "checked": n}+++def _prime_browser(h):+ bf._cached(h, "catalog", _catalog_lx)+++@_lp("browser.catalog", level="L1", family=BROWSER, tier="T0", collect="core")+def browser_catalog(h, facts):+ """Chromium (native/snap/flatpak under ~/.config, ~/snap, ~/.var) and Gecko (~/.mozilla...) user-data roots."""+ c = bf._cached(h, "catalog", _catalog_lx)+ return {"present": bool(c["chromium"] or c["gecko"]), "chromium": sorted(c["chromium"]), "gecko": sorted(c["gecko"]),+ "checked": c["checked"]}+++@_lp("browser.brave.present", level="L1", family=BROWSER, tier="T0", collect="core")+def brave_present(h, facts):+ """Brave user-data dir exists (native, snap or flatpak)."""+ for p in (_cfg(h, "BraveSoftware", "Brave-Browser"), _snapu(h, "brave", "current", ".config", "BraveSoftware", "Brave-Browser"),+ _flat(h, "com.brave.Browser", "config", "BraveSoftware", "Brave-Browser")):+ if _isdir(p):+ m = h.meta(os.path.join(p, "Local State"))+ return {"present": True, "local_state_mtime": bf._iso(m.get("mtime"))}+ return {"present": False}+++@_lp("browser.edge.present", level="L1", family=BROWSER, tier="T0", collect="core")+def edge_present(h, facts):+ """Microsoft Edge user-data dir exists (native or flatpak); on Linux it is never preinstalled."""+ for p in (_cfg(h, "microsoft-edge"), _flat(h, "com.microsoft.Edge", "config", "microsoft-edge")):+ if _isdir(p):+ return {"present": True, "local_state_mtime": bf._iso(h.meta(os.path.join(p, "Local State")).get("mtime"))}+ return {"present": False}+++def _mimeapps(h):+ """Merged [Default Applications] from the XDG mimeapps.list chain (user files first). {mime: (desktop_id, scope)}."""+ files = [("user", _cfg(h, "kde-mimeapps.list")), ("user", _cfg(h, "mimeapps.list")),+ ("user", _data(h, "applications", "mimeapps.list")), ("system", "/etc/xdg/kde-mimeapps.list"),+ ("system", "/etc/xdg/mimeapps.list"), ("system", "/usr/share/applications/kde-mimeapps.list"),+ ("system", "/usr/share/applications/mimeapps.list"), ("system", "/usr/share/applications/defaults.list")]+ out = {}+ for scope, p in files:+ t = _open_text(p, 2_000_000)+ if not t:+ continue+ sec = None+ for line in t.splitlines():+ line = line.strip()+ if line.startswith("["):+ sec = line+ continue+ if sec in ("[Default Applications]",) and "=" in line:+ k, v = line.split("=", 1)+ first = next((x for x in v.split(";") if x), None)+ if first and k.strip() not in out:+ out[k.strip()] = (first, scope)+ return out+++_BROWSER_IDS = [("brave", r"brave"), ("chrome", r"google-chrome|com\.google\.chrome"), ("chromium", r"chromium"),+ ("firefox", r"firefox"), ("edge", r"microsoft-edge"), ("vivaldi", r"vivaldi"), ("opera", r"opera"),+ ("librewolf", r"librewolf"), ("zen", r"zen"), ("floorp", r"floorp"), ("falkon", r"falkon"),+ ("konqueror", r"konqueror"), ("epiphany", r"epiphany")]+++def _browser_of(desktop_id):+ d = (desktop_id or "").lower()+ return next((b for b, rx in _BROWSER_IDS if re.search(rx, d)), desktop_id)+++@_lp("browser.default", level="L1", family=BROWSER, tier="T0", collect="core")+def browser_default(h, facts):+ """Default browser from mimeapps.list (x-scheme-handler/https, http, text/html) or KDE BrowserApplication."""+ m = _mimeapps(h)+ got = {k: m[k] for k in ("x-scheme-handler/https", "x-scheme-handler/http", "text/html", "application/pdf") if k in m}+ kde = None+ t = _open_text(_cfg(h, "kdeglobals"), 2_000_000) or ""+ km = re.search(r"^BrowserApplication=(.+)$", t, re.M)+ if km:+ kde = km.group(1).strip().lstrip("!")+ pid = (got.get("x-scheme-handler/https") or got.get("x-scheme-handler/http") or got.get("text/html") or (None,))[0] or kde+ if not pid:+ return {"present": False}+ src = got.get("x-scheme-handler/https") or got.get("x-scheme-handler/http") or got.get("text/html")+ return {"present": True, "browser": _browser_of(pid), "prog_id": pid,+ "set_by_user": bool(src and src[1] == "user") or bool(kde),+ "handlers": {k: _browser_of(v[0]) for k, v in got.items()}, "kde_browser_application": _browser_of(kde) if kde else None}+++@_lp("defaults.mailto_pdf_media", level="L1", family=BROWSER, tier="T0", collect="core")+def defaults_mailto_pdf_media(h, facts):+ """Default handlers (desktop ids) for mailto, PDF, video, audio, images, text."""+ m = _mimeapps(h)+ keys = {"mailto": "x-scheme-handler/mailto", ".pdf": "application/pdf", ".mp4": "video/mp4", ".mkv": "video/x-matroska",+ ".mp3": "audio/mpeg", ".jpg": "image/jpeg", ".png": "image/png", ".txt": "text/plain", ".md": "text/markdown",+ ".py": "text/x-python"}+ got = {k: m[v][0] for k, v in keys.items() if v in m}+ return {"present": bool(got), "handlers": got}+++@_lp("browser.registered", level="L2", family=BROWSER, tier="T0", collect="core", gate="apps.dpkg")+def browser_registered(h, facts):+ """Browsers with a launchable .desktop entry that handles x-scheme-handler/http(s)."""+ names = sorted({_browser_of(e["id"]) for e in _desktop(h) if "x-scheme-handler/http" in e["mime"]+ and ("WebBrowser" in e["categories"] or "Network" in e["categories"])})+ return {"present": bool(names), "browsers": names}+++_T3_CHROMIUM = ("Cookies", "Network/Cookies", "Login Data", "Login Data For Account", "Web Data", "Account Web Data")+_T3_GECKO = ("cookies.sqlite", "logins.json", "key4.db", "formhistory.sqlite")+++@_lp("browser.t3_presence", level="L1", family=BROWSER, tier="T3", collect="core")+def browser_t3_presence(h, facts):+ """Credential/cookie stores per profile: stat only (size), never opened."""+ _prime_browser(h)+ rows = {}+ for bid, ud, pdir, _i in bf._profiles(h):+ base = os.path.join(ud, pdir) if pdir else ud+ sizes = {f.replace("Network/", ""): m["bytes"] for f in _T3_CHROMIUM+ for m in [h.meta(os.path.join(base, f))] if m.get("present")}+ if sizes:+ rows[bf._pkey(bid, pdir)] = sizes+ for bid, root in bf._cached(h, "catalog", _catalog_lx)["gecko"].items():+ for pd in glob.glob(os.path.join(root, "*"))[:30]:+ sizes = {f: m["bytes"] for f in _T3_GECKO for m in [h.meta(os.path.join(pd, f))] if m.get("present")}+ if sizes:+ rows[f"{bid}:{len(rows)}"] = sizes+ return {"present": bool(rows), "profiles": rows}+++@_lp("browser.generic_sweep", level="L1", family=BROWSER, tier="T0", collect="extended")+def browser_generic_sweep(h, facts):+ """Chromium-style user-data dirs under ~/.config not in the catalog (Local State + Default)."""+ known = {os.path.realpath(p) for p in bf._cached(h, "catalog", _catalog_lx)["chromium"].values()}+ unknown = []+ for pat in (_cfg(h, "*", "Local State"), _cfg(h, "*", "*", "Local State")):+ for p in glob.glob(pat)[:200]:+ d = os.path.dirname(p)+ if os.path.realpath(d) not in known and _isdir(os.path.join(d, "Default")) and not _is_op(h, d):+ unknown.append(os.path.relpath(d, _U(h)))+ return {"present": True, "unknown_forks": len(unknown), "roots": unknown[:10]}+++for _id, _fn in (("browser.local_state", bf.browser_local_state), ("browser.tab_stats", bf.browser_tab_stats),+ ("browser.profile_prefs", bf.browser_profile_prefs), ("browser.extensions", bf.browser_extensions),+ ("browser.bookmarks", bf.browser_bookmarks), ("browser.history.copy", bf.history_copy),+ ("browser.history.stats", bf.history_stats), ("browser.history.hour_weekday", bf.history_hour_weekday),+ ("browser.history.top_domains", bf.history_top_domains),+ ("browser.history.top_domains_named", bf.history_top_domains_named),+ ("browser.history.localhost", bf.history_localhost), ("browser.history.downloads", bf.history_downloads),+ ("browser.history.search_terms", bf.history_search_terms),+ ("browser.history.github_repos", bf.history_github_repos), ("browser.firefox.history", bf.firefox_history),+ ("l3.browser_category_share", bf.l3_browser_category_share), ("l3.primary_browser", bf.l3_primary_browser),+ ("l3.browser_rhythm", bf.l3_browser_rhythm), ("l3.browser_persona_hints", bf.l3_browser_persona_hints),+ ("browser.history.workspaces", bf_comms.history_workspaces), ("browser.history.work_hosts", bf_comms.history_work_hosts)):+ _mirror(_id, _fn, _prime_browser)+++# ================================================================== comms_work++def _app_row(h, installs, data_dirs, activity):+ """installed/launched/last-used for one app. activity = files whose mtime means the app ran."""+ inst = [p for p in installs if os.path.exists(p)]+ data = [p for p in data_dirs if _isdir(p)]+ if not (inst or data):+ return None+ last = _newest_mtime([a for a in activity if a] + data)+ return {"installed": bool(inst), "launched": bool(data), "last_used": _day(last),+ "recent_use": bool(last and time.time() - last < 30 * 86400)}+++def _comms_cands(h):+ U = _U(h)+ return {+ "slack": (["/usr/bin/slack", "/usr/lib/slack", "/snap/slack", "/var/lib/flatpak/app/com.slack.Slack"],+ [_cfg(h, "Slack"), _snapu(h, "slack", "current", ".config", "Slack"), _flat(h, "com.slack.Slack", "config", "Slack")],+ [_cfg(h, "Slack", "logs"), _cfg(h, "Slack", "Local Storage")]),+ "telegram": (["/usr/bin/telegram-desktop", "/opt/telegram", "/snap/telegram-desktop", "/var/lib/flatpak/app/org.telegram.desktop"],+ [_data(h, "TelegramDesktop"), _flat(h, "org.telegram.desktop", "data", "TelegramDesktop"),+ _snapu(h, "telegram-desktop", "current", ".local", "share", "TelegramDesktop")],+ [_data(h, "TelegramDesktop", "tdata", "settingss")]),+ "signal": (["/usr/bin/signal-desktop", "/opt/Signal", "/var/lib/flatpak/app/org.signal.Signal"],+ [_cfg(h, "Signal"), _flat(h, "org.signal.Signal", "config", "Signal")],+ [_cfg(h, "Signal", "logs"), _cfg(h, "Signal", "sql")]),+ "zoom": (["/usr/bin/zoom", "/opt/zoom", "/var/lib/flatpak/app/us.zoom.Zoom"],+ [os.path.join(U, ".zoom"), _flat(h, "us.zoom.Zoom", ".zoom")],+ [_cfg(h, "zoomus.conf"), os.path.join(U, ".zoom", "logs")]),+ "teams_for_linux": (["/usr/bin/teams-for-linux", "/opt/teams-for-linux"], [_cfg(h, "teams-for-linux")], []),+ "element": (["/usr/bin/element-desktop", "/opt/Element"], [_cfg(h, "Element")], []),+ "whatsapp": (["/usr/bin/whatsapp-for-linux", "/usr/bin/zapzap"], [_cfg(h, "whatsapp-for-linux"), _flat(h, "com.rtosta.zapzap")], []),+ "thunderbird": (["/usr/bin/thunderbird", "/snap/thunderbird"], [os.path.join(U, ".thunderbird"),+ _snapu(h, "thunderbird", "common", ".thunderbird")], []),+ "evolution": (["/usr/bin/evolution"], [_cfg(h, "evolution"), _data(h, "evolution")], []),+ "kmail": (["/usr/bin/kmail"], [_data(h, "kmail2"), _cfg(h, "kmail2rc")], [_cfg(h, "kmail2rc")]),+ "mattermost": (["/opt/Mattermost"], [_cfg(h, "Mattermost")], []),+ "skype": (["/usr/bin/skypeforlinux", "/snap/skype"], [_cfg(h, "skypeforlinux")], []),+ }+++@_lp("comms.native_apps", level="L1", family=COMMS, tier="T0", collect="core")+def comms_native_apps(h, facts):+ """Native comms/mail apps: installed, launched (profile dir exists), last-used day from profile mtimes."""+ rows = {}+ for app, (inst, data, act) in _comms_cands(h).items():+ r = _app_row(h, inst, data, act)+ if r:+ rows[app] = r+ if not rows:+ return {"present": False}+ return {"present": True, **rows}+++def _discord_dirs(h):+ return [d for d in (_cfg(h, "discord"), _cfg(h, "discordcanary"), _cfg(h, "discordptb"),+ _flat(h, "com.discordapp.Discord", "config", "discord"), _snapu(h, "discord", "current", ".config", "discord"))+ if _isdir(d)]+++@_lp("discord.present", level="L1", family=COMMS, tier="T0", collect="core")+def discord_present(h, facts):+ """Discord desktop: install dirs, profile dir, version dir, autostart entry."""+ inst = _first("/usr/share/discord", "/opt/discord", "/usr/lib/discord", "/var/lib/flatpak/app/com.discordapp.Discord", "/snap/discord")+ dirs = _discord_dirs(h)+ if not (inst or dirs):+ return {"present": False}+ vers = sorted(n for d in dirs for n in (_ls(d) or []) if re.fullmatch(r"\d+\.\d+\.\d+", n))+ auto = any("discord" in n.lower() for n in (_ls(_cfg(h, "autostart")) or []))+ return {"present": True, "installed": bool(inst), "profile_dir": bool(dirs), "version": vers[-1] if vers else None,+ "autostart": auto}+++@_lp("discord.usage", level="L2", family=COMMS, tier="T1", collect="extended", gate="discord.present", timeout_ms=3000)+def discord_usage(h, facts):+ """Signed-in and voice days from logs/renderer_js.log tags; last use from Local Storage mtime."""+ dirs = _discord_dirs(h)+ if not dirs:+ return {"present": False}+ days, gw, rtc = set(), set(), set()+ size = 0+ rx = re.compile(r"^\[(\d{4}-\d\d-\d\d) ([\d:.]+)\] \[\w+\]\s+\[?([A-Za-z_]+)")+ for d in dirs:+ log = os.path.join(d, "logs", "renderer_js.log")+ if not os.path.isfile(log):+ continue+ size += os.path.getsize(log)+ with open(log, encoding="utf-8", errors="replace") as fh:+ if os.path.getsize(log) > 16_000_000:+ fh.seek(os.path.getsize(log) - 16_000_000)+ for line in fh:+ m = rx.match(line)+ if not m:+ continue+ dd, _tm, tag = m.groups()+ days.add(dd)+ if tag == "GatewaySocket":+ gw.add(dd)+ elif tag.startswith("RTC"):+ rtc.add(dd)+ ls = _newest_mtime([os.path.join(d, "Local Storage", "leveldb") for d in dirs])+ used = bool(gw or rtc) or bool(ls and time.time() - ls < 90 * 86400)+ return {"present": used, "log_days": len(days), "first_day": min(days) if days else None,+ "last_day": max(days) if days else None, "gateway_days": len(gw), "rtc_days": len(rtc),+ "local_storage_last": _day(ls), "log_bytes": size}+++def _notes_cands(h):+ U = _U(h)+ return {+ "obsidian": (["/usr/bin/obsidian", "/opt/Obsidian", "/snap/obsidian", "/var/lib/flatpak/app/md.obsidian.Obsidian"],+ [_cfg(h, "obsidian"), _flat(h, "md.obsidian.Obsidian", "config", "obsidian")],+ [_cfg(h, "obsidian", "obsidian.json")]),+ "notion": (["/opt/Notion", "/usr/bin/notion-app"], [_cfg(h, "Notion"), _cfg(h, "notion-app")], []),+ "logseq": (["/opt/Logseq", "/var/lib/flatpak/app/com.logseq.Logseq"], [os.path.join(U, ".logseq"), _cfg(h, "Logseq")], []),+ "joplin": ([os.path.join(U, ".joplin")], [_cfg(h, "joplin-desktop"), _cfg(h, "Joplin")], []),+ "standard_notes": ([], [_cfg(h, "Standard Notes")], []),+ "zim": (["/usr/bin/zim"], [_cfg(h, "zim")], []),+ "knotes": (["/usr/bin/knotes"], [_data(h, "knotes")], []),+ "anytype": ([], [_cfg(h, "anytype")], []),+ "trilium": ([], [_cfg(h, "trilium-data"), os.path.join(U, "trilium-data")], []),+ }+++@_lp("productivity.notes_apps", level="L1", family=COMMS, tier="T0", collect="core")+def notes_apps(h, facts):+ """Notes apps installed or launched: Obsidian, Notion, Logseq, Joplin, Zim, KNotes, ..."""+ rows = {}+ for app, (inst, data, act) in _notes_cands(h).items():+ r = _app_row(h, inst, data, act)+ if r:+ rows[app] = r+ return {"present": bool(rows), "apps": sorted(rows), "detail": rows}+++@_lp("obsidian.vaults", level="L2", family=COMMS, tier="T1", collect="extended", gate="productivity.notes_apps")+def obsidian_vaults(h, facts):+ """Obsidian vault count and note counts (vault names and paths are not emitted)."""+ j = _read_json(_cfg(h, "obsidian", "obsidian.json")) or _read_json(_flat(h, "md.obsidian.Obsidian", "config", "obsidian", "obsidian.json"))+ vs = (j or {}).get("vaults") or {} if isinstance(j, dict) else {}+ if not vs:+ return {"present": False}+ notes, files, newest = 0, 0, 0++ def on_file(e, s, depth):+ nonlocal notes, newest+ if e.name.lower().endswith(".md"):+ notes += 1+ newest = max(newest, s.st_mtime)+ for v in list(vs.values())[:10]:+ p = v.get("path") if isinstance(v, dict) else None+ if p and _isdir(p) and p.startswith(_U(h)):+ st = bf._walk(p, max_depth=6, max_entries=30000, budget_s=1.5, on_file=on_file,+ skip_dir=lambda n, _p: n in (".obsidian", ".git", ".trash", "node_modules"))+ files += st["files"]+ return {"present": True, "vaults": len(vs), "open": sum(1 for v in vs.values() if isinstance(v, dict) and v.get("open")),+ "notes_md": notes, "files": files, "newest_note": bf._iso(newest)}+++_EDR = {"crowdstrike": ["/opt/CrowdStrike"], "sentinelone": ["/opt/sentinelone"], "defender_mdatp": ["/opt/microsoft/mdatp", "/etc/opt/microsoft/mdatp"],+ "tanium": ["/opt/Tanium"], "wazuh": ["/var/ossec"], "elastic_agent": ["/opt/Elastic"], "osquery": ["/etc/osquery", "/opt/osquery"],+ "sophos": ["/opt/sophos-spl"], "carbonblack": ["/opt/carbonblack"], "qualys": ["/usr/local/qualys"],+ "rapid7": ["/opt/rapid7"], "trendmicro": ["/opt/ds_agent"], "jamf_protect": ["/opt/jamf"], "kolide": ["/usr/local/kolide-k2"],+ "zscaler": ["/opt/zscaler"], "globalprotect": ["/opt/paloaltonetworks"], "netskope": ["/opt/netskope"]}+++@_lp("work.security_agents", level="L1", family=COMMS, tier="T0", collect="core")+def work_security_agents(h, facts):+ """EDR/ZTNA/RMM agents by install path (no service queries)."""+ hits = sorted(k for k, ps in _EDR.items() if _ex(*ps))+ return {"present": True, "agents": hits, "checked": len(_EDR)}+++@_lp("work.mdm", level="L1", family=COMMS, tier="T0", collect="core")+def work_mdm(h, facts):+ """Device management on Linux: Intune for Linux, Canonical Landscape, Ubuntu Pro attach, Puppet/Chef/Salt agents."""+ found = {"intune": _ex("/opt/microsoft/intune", "/usr/bin/intune-portal"),+ "landscape": _ex("/etc/landscape/client.conf"), "ubuntu_pro_attached": _ex("/var/lib/ubuntu-advantage/private/machine-token.json"),+ "puppet": _ex("/etc/puppetlabs"), "chef": _ex("/etc/chef"), "salt_minion": _ex("/etc/salt/minion"),+ "fleetd": _ex("/opt/orbit")}+ real = [k for k, v in found.items() if v and k != "ubuntu_pro_attached"]+ return {"present": True, "real_enrollments": len(real), "enrollments": real, "ubuntu_pro_attached": found["ubuntu_pro_attached"]}+++@_lp("work.join_state", level="L1", family=COMMS, tier="T0", collect="core")+def work_join_state(h, facts):+ """Directory join: sssd/realmd/winbind config presence and krb5 default realm set (realm name not emitted)."""+ krb = _open_text("/etc/krb5.conf", 200_000) or ""+ sssd = _ex("/etc/sssd/sssd.conf")+ winbind = "winbind" in (_open_text("/etc/nsswitch.conf", 100_000) or "")+ joined = sssd or winbind+ return {"present": True, "sssd": sssd, "winbind": winbind, "realmd": _ex("/etc/realmd.conf"),+ "krb5_default_realm_set": bool(re.search(r"^\s*default_realm\s*=", krb, re.M)),+ "state": "joined" if joined else "workgroup", "domain_joined": joined, "azure_ad_joined": _ex("/opt/microsoft/intune")}+++@_lp("work.policies", level="L1", family=COMMS, tier="T0", collect="core")+def work_policies(h, facts):+ """Managed browser policy files (Chrome, Chromium, Brave, Edge, Firefox): file counts only."""+ dirs = {"chrome": "/etc/opt/chrome/policies/managed", "chromium": "/etc/chromium/policies/managed",+ "brave": "/etc/brave/policies/managed", "edge": "/etc/opt/edge/policies/managed"}+ apps = {k: len([n for n in (_ls(d) or []) if n.endswith(".json")]) for k, d in dirs.items()}+ if _ex("/etc/firefox/policies/policies.json", "/usr/lib/firefox/distribution/policies.json"):+ apps["firefox"] = 1+ configured = {k: {"values": v, "subkeys": 0} for k, v in apps.items() if v}+ return {"present": True, "app_policies": configured, "app_policy_count": len(configured)}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_apps_dev.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_apps_dev.pynew file mode 100644index 00000000000..53b83ae4030--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_apps_dev.py@@ -0,0 +1,562 @@+"""Linux user-level probes: dev.++Registration only at import time. Shared helpers and registration wrappers live in linux_apps.+"""+from __future__ import annotations++import collections+import datetime as dt+import glob+import os+import re+import shutil+import time++from . import apps_dev as ad+from . import apps_dev_devenv as ad_devenv+from .linux_apps import (DEV, _U, _cachedir, _cfg, _data, _day, _ex, _extra_bins, _fact, _first,+ _is_op, _isdir, _lp, _ls, _mirror, _mtime, _npm_roots, _read_json, _spawn, _which)++# ================================================================== dev++@_lp("apps.pkg_managers", level="L1", family=DEV, tier="T0", collect="core")+def apps_pkg_managers(h, facts):+ """Package managers: apt (inbox), snap, flatpak, brew, nix, npm/pnpm/bun/yarn, cargo, go, uv, pipx."""+ U = _U(h)+ b = {"apt": os.path.exists("/usr/bin/apt"), "snap": os.path.exists("/usr/bin/snap"),+ "flatpak": os.path.exists("/usr/bin/flatpak"), "brew": _ex("/home/linuxbrew/.linuxbrew/bin/brew", os.path.join(U, ".linuxbrew")),+ "nix": _ex("/nix", os.path.join(U, ".nix-profile")), "npm": bool(_which(h, "npm")), "pnpm": bool(_which(h, "pnpm")),+ "bun": bool(_which(h, "bun")), "yarn": bool(_which(h, "yarn")), "cargo": bool(_which(h, "cargo")),+ "go": bool(_which(h, "go")), "uv": bool(_which(h, "uv")), "pipx": bool(_which(h, "pipx")),+ "fnm": bool(_which(h, "fnm")) or _isdir(_data(h, "fnm")), "nvm": _isdir(os.path.join(U, ".nvm"))}+ inbox = {"apt", "snap"}+ return {"present": True, **b, "managers": sorted(k for k, v in b.items() if v and k not in inbox)}+++def _ls_pkgs(root, cap=500):+ names = _ls(root, cap)+ if names is None:+ return None+ pk = []+ for n in names:+ if n.startswith("@"):+ pk += [f"{n}/{s}" for s in (_ls(os.path.join(root, n), 100) or [])]+ elif not n.startswith("."):+ pk.append(n)+ return sorted(pk)+++@_lp("dev.npm_globals", level="L2", family=DEV, tier="T1", collect="core", gate="apps.pkg_managers")+def dev_npm_globals(h, facts):+ """Global JS packages by manager (npm roots incl. fnm/nvm, pnpm, bun, yarn); directory listings, no spawn."""+ U = _U(h)+ out, allp = {}, set()+ for r in _npm_roots(h):+ pk = [p for p in (_ls_pkgs(r) or []) if p not in ("npm", "corepack")]+ if pk:+ key = "npm_user" if r.startswith(U) else "npm_system"+ out.setdefault(key, []).extend(pk)+ allp.update(pk)+ for key, r in (("pnpm", _data(h, "pnpm", "global", "5", "node_modules")),+ ("bun", os.path.join(U, ".bun", "install", "global", "node_modules")),+ ("yarn", _cfg(h, "yarn", "global", "node_modules"))):+ pk = _ls_pkgs(r)+ if pk:+ out[key] = pk+ allp.update(pk)+ if not out:+ return {"present": False}+ return {"present": True, "count": len(allp), "packages": sorted(allp)[:80],+ "by_manager": {k: len(set(v)) for k, v in out.items()}}+++@_lp("dev.lang_globals", level="L2", family=DEV, tier="T1", collect="core", gate="apps.pkg_managers")+def dev_lang_globals(h, facts):+ """cargo-installed crates (~/.cargo/.crates2.json) and ~/go/bin binaries; names only."""+ U = _U(h)+ out = {}+ cj = _read_json(os.path.join(U, ".cargo", ".crates2.json"))+ if isinstance(cj, dict) and isinstance(cj.get("installs"), dict):+ out["cargo"] = sorted({k.split(" ")[0] for k in cj["installs"]})[:60]+ elif _isdir(os.path.join(U, ".cargo", "bin")):+ out["cargo_bin"] = sorted(n for n in _ls(os.path.join(U, ".cargo", "bin")) or [] if not n.startswith("."))[:60]+ gb = _ls(os.path.join(os.environ.get("GOPATH") or os.path.join(U, "go"), "bin"))+ if gb:+ out["go_bin"] = sorted(gb)[:60]+ if not out:+ return {"present": False}+ return {"present": True, "count": sum(len(v) for v in out.values()), **out}+++@_lp("dev.uv_tools", level="L2", family=DEV, tier="T1", collect="core", gate="dev.toolchain_presence")+def dev_uv_tools(h, facts):+ """uv tools and uv-managed Pythons (~/.local/share/uv listing, equals `uv tool list`), ~/.local/bin entries."""+ tools = _ls(_data(h, "uv", "tools"), 200)+ py = _ls(_data(h, "uv", "python"), 200)+ lb = _ls(os.path.join(_U(h), ".local", "bin"), 300)+ if tools is None and py is None and lb is None:+ return {"present": False}+ return {"present": True, "tools": sorted(t for t in (tools or []) if not t.startswith("."))[:60],+ "pythons": sorted(p for p in (py or []) if p.startswith(("cpython", "pypy")))[:30],+ "local_bin_count": len(lb or []), "local_bin": sorted(lb or [])[:40]}+++@_lp("dev.git", level="L1", family=DEV, tier="T0", collect="core")+def dev_git(h, facts):+ """git binary on PATH (no spawn); version comes from dev.toolchain_versions."""+ exe = _which(h, "git")+ if not exe:+ return None+ return {"present": True, "on_path": bool(shutil.which("git")), "path_kind": "user" if exe.startswith(_U(h)) else "system",+ "xdg_config": os.path.exists(_cfg(h, "git", "config"))}+++_mirror("dev.git_global_config", ad_devenv.dev_git_global_config)+++@_lp("dev.gh_auth_presence", level="L1", family=DEV, tier="T3", collect="core")+def dev_gh_auth_presence(h, facts):+ """GitHub CLI hosts.yml presence/size (means gh logged in; never opened)."""+ return h.meta(_cfg(h, "gh", "hosts.yml"))+++@_lp("dev.docker_config_presence", level="L1", family=DEV, tier="T3", collect="core")+def dev_docker_config_presence(h, facts):+ """~/.docker/config.json presence/size (may hold registry auths; never opened)."""+ return h.meta(os.path.join(_U(h), ".docker", "config.json"))+++_mirror("dev.npmrc_presence", ad_devenv.dev_npmrc_presence)++_PATH_TOOLS = [("local_bin", r"/\.local/bin$"), ("home_bin", r"^/home/[^/]+/bin$"), ("bun", r"/\.bun/bin"),+ ("cargo", r"/\.cargo/bin"), ("go", r"/go/bin"), ("fnm", r"fnm"), ("nvm", r"\.nvm"), ("volta", r"\.volta"),+ ("pnpm", r"pnpm"), ("deno", r"\.deno"), ("snap", r"^/snap/bin"), ("flatpak", r"flatpak/exports/bin"),+ ("linuxbrew", r"linuxbrew"), ("nix", r"\.nix-profile|/nix/"), ("cuda", r"cuda"), ("conda", r"conda|miniforge"),+ ("pyenv", r"\.pyenv"), ("hermes", r"hermes"), ("games", r"^/usr(/local)?/games$"), ("opt", r"^/opt/")]+++@_lp("dev.path_entries", level="L1", family=DEV, tier="T0", collect="core")+def dev_path_entries(h, facts):+ """PATH entry count and known-tool dir matches for this process (paths not emitted); user bin dirs off PATH."""+ ents = [e for e in os.environ.get("PATH", "").split(":") if e]+ tools = sorted({t for t, rx in _PATH_TOOLS for e in ents if re.search(rx, e)})+ off = [os.path.relpath(d, _U(h)) for d in _extra_bins(h)+ if d.startswith(_U(h)) and _isdir(d) and d not in ents]+ return {"present": True, "entries": len(ents), "user": sum(1 for e in ents if e.startswith(_U(h))),+ "machine": sum(1 for e in ents if not e.startswith(_U(h))), "tools": tools, "user_bin_dirs_off_path": off}+++_mirror("dev.ssh_config", ad_devenv.dev_ssh_config)++_TOOLCHAIN = ["node", "npm", "pnpm", "yarn", "bun", "deno", "fnm", "nvm", "volta", "uv", "pipx", "conda", "poetry",+ "rustc", "cargo", "rustup", "go", "dotnet", "java", "javac", "mvn", "gradle", "cmake", "ninja", "make", "clang",+ "gcc", "zig", "nvcc", "gh", "docker", "podman", "kubectl", "terraform", "tailscale", "claude", "codex",+ "hermes", "ollama", "code", "cursor", "windsurf", "zed", "nvim", "vim", "emacs", "kate", "python3", "python",+ "tmux", "zellij", "lazygit", "rg", "fd", "fzf", "zoxide", "mcfly", "btop", "htop", "jq", "ssh", "mosh"]+++@_lp("dev.toolchain_presence", level="L1", family=DEV, tier="T0", collect="core")+def dev_toolchain_presence(h, facts):+ """which() for language/infra/AI/editor CLIs over PATH plus user tool dirs; off-PATH install dirs."""+ U = _U(h)+ found, user_found = [], []+ for t in _TOOLCHAIN:+ p = _which(h, t)+ if p:+ found.append(t)+ if p.startswith(U):+ user_found.append(t)+ off = {k: _isdir(p) for k, p in [+ ("cargo_home", os.path.join(U, ".cargo")), ("rustup", os.path.join(U, ".rustup")), ("go_root", "/usr/local/go"),+ ("gopath", os.path.join(U, "go")), ("uv_pythons", _data(h, "uv", "python")), ("pyenv", os.path.join(U, ".pyenv")),+ ("miniconda", os.path.join(U, "miniconda3")), ("anaconda", os.path.join(U, "anaconda3")),+ ("miniforge", os.path.join(U, "miniforge3")), ("fnm_nodes", _data(h, "fnm", "node-versions")),+ ("nvm", os.path.join(U, ".nvm")), ("cuda", "/usr/local/cuda"), ("sdkman", os.path.join(U, ".sdkman")),+ ("android_sdk", os.path.join(U, "Android", "Sdk")), ("dotnet", os.path.join(U, ".dotnet"))]}+ return {"present": True, "on_path": found, "user_installed": user_found, "off_path": sorted(k for k, v in off.items() if v)}+++@_lp("dev.toolchain_versions", level="L2", family=DEV, tier="T0", collect="extended", gate="dev.toolchain_presence",+ timeout_ms=12000)+def dev_toolchain_versions(h, facts):+ """--version spawns (parallel, gated on which) for runtimes, package managers, AI CLIs and infra CLIs.+ `hermes --version` is excluded: it blocked > 10 s; hermes.present reads the version from pyproject."""+ from concurrent.futures import ThreadPoolExecutor+ specs = [("node", ["--version"]), ("npm", ["--version"]), ("uv", ["--version"]), ("gh", ["--version"]),+ ("git", ["--version"]), ("docker", ["--version"]), ("bun", ["--version"]), ("pnpm", ["--version"]),+ ("deno", ["--version"]), ("rustc", ["--version"]), ("cargo", ["--version"]), ("go", ["version"]),+ ("python3", ["--version"]), ("claude", ["--version"]), ("codex", ["--version"]), ("ollama", ["--version"]),+ ("tmux", ["-V"]), ("nvim", ["--version"]), ("kubectl", ["version", "--client=true"]),+ ("tailscale", ["version"]), ("java", ["-version"])]+ todo = [(n, [_which(h, n)] + a) for n, a in specs if _which(h, n)]++ def one(item):+ name, args = item+ rc, txt, ms = _spawn(h, args, timeout=3)+ line = next((l.strip() for l in txt.splitlines() if l.strip()), None)+ return name, {"version": ad._redact(line, 90) if line else None, "rc": rc, "ms": ms}+ out = {}+ with ThreadPoolExecutor(max_workers=6) as ex:+ for name, r in ex.map(one, todo):+ out[name] = r+ return {"present": bool(out), "tools": out}+++_EDITORS = {+ # name: (install paths, extension dir(s), user dir)+ "vscode": (["/usr/share/code", "/usr/bin/code", "/snap/code", "/var/lib/flatpak/app/com.visualstudio.code"],+ [".vscode/extensions"], "Code"),+ "vscode_insiders": (["/usr/share/code-insiders"], [".vscode-insiders/extensions"], "Code - Insiders"),+ "vscode_server": ([], [".vscode-server/extensions"], None),+ "cursor": (["/opt/Cursor", "/usr/share/cursor", "/usr/bin/cursor"], [".cursor/extensions"], "Cursor"),+ "cursor_server": ([], [".cursor-server/extensions"], None),+ "windsurf": (["/usr/share/windsurf", "/opt/Windsurf"], [".windsurf/extensions"], "Windsurf"),+ "windsurf_server": ([], [".windsurf-server/extensions"], None),+ "vscodium": (["/usr/share/codium", "/snap/codium"], [".vscode-oss/extensions"], "VSCodium"),+ "kiro": (["/usr/share/kiro", "/opt/Kiro"], [".kiro/extensions"], "Kiro"),+}+++@_lp("editor.vscode", level="L2", family=DEV, tier="T2", collect="core", gate="dev.toolchain_presence")+def editor_vscode(h, facts):+ """VS Code family incl. Remote-SSH server dirs: extension ids (AI flagged), workspaces, MCP/chat; other editors."""+ U = _U(h)+ out = {}+ for name, (inst, extds, userd) in _EDITORS.items():+ installed = any(os.path.exists(p) for p in inst)+ extd = next((os.path.join(U, e) for e in extds if _isdir(os.path.join(U, e))), None)+ user = _cfg(h, userd, "User") if userd else None+ if not (installed or extd or (user and _isdir(user))):+ continue+ ids = ad_devenv._ext_ids(extd) if extd else []+ e = {"installed": installed, "extensions": len(ids), "extension_ids": ids[:80],+ "ai_extensions": [i for i in ids if ad_devenv._AI_EXT.search(i)]}+ if user and _isdir(user):+ ws = _ls(os.path.join(user, "workspaceStorage"), 5000)+ e["workspaces_opened"] = len(ws) if ws is not None else 0+ e["settings_json"] = os.path.exists(os.path.join(user, "settings.json"))+ e["keybindings_json"] = os.path.exists(os.path.join(user, "keybindings.json"))+ e["profiles"] = len(_ls(os.path.join(user, "profiles")) or [])+ mj = _read_json(os.path.join(user, "mcp.json"), jsonc=True)+ e["mcp_servers"] = len((mj.get("servers") or mj.get("mcpServers") or {})) if isinstance(mj, dict) else 0+ e["chat_sessions"] = len(glob.glob(os.path.join(user, "workspaceStorage", "*", "chatSessions", "*"))[:5000])+ e["user_mtime"] = _mtime(user)+ if name.endswith("_server"):+ e["remote_target"] = True+ e["user_mtime"] = _mtime(extd) if extd else None+ out[name] = e+ other = {"jetbrains": [x for x in (_ls(_cfg(h, "JetBrains")) or []) if re.match(r"^[A-Za-z]+\d{4}\.\d", x)],+ "zed": _isdir(_cfg(h, "zed")) or _isdir(_data(h, "zed")),+ "neovim_config": _isdir(_cfg(h, "nvim")), "vimrc": _ex(os.path.join(U, ".vimrc"), os.path.join(U, ".vim")),+ "emacs": _ex(os.path.join(U, ".emacs.d"), os.path.join(U, ".emacs"), _cfg(h, "emacs")),+ "helix": _isdir(_cfg(h, "helix")), "sublime": _isdir(_cfg(h, "sublime-text")),+ "kate": _ex(_cfg(h, "katerc")), "kwrite": _ex(_cfg(h, "kwriterc"))}+ other = {k: v for k, v in other.items() if v}+ customised = any(e["extensions"] or e.get("settings_json") or e.get("keybindings_json") for e in out.values()) or \+ bool(other.get("neovim_config") or other.get("emacs"))+ return {"present": bool(out or other), "extensions": sum(e["extensions"] for e in out.values()),+ "customised": customised, "editors": out, "other": other}+++# ---------------- repos (deep)++_REPO_SKIP = {"node_modules", ".cache", "__pycache__", ".venv", "venv", "site-packages", ".npm", ".rustup", "snap",+ ".cargo", ".bun", ".vscode-server", ".cursor-server", ".mozilla", "trash", ".local/share/trash",+ "target", "dist", "build", ".next", ".git", "go", ".gradle", ".m2", ".nvm", ".pyenv", "miniconda3",+ "anaconda3", ".docker", ".ollama", ".var", ".steam"}+++def _repos_lx(h):+ """Bounded repo walk: home depth 5, 60k dirs, 8 s; classes user_area / tool_managed (dot dirs) / operator."""+ def build():+ deadline = time.perf_counter() + 8.0+ U = _U(h)+ hits, seen, visited = [], set(), [0]+ stack = [(U, 0)]+ while stack and time.perf_counter() < deadline and visited[0] < 60000:+ d, depth = stack.pop()+ visited[0] += 1+ try:+ with os.scandir(d) as it:+ ents = list(zip(range(3000), it))+ except OSError:+ continue+ names = {e.name for _, e in ents}+ if ".git" in names and (os.path.exists(os.path.join(d, ".git", "HEAD")) or os.path.isfile(os.path.join(d, ".git"))):+ rp = os.path.realpath(d)+ if rp not in seen:+ seen.add(rp)+ hits.append(d)+ continue+ if depth >= 5:+ continue+ for _, e in ents:+ if e.name.lower() in _REPO_SKIP:+ continue+ try:+ if not e.is_dir(follow_symlinks=False):+ continue+ except OSError:+ continue+ stack.append((e.path, depth + 1))+ repos = []+ for d in hits[:200]:+ rel = os.path.relpath(d, U)+ cls = "operator" if _is_op(h, d) else "tool_managed" if rel.startswith(".") else "user_area"+ gd = os.path.join(d, ".git")+ remotes, branch, head_mtime, local_email = [], None, None, None+ if os.path.isdir(gd):+ try:+ with open(os.path.join(gd, "HEAD"), encoding="utf-8", errors="replace") as f:+ hd = f.read(200).strip()+ branch = hd[16:] if hd.startswith("ref: refs/heads/") else "detached"+ except OSError:+ pass+ head_mtime = _mtime(os.path.join(gd, "logs", "HEAD")) or _mtime(os.path.join(gd, "index"))+ try:+ with open(os.path.join(gd, "config"), encoding="utf-8", errors="replace") as f:+ cfg = f.read(100_000)+ remotes = re.findall(r"^\s*url\s*=\s*(\S+)", cfg, re.M)+ m = re.search(r"^\s*email\s*=\s*(\S+)", cfg, re.M)+ local_email = m.group(1).lower() if m else None+ except OSError:+ pass+ markers = [m for m in ("package.json", "pyproject.toml", "uv.lock", "Cargo.toml", "go.mod", "pom.xml",+ "build.gradle", "Dockerfile", "flake.nix", "AGENTS.md", "CLAUDE.md", ".mcp.json")+ if os.path.exists(os.path.join(d, m))]+ repos.append({"path": d, "class": cls, "branch": branch, "head_mtime": head_mtime, "remotes": remotes,+ "local_email": local_email, "markers": markers})+ return {"repos": repos, "visited_dirs": visited[0], "timed_out": time.perf_counter() >= deadline}+ return build+++def _commits_lx(h):+ def build():+ git = _which(h, "git")+ if not git:+ return None+ env_ids = {x.strip().lower() for x in os.environ.get("UIL_GIT_IDENTITY", "").split(",") if x.strip()}+ ids = set(env_ids)+ for gc in (os.path.join(_U(h), ".gitconfig"), _cfg(h, "git", "config")):+ try:+ with open(gc, encoding="utf-8", errors="replace") as f:+ ids |= {m.lower() for m in re.findall(r"^\s*email\s*=\s*(\S+)", f.read(100_000), re.M)}+ except OSError:+ pass+ res = {"identity_sources": {"env": bool(env_ids), "global": bool(ids - env_ids), "repo_local": 0}, "by_class": {},+ "hours_local": collections.Counter(), "tz_offsets": collections.Counter(), "weekday": collections.Counter(),+ "month": collections.Counter(), "repos_with_own": {}}+ # Newest HEAD first, so when the deadline cuts the scan it drops the stalest repos, not a random set.+ deadline = time.perf_counter() + 10.0+ res["repos_scanned"], res["timed_out"] = 0, False+ for x in sorted(ad_devenv._repos(h)["repos"], key=lambda r: str(r.get("head_mtime") or ""), reverse=True):+ if x["class"] == "operator":+ continue+ if time.perf_counter() > deadline:+ res["timed_out"] = True+ break+ rid = set(ids)+ if x["local_email"]:+ rid.add(x["local_email"])+ res["identity_sources"]["repo_local"] += 1+ rc, txt, _ms = _spawn(h, [git, "-C", x["path"], "log", "--all", "--no-merges",+ "--format=%ae%x09%an%x09%at%x09%ai", "-n", "100000"], timeout=max(0.5, deadline - time.perf_counter()))+ if rc != 0:+ continue+ res["repos_scanned"] += 1+ mine = total = 0+ for line in txt.splitlines():+ parts = line.split("\t")+ if len(parts) < 4:+ continue+ total += 1+ if parts[0].lower() in rid or parts[1].lower() in rid:+ mine += 1+ try:+ t = dt.datetime.fromtimestamp(int(parts[2]))+ res["hours_local"][t.hour] += 1+ res["weekday"][t.strftime("%a")] += 1+ res["month"][t.strftime("%Y-%m")] += 1+ except (ValueError, OSError):+ pass+ res["tz_offsets"][parts[3].strip()[-5:]] += 1+ c = res["by_class"].setdefault(x["class"], [0, 0])+ c[0] += mine+ c[1] += total+ if mine:+ res["repos_with_own"][x["class"]] = res["repos_with_own"].get(x["class"], 0) + 1+ return res+ return build+++def _prime_repos(h):+ ad._memo(h, "repos", _repos_lx(h))+++def _prime_commits(h):+ _prime_repos(h)+ ad._memo(h, "commits", _commits_lx(h))+++# dev.repos and dev.repos.remotes need only the walk; priming commits there made them wait for git log on every repo.+_mirror("dev.repos", ad_devenv.dev_repos, _prime_repos)+_mirror("dev.repos.remotes", ad_devenv.dev_repos_remotes, _prime_repos)+_mirror("dev.repos.my_commits", ad_devenv.dev_repos_my_commits, _prime_commits)+_mirror("dev.repos.commit_hours", ad_devenv.dev_repos_commit_hours, _prime_commits)++_BUILTINS = {"cd", "export", "source", ".", "alias", "unalias", "echo", "exit", "history", "set", "unset", "eval", "exec",+ "type", "which", "for", "if", "while", "sudo", "time", "nohup", "env", "clear", "pwd", "ls", "ll", "la", "fg",+ "bg", "jobs", "kill", "z", "zi", "man", "help"}+++def _cmd_name(line, known):+ t = line.strip().split()+ while t and (t[0] in ("sudo", "time", "nohup", "env", "exec") or "=" in t[0]):+ t = t[1:]+ if not t:+ return None+ c = os.path.basename(t[0])+ if not re.fullmatch(r"[A-Za-z0-9._+\-]{1,32}", c):+ return None+ return c if c in _BUILTINS or c in known else None+++@_lp("dev.shell_history", level="L2", family=DEV, tier="T1", collect="extended", gate="dev.path_entries")+def dev_shell_history(h, facts):+ """bash/zsh/fish/python/node history: line counts, last write, top command names (resolved executables or+ builtins only). Command lines, arguments and paths are never emitted."""+ U = _U(h)+ files = [("bash", os.path.join(U, ".bash_history")), ("zsh", os.environ.get("HISTFILE") or os.path.join(U, ".zsh_history")),+ ("zsh_histfile", os.path.join(U, ".histfile")), ("fish", _data(h, "fish", "fish_history")),+ ("python", os.path.join(U, ".python_history")), ("node", os.path.join(U, ".node_repl_history")),+ ("mcfly_db", _data(h, "mcfly", "history.db")), ("atuin_db", _data(h, "atuin", "history.db"))]+ known = set()+ for d in os.environ.get("PATH", "").split(":") + _extra_bins(h):+ known.update(_ls(d, 20000) or [])+ out, cmds, total = {}, collections.Counter(), 0+ seen = set()+ for label, p in files:+ try:+ rp = os.path.realpath(p)+ if rp in seen:+ continue+ st = os.stat(p)+ except OSError:+ continue+ seen.add(rp)+ if label.endswith("_db"):+ out[label] = {"bytes": st.st_size, "mtime": _day(st.st_mtime)}+ continue+ if st.st_size > 50_000_000:+ out[label] = {"bytes": st.st_size, "lines": None, "mtime": _day(st.st_mtime)}+ continue+ n = 0+ with open(p, "rb") as f:+ for raw in f:+ line = raw.decode("utf-8", "replace").strip()+ if not line:+ continue+ if label == "fish":+ if not line.startswith("- cmd: "):+ continue+ line = line[7:]+ elif label.startswith("zsh"):+ line = re.sub(r"^: \d+:\d+;", "", line)+ n += 1+ if label in ("bash", "zsh", "zsh_histfile", "fish"):+ c = _cmd_name(line, known)+ if c:+ cmds[c] += 1+ out[label] = {"lines": n, "bytes": st.st_size, "mtime": _day(st.st_mtime)}+ if label in ("bash", "zsh", "zsh_histfile", "fish"):+ total += n+ if not out:+ return {"present": False}+ return {"present": True, "lines": total, "files": out, "top_commands": dict(cmds.most_common(15)),+ "distinct_commands": len(cmds)}+++@_lp("dev.docker", level="L1", family=DEV, tier="T0", collect="core")+def dev_docker(h, facts):+ """Docker engine/CLI: binary, socket access for this user, docker group, rootless or Desktop-for-Linux dirs."""+ cli = _which(h, "docker")+ sock = "/var/run/docker.sock"+ rootless = os.path.join(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"), "docker.sock")+ desktop = _isdir(os.path.join(_U(h), ".docker", "desktop"))+ if not (cli or os.path.exists(sock) or desktop):+ return None+ try:+ import grp+ in_group = "docker" in {grp.getgrgid(g).gr_name for g in os.getgroups()}+ except Exception:+ in_group = None+ return {"present": True, "cli": bool(cli), "engine_socket": os.path.exists(sock),+ "socket_access": os.access(sock, os.R_OK | os.W_OK), "docker_group": in_group,+ "rootless_socket": os.path.exists(rootless), "desktop_for_linux": desktop,+ "podman": bool(_which(h, "podman")), "compose_plugin": _ex("/usr/libexec/docker/cli-plugins/docker-compose",+ "/usr/lib/docker/cli-plugins/docker-compose")}+++def _gb(s):+ m = re.match(r"([\d.]+)\s*([kKMGT]?B)", s or "")+ if not m:+ return 0.0+ return float(m.group(1)) * {"B": 1e-9, "kB": 1e-6, "KB": 1e-6, "MB": 1e-3, "GB": 1.0, "TB": 1e3}.get(m.group(2), 0)+++@_lp("dev.docker_runtime", level="L2", family=DEV, tier="T2", collect="extended", gate="dev.docker", timeout_ms=8000)+def dev_docker_runtime(h, facts):+ """`docker ps` names/images and `docker images` repos/sizes only; never exec, inspect or logs."""+ d = _fact(facts, "dev.docker") or {}+ cli = _which(h, "docker")+ if not cli or not (d.get("socket_access") or d.get("rootless_socket")):+ return {"present": True, "accessible": False, "count": 0}+ rc, ps, ms1 = _spawn(h, [cli, "ps", "--format", "{{.Names}}\t{{.Image}}\t{{.RunningFor}}"], timeout=5)+ rc2, im, ms2 = _spawn(h, [cli, "images", "--format", "{{.Repository}}:{{.Tag}}\t{{.Size}}"], timeout=5)+ if rc != 0 and rc2 != 0:+ return {"present": True, "accessible": False, "count": 0}+ running = [dict(zip(("name", "image", "up"), l.split("\t"))) for l in ps.splitlines() if l.strip()]+ images = [l.split("\t") for l in im.splitlines() if l.strip()]+ return {"present": True, "accessible": True, "count": len(running),+ "running": [{"name": r.get("name"), "image": (r.get("image") or "").split("@")[0][:80], "up": r.get("up")}+ for r in running[:40]],+ "images": len(images), "images_gb": round(sum(_gb(x[1]) for x in images if len(x) > 1), 2),+ "image_repos": sorted({x[0].rsplit(":", 1)[0] for x in images})[:40], "ms": round(ms1 + ms2, 1)}+++@_lp("dev.multiplexers", level="L2", family=DEV, tier="T1", collect="core", gate="dev.toolchain_presence")+def dev_multiplexers(h, facts):+ """tmux / zellij / screen session counts for this user (session names not emitted)."""+ uid = os.getuid()+ out = {}+ # no-tmp: ok — tmux puts its sockets under TMUX_TMPDIR, which falls back to /tmp+ tdir = os.path.join(os.environ.get("TMUX_TMPDIR", "/tmp"), f"tmux-{uid}")+ socks = [os.path.join(tdir, n) for n in (_ls(tdir) or [])]+ tm = _which(h, "tmux")+ if socks or tm:+ n = 0+ for s in socks[:10]:+ rc, txt, _ = _spawn(h, [tm, "-S", s, "ls"], timeout=2) if tm else (None, "", 0)+ if rc == 0:+ n += len([l for l in txt.splitlines() if l.strip()])+ out["tmux"] = {"installed": bool(tm), "sockets": len(socks), "sessions": n,+ "config": _ex(os.path.join(_U(h), ".tmux.conf"), _cfg(h, "tmux", "tmux.conf"))}+ zj = _which(h, "zellij")+ rt = os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{uid}")+ zsocks = [p for p in glob.glob(os.path.join(rt, "zellij", "*", "*")) + glob.glob(os.path.join(tempfile_dir(), f"zellij-{uid}", "*", "*"))+ if not os.path.isdir(p)]+ zres = glob.glob(_cachedir(h, "zellij", "*", "session_info", "*"))+ if zj or zsocks or zres:+ out["zellij"] = {"installed": bool(zj), "live_sessions": len(zsocks), "resurrectable": len(zres),+ "config": _isdir(_cfg(h, "zellij"))}+ sd = _first(f"/run/screen/S-{os.environ.get('USER', '')}", os.path.join(_U(h), ".screen"))+ if sd:+ out["screen"] = {"sessions": len(_ls(sd) or [])}+ if not out:+ return {"present": False}+ return {"present": True, "count": sum(v.get("sessions", 0) + v.get("live_sessions", 0) for v in out.values()), **out}+++def tempfile_dir():+ # no-tmp: ok — zellij puts its sockets under TMPDIR, which falls back to /tmp+ return os.environ.get("TMPDIR") or "/tmp"diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_apps_files.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_apps_files.pynew file mode 100644index 00000000000..27e84923e2d--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_apps_files.py@@ -0,0 +1,483 @@+"""Linux user-level probes: files, gaming, media.++Registration only at import time. Shared helpers and registration wrappers live in linux_apps.+"""+from __future__ import annotations++import collections+import datetime as dt+import os+import re+import time++from . import browser_files as bf+from . import usage_gaming as ug+from . import browser_files_content as bf_content+from . import usage_gaming_games as ug_games+from .linux_apps import (FILES, GAMING, MEDIA, _OP_DEEP, _OP_TOP, _U, _age_bucket, _cachedir,+ _cfg, _data, _ex, _first, _flat, _isdir, _lp, _ls, _mirror, _mtime, _open_text, _read_json, _snapu,+ _state)+from .linux_apps_dev import tempfile_dir++# ================================================================== files++_XDG_DEFAULTS = {"DESKTOP": "Desktop", "DOCUMENTS": "Documents", "DOWNLOAD": "Downloads", "PICTURES": "Pictures",+ "VIDEOS": "Videos", "MUSIC": "Music", "TEMPLATES": "Templates", "PUBLICSHARE": "Public"}+_KF_NAME = {"DESKTOP": "Desktop", "DOCUMENTS": "Documents", "DOWNLOAD": "Downloads", "PICTURES": "Pictures",+ "VIDEOS": "Videos", "MUSIC": "Music", "TEMPLATES": "Templates", "PUBLICSHARE": "Public"}+++def _known_folders_lx(h):+ U = _U(h)+ out = {v: os.path.join(U, d) for k, d in _XDG_DEFAULTS.items() for v in [_KF_NAME[k]]}+ t = _open_text(_cfg(h, "user-dirs.dirs"), 100_000) or ""+ for m in re.finditer(r'^XDG_(\w+)_DIR="([^"]*)"', t, re.M):+ k, v = m.group(1), m.group(2).replace("$HOME", U)+ if k in _KF_NAME:+ out[_KF_NAME[k]] = v if v.rstrip("/") != U.rstrip("/") else None+ pics = out.get("Pictures") or os.path.join(U, "Pictures")+ out["Screenshots"] = os.path.join(pics, "Screenshots")+ return out+++def _prime_kf(h):+ bf._cached(h, "kf", _known_folders_lx)+++_STANDARD = {"desktop", "documents", "downloads", "pictures", "videos", "music", "templates", "public", "snap"}+++def _home_root(h):+ U = _U(h)+ cls, loose = collections.Counter(), 0+ try:+ ents = list(zip(range(5000), os.scandir(U)))+ except OSError:+ return None+ for _, e in ents:+ try:+ is_dir = e.is_dir(follow_symlinks=False)+ except OSError:+ continue+ if not is_dir:+ loose += 0 if e.name.startswith(".") else 1+ continue+ low = e.name.lower()+ cls["operator" if _OP_TOP.match(e.name) else "dot" if low.startswith(".") else+ "standard" if low in _STANDARD else "custom"] += 1+ return {"dirs_by_class": dict(cls), "loose_visible_files": loose}+++@_lp("files.known_folders", level="L1", family=FILES, tier="T0", collect="core")+def files_known_folders(h, facts):+ """XDG user dirs (user-dirs.dirs): path under home, exists."""+ kf = bf._cached(h, "kf", _known_folders_lx)+ U = _U(h)+ rows = {n: {"path": ("~" + p[len(U):]) if p and p.startswith(U) else p, "exists": bool(p and _isdir(p)),+ "under_profile": bool(p and p.startswith(U)), "under_onedrive": False} for n, p in kf.items()}+ return {"present": any(r["exists"] for r in rows.values()), "folders": rows,+ "user_dirs_file": os.path.exists(_cfg(h, "user-dirs.dirs"))}+++@_lp("files.composition", level="L2", family=FILES, tier="T1", collect="extended", gate="files.known_folders",+ timeout_ms=9000)+def files_composition(h, facts):+ """Per XDG folder: files, bytes, extension/kind/age histograms (depth <= 6, 100k entries), plus home-root dir+ classes (dot/standard/custom/operator). No file names."""+ _prime_kf(h)+ v = bf_content.files_composition(h, facts)+ if isinstance(v, dict):+ v["home_root"] = _home_root(h)+ return v+_mirror("files.screenshots", bf_content.files_screenshots, _prime_kf)+++@_lp("files.recent_lnk", level="L2", family=FILES, tier="T1", collect="core", gate="files.known_folders")+def files_recent_lnk(h, facts):+ """Recent files: recently-used.xbel + KDE RecentDocuments (counts, ext histogram, date range) and the KDE+ activity-manager score cache (row count, top agent apps, range). File names and paths are never emitted."""+ now = time.time()+ mts, ext, ages = [], collections.Counter(), collections.Counter()+ op = 0+ xb = _open_text(_data(h, "recently-used.xbel"), 20_000_000)+ if xb:+ for m in re.finditer(r'<bookmark href="([^"]+)"[^>]*?modified="([^"]+)"', xb):+ href, mod = m.group(1), m.group(2)+ if _OP_DEEP.search(href):+ op += 1+ continue+ try:+ t = dt.datetime.fromisoformat(mod.replace("Z", "+00:00")).timestamp()+ except ValueError:+ continue+ mts.append(t)+ ages[_age_bucket(now - t)] += 1+ x = os.path.splitext(href.split("?")[0])[1].lower()+ ext[x if re.fullmatch(r"\.[a-z0-9]{1,5}", x or "") else "(folder_or_none)"] += 1+ rd = _data(h, "RecentDocuments")+ for n in (_ls(rd, 5000) or []):+ try:+ t = os.stat(os.path.join(rd, n)).st_mtime+ except OSError:+ continue+ mts.append(t)+ ages[_age_bucket(now - t)] += 1+ x = os.path.splitext(n[:-8] if n.endswith(".desktop") else n)[1].lower()+ ext[x if re.fullmatch(r"\.[a-z0-9]{1,5}", x or "") else "(folder_or_none)"] += 1+ ka = None+ db = _data(h, "kactivitymanagerd", "resources", "database")+ if os.path.exists(db):+ rows = h.sqlite(db, "select initiatingAgent, count(*), min(firstUpdate), max(lastUpdate) from ResourceScoreCache group by 1")+ if rows:+ agents = collections.Counter({(a or "?"): n for a, n, _f, _l in rows})+ ka = {"rows": sum(agents.values()), "agents": len(agents), "top_agents": dict(agents.most_common(10)),+ "first": bf._iso(min((r[2] or 0) for r in rows)), "last": bf._iso(max((r[3] or 0) for r in rows))}+ if not mts and not ka:+ return {"present": False}+ folders = ext.get("(folder_or_none)", 0)+ return {"present": True, "count": len(mts), "operator_filtered": op, "oldest": bf._iso(min(mts)) if mts else None,+ "newest": bf._iso(max(mts)) if mts else None, "folder_or_none": folders, "files": len(mts) - folders,+ "target_ext_top": dict(ext.most_common(10)), "age_mtime": {k: ages.get(k, 0) for k in bf.AGE_KEYS},+ "active_days_30d": len({time.strftime("%Y-%m-%d", time.localtime(t)) for t in mts if now - t < 30 * 86400}),+ "kactivity": ka}+++@_lp("files.clutter", level="L2", family=FILES, tier="T1", collect="extended", gate="files.known_folders", timeout_ms=6000)+def files_clutter(h, facts):+ """Trash, ~/.cache and thumbnail sizes, this user's files in TMPDIR, Desktop item count (bounded walks)."""+ _prime_kf(h)+ out = {"present": True}+ tr = _data(h, "Trash")+ if _isdir(tr):+ st = bf._walk(os.path.join(tr, "files"), max_depth=6, max_entries=100000, budget_s=1.5)+ out["recycle_bin"] = {"items": len(_ls(os.path.join(tr, "info"), 100000) or []), "files": st["files"],+ "bytes": st["bytes"], "truncated": st["truncated"]}+ c = _cachedir(h)+ if _isdir(c):+ st = bf._walk(c, max_depth=6, max_entries=150000, budget_s=1.5)+ out["cache_bytes"], out["cache_files"], out["cache_truncated"] = st["bytes"], st["files"], st["truncated"]+ th = bf._walk(_cachedir(h, "thumbnails"), max_depth=3, max_entries=100000, budget_s=0.8)+ out["thumbcache_bytes"] = th["bytes"]+ me, n, b = os.getuid(), [0], [0]++ def mine(e, s, depth):+ if s.st_uid == me:+ n[0] += 1+ b[0] += s.st_size+ tmp = tempfile_dir()+ st = bf._walk(tmp, max_depth=3, max_entries=50000, budget_s=1.0, on_file=mine,+ skip_dir=lambda nm, p: nm == "userscan" or bool(_OP_DEEP.search(p)))+ out["temp_files"], out["temp_bytes"], out["temp_truncated"] = n[0], b[0], st["truncated"]+ desk = bf_content._kf(h, "Desktop")+ names = [x for x in h.list_dir(desk, 5000) if not x.startswith(".")]+ out["desktop_items"] = len(names)+ out["desktop_shortcuts"] = sum(1 for x in names if x.endswith(".desktop"))+ out["baloo_index_bytes"] = h.meta(_data(h, "baloo", "index")).get("bytes")+ return out+++@_lp("files.download_sources", level="L2", family=FILES, tier="T1", collect="deep", gate="files.known_folders",+ timeout_ms=6000)+def files_download_sources(h, facts):+ """user.xdg.origin.url xattrs in Downloads (depth <= 2; written by Chrome/Firefox): source-site category counts+ (no hosts, no file names). The Linux counterpart of Zone.Identifier."""+ _prime_kf(h)+ root = bf_content._kf(h, "Downloads")+ if not _isdir(root):+ return {"present": False}+ cats, ext_cat = collections.Counter(), collections.Counter()+ n = with_x = 0+ deadline = time.perf_counter() + 4.0+ stack, trunc = [(root, 0)], None+ while stack:+ d, depth = stack.pop()+ try:+ entries = list(os.scandir(d))+ except OSError:+ continue+ for e in entries:+ if e.is_dir(follow_symlinks=False):+ if depth + 1 < 2 and not _OP_DEEP.search(e.path):+ stack.append((e.path, depth + 1))+ continue+ n += 1+ if n > 5000 or time.perf_counter() > deadline:+ trunc = "cap"+ stack.clear()+ break+ try:+ url = os.getxattr(e.path, "user.xdg.origin.url", follow_symlinks=False).decode("utf-8", "replace")+ except (OSError, AttributeError):+ continue+ with_x += 1+ host, _ = bf._host_of(url)+ c = bf._categorize(bf_content._reg_domain(host)) if host else "other"+ c = "sensitive" if c in bf.SENSITIVE_CATS else c+ cats[c] += 1+ ext_cat[f"{c}:{os.path.splitext(e.name)[1].lower() or '(none)'}"] += 1+ return {"present": n > 0, "files_scanned": n, "depth": 2, "truncated": trunc, "with_origin_xattr": with_x,+ "source_categories": dict(cats.most_common()), "category_ext_top": dict(ext_cat.most_common(10))}+++@_lp("files.profile_size_walk", level="L2", family=FILES, tier="T2", collect="deep", gate="files.known_folders",+ timeout_ms=30000)+def files_profile_size_walk(h, facts):+ """Size of each top-level home dir (depth <= 10, 300k entries/dir, 25 s total); operator dirs excluded."""+ U = _U(h)+ deadline = time.perf_counter() + 25.0+ rows, loose = [], 0+ try:+ entries = list(os.scandir(U))+ except OSError:+ return {"present": False}+ for e in entries:+ try:+ if not e.is_dir(follow_symlinks=False):+ loose += 1+ continue+ except OSError:+ continue+ low = e.name.lower()+ cls = ("operator" if _OP_TOP.match(e.name) else "dot" if low.startswith(".") else+ "standard" if low in _STANDARD else "custom")+ if cls == "operator":+ rows.append({"name": e.name, "class": cls, "bytes": 0, "skipped": "operator"})+ continue+ remain = deadline - time.perf_counter()+ if remain <= 0:+ rows.append({"name": e.name, "class": cls, "bytes": 0, "skipped": "budget"})+ continue+ st = bf._walk(e.path, max_depth=10, max_entries=300000, budget_s=min(4.0, remain))+ rows.append({"name": e.name, "class": cls, "bytes": st["bytes"], "files": st["files"], "truncated": st["truncated"]})+ rows.sort(key=lambda r: -r["bytes"])+ shown = 0+ for r in rows:+ if r["class"] == "custom":+ shown += 1+ if shown > 5:+ r["name"] = f"custom#{shown}"+ cls = collections.Counter(r["class"] for r in rows)+ return {"present": True, "top_dirs": [r for r in rows if r["class"] != "operator"][:12], "class_counts": dict(cls),+ "custom_root_dirs": cls.get("custom", 0), "operator_dirs_excluded": cls.get("operator", 0),+ "custom_bytes": sum(r["bytes"] for r in rows if r["class"] == "custom"),+ "total_bytes": sum(r["bytes"] for r in rows), "loose_root_files": loose,+ "truncated_dirs": sum(1 for r in rows if r.get("truncated") or r.get("skipped") == "budget")}+++@_lp("sync.other", level="L1", family=FILES, tier="T0", collect="core")+def sync_other(h, facts):+ """Sync clients: Dropbox, Nextcloud, ownCloud, Syncthing, MEGA, pCloud, Insync, onedrive (abraunegg), rclone, GOA."""+ U = _U(h)+ cands = {"dropbox": [os.path.join(U, ".dropbox")], "nextcloud": [_cfg(h, "Nextcloud")], "owncloud": [_cfg(h, "ownCloud")],+ "syncthing": [_state(h, "syncthing"), _cfg(h, "syncthing")], "mega": [_data(h, "data", "Mega Limited")],+ "pcloud": [os.path.join(U, ".pcloud")], "insync": [_data(h, "Insync"), _cfg(h, "Insync")],+ "onedrive": [_cfg(h, "onedrive")], "rclone": [_cfg(h, "rclone", "rclone.conf")],+ "gnome_online_accounts": [_cfg(h, "goa-1.0", "accounts.conf")], "kde_accounts": [_cfg(h, "libaccounts-glib", "accounts.db")],+ "google_drive_ocamlfuse": [os.path.join(U, ".gdfuse")], "proton_drive": [_cfg(h, "Proton Drive")]}+ found = [k for k, ps in cands.items() if _ex(*ps)]+ if "kde_accounts" in found:+ rows = h.sqlite(_cfg(h, "libaccounts-glib", "accounts.db"), "select count(*) from Accounts")+ if not rows or not rows[0][0]:+ found.remove("kde_accounts")+ return {"present": bool(found), "clients": found}+++# ================================================================== gaming++def _steam_root(h):+ for p in (_data(h, "Steam"), os.path.join(_U(h), ".steam", "steam"), os.path.join(_U(h), ".steam", "debian-installation"),+ _flat(h, "com.valvesoftware.Steam", ".local", "share", "Steam"), _snapu(h, "steam", "common", ".local", "share", "Steam")):+ if _isdir(os.path.join(p, "steamapps")) or os.path.isfile(os.path.join(p, "steam.sh")):+ return os.path.realpath(p)+ return None+++def _steam_lx(h):+ def load():+ sp = _steam_root(h)+ if not sp:+ return None+ libs = []+ txt = ug._read(os.path.join(sp, "steamapps", "libraryfolders.vdf"))+ if txt:+ for _k, v in (ug_games._ci(ug_games._vdf(txt), "libraryfolders") or {}).items():+ if isinstance(v, dict) and v.get("path"):+ libs.append(os.path.normpath(v["path"]))+ libs = libs or [sp]+ installed = []+ for lib in libs[:20]:+ sa = os.path.join(lib, "steamapps")+ for n in h.list_dir(sa, 2000):+ if n.startswith("appmanifest_") and n.endswith(".acf"):+ st = ug_games._ci(ug_games._vdf(ug._read(os.path.join(sa, n)) or ""), "AppState") or {}+ installed.append({"appid": int(st.get("appid", 0) or 0), "name": st.get("name"),+ "size_gb": round(int(st.get("SizeOnDisk", 0) or 0) / 1e9, 1),+ "drive": "home" if lib.startswith(_U(h)) else "other",+ "last_played": int(st.get("LastPlayed", 0) or 0)})+ ud = os.path.join(sp, "userdata")+ uids = [u for u in h.list_dir(ud, 50) if u.isdigit()]+ users = {}+ for uid in uids:+ apps = {}+ t = ug._read(os.path.join(ud, uid, "config", "localconfig.vdf"))+ if t:+ node = ug_games._ci(ug_games._vdf(t), "UserLocalConfigStore", "Software", "Valve", "Steam", "apps") or {}+ for aid, v in node.items():+ if isinstance(v, dict) and aid.isdigit() and ("Playtime" in v or "LastPlayed" in v):+ apps[int(aid)] = {"min": int(v.get("Playtime", 0) or 0), "min2wk": int(v.get("Playtime2wks", 0) or 0),+ "last": int(v.get("LastPlayed", 0) or 0)}+ users[uid] = apps+ return {"path": sp, "libs": libs, "installed": installed, "uids": uids, "users": users,+ "appinfo_path": os.path.join(sp, "appcache", "appinfo.vdf")}+ return load+++def _prime_steam(h):+ ug._cached(("steam", h.l0.get("run_id")), _steam_lx(h))+++@_lp("steam.present", level="L1", family=GAMING, tier="T0", collect="core")+def steam_present(h, facts):+ """Steam client data dir (native ~/.local/share/Steam, ~/.steam, flatpak, snap); gates the Steam subtree."""+ sp = _steam_root(h)+ if not sp:+ return None+ via = "flatpak" if "/.var/app/" in sp else "snap" if "/snap/" in sp else "native"+ return {"present": True, "via": via, "proton_prefixes": len(_ls(os.path.join(sp, "steamapps", "compatdata"), 5000) or [])}+++for _id, _fn in (("steam.installed", ug_games.steam_installed), ("steam.playtime", ug_games.steam_playtime),+ ("steam.appinfo_genres", ug_games.steam_appinfo_genres), ("steam.local_sessions", ug_games.steam_local_sessions),+ ("steam.non_steam_shortcuts", ug_games.steam_non_steam_shortcuts), ("steam.screenshots", ug_games.steam_screenshots),+ ("steam.login_users", ug_games.steam_login_users), ("steam.remote_clients", ug_games.steam_remote_clients)):+ _mirror(_id, _fn, _prime_steam)+++def _legendary_dir(h):+ return _first(_cfg(h, "heroic", "legendaryConfig", "legendary"), _cfg(h, "legendary"),+ _flat(h, "com.heroicgameslauncher.hgl", "config", "heroic", "legendaryConfig", "legendary"))+++@_lp("epic.present", level="L1", family=GAMING, tier="T0", collect="core")+def epic_present(h, facts):+ """Epic Games library via Heroic/legendary config (the Linux route to Epic)."""+ d = _legendary_dir(h)+ if not d:+ return None+ return {"present": True, "via": "heroic" if "heroic" in d else "legendary", "mtime": _mtime(d)}+++@_lp("epic.installs", level="L2", family=GAMING, tier="T0", collect="core", gate="epic.present")+def epic_installs(h, facts):+ """Epic installs from legendary installed.json: titles and GB."""+ d = _legendary_dir(h)+ j = _read_json(os.path.join(d, "installed.json")) if d else None+ if not isinstance(j, dict) or not j:+ return {"present": False}+ rows = [[v.get("title") or k, round((v.get("install_size") or 0) / 1e9, 1)] for k, v in j.items() if isinstance(v, dict)]+ rows.sort(key=lambda r: -r[1])+ return {"present": True, "count": len(rows), "total_gb": round(sum(r[1] for r in rows), 1), "manifests": rows[:20]}+++@_lp("launchers.other", level="L1", family=GAMING, tier="T0", collect="core")+def launchers_other(h, facts):+ """Linux game launchers: Heroic, Lutris, Bottles, itch, Minigalaxy, Prism/Minecraft, Wine prefix, ProtonUp-Qt."""+ U = _U(h)+ cands = {"heroic": [_cfg(h, "heroic"), _flat(h, "com.heroicgameslauncher.hgl")],+ "lutris": [_data(h, "lutris"), _cfg(h, "lutris"), _flat(h, "net.lutris.Lutris")],+ "bottles": [_data(h, "bottles"), _flat(h, "com.usebottles.bottles")], "itch": [_cfg(h, "itch")],+ "minigalaxy": [_cfg(h, "minigalaxy")], "gog_via_heroic": [_cfg(h, "heroic", "gog_store")],+ "prismlauncher": [_data(h, "PrismLauncher"), _flat(h, "org.prismlauncher.PrismLauncher")],+ "minecraft": [os.path.join(U, ".minecraft")], "wine": [os.path.join(U, ".wine")],+ "protonup_qt": [_flat(h, "net.davidotek.pupgui2"), _cfg(h, "pupgui")], "gamemode": ["/usr/bin/gamemoderun"],+ "mangohud": [_cfg(h, "MangoHud")]}+ hits = sorted(k for k, ps in cands.items() if _ex(*ps))+ return {"present": True, "launchers": hits} if hits else None+++@_lp("emulators", level="L1", family=GAMING, tier="T0", collect="core")+def emulators(h, facts):+ """Emulator config dirs (RetroArch, Ryujinx, Dolphin, PCSX2, RPCS3, Cemu, DuckStation, PPSSPP, ...), native or flatpak."""+ c = {"RetroArch": [_cfg(h, "retroarch"), _flat(h, "org.libretro.RetroArch")], "Ryujinx": [_cfg(h, "Ryujinx"), _flat(h, "org.ryujinx.Ryujinx")],+ "yuzu/suyu": [_data(h, "yuzu"), _data(h, "suyu")], "Dolphin": [_data(h, "dolphin-emu"), _flat(h, "org.DolphinEmu.dolphin-emu")],+ "PCSX2": [_cfg(h, "PCSX2"), _flat(h, "net.pcsx2.PCSX2")], "RPCS3": [_cfg(h, "rpcs3"), _flat(h, "net.rpcs3.RPCS3")],+ "Cemu": [_data(h, "Cemu"), _flat(h, "info.cemu.Cemu")], "DuckStation": [_data(h, "duckstation"), _flat(h, "org.duckstation.DuckStation")],+ "PPSSPP": [_cfg(h, "ppsspp"), _flat(h, "org.ppsspp.PPSSPP")], "xemu": [_data(h, "xemu")], "melonDS": [_cfg(h, "melonDS")]}+ hits = sorted(k for k, ps in c.items() if _ex(*ps))+ return {"present": True, "found": hits} if hits else None+++# ================================================================== media++@_lp("media.libraries", level="L1", family=MEDIA, tier="T1", collect="core")+def media_libraries(h, facts):+ """XDG Music/Videos/Pictures file counts by type and size (bounded walk), plus Screenshots count."""+ kf = bf._cached(h, "kf", _known_folders_lx)+ out = {}+ for short in ("Music", "Videos", "Pictures"):+ p = kf.get(short) or os.path.join(_U(h), short)+ s = ug_games._walk_media(p)+ s["gb"] = round(s.pop("bytes") / 1e9, 2)+ s["onedrive"] = False+ out[short] = s+ out["screenshots"] = max(h.count_dir(kf.get("Screenshots") or "", 20000), 0)+ return {"present": True, **out}+++@_lp("media.obs", level="L1", family=MEDIA, tier="T0", collect="core")+def media_obs(h, facts):+ """OBS Studio: package/flatpak install and whether a config dir exists (launched at least once)."""+ inst = [k for k, p in (("deb", "/usr/bin/obs"), ("flatpak", "/var/lib/flatpak/app/com.obsproject.Studio"),+ ("snap", "/snap/obs-studio")) if os.path.exists(p)]+ cfgs = [k for k, p in (("native", _cfg(h, "obs-studio")), ("flatpak", _flat(h, "com.obsproject.Studio", "config", "obs-studio")))+ if _isdir(p)]+ if not (inst or cfgs):+ return None+ return {"present": True, "obs_installs": inst, "obs_configs": cfgs, "config_dir": bool(cfgs),+ "obs_config_in_agent_container": 0, "streamlabs": False, "streamlabs_config": False}+++@_lp("media.players", level="L1", family=MEDIA, tier="T0", collect="core")+def media_players(h, facts):+ """Music/video players and streaming apps (Spotify, Elisa, mpv, Strawberry, Kodi, Haruna, ...), native/snap/flatpak."""+ U = _U(h)+ c = {"spotify": [_cfg(h, "spotify"), "/snap/spotify", _flat(h, "com.spotify.Client"), "/usr/share/spotify"],+ "elisa": [_cfg(h, "elisarc"), "/usr/bin/elisa"], "mpv": [_cfg(h, "mpv"), "/usr/bin/mpv"],+ "strawberry": [_cfg(h, "strawberry")], "clementine": [_cfg(h, "Clementine")], "rhythmbox": [_data(h, "rhythmbox")],+ "audacious": [_cfg(h, "audacious")], "kodi": [os.path.join(U, ".kodi")], "plex": [_data(h, "plex"), "/snap/plex-desktop"],+ "jellyfin": [_data(h, "jellyfinmediaplayer"), _flat(h, "com.github.iwalton3.jellyfin-media-player")],+ "haruna": [_cfg(h, "haruna"), "/usr/bin/haruna"], "celluloid": [_cfg(h, "celluloid")], "tidal": [_cfg(h, "tidal-hifi")],+ "youtube_music": [_cfg(h, "YouTube Music")], "smplayer": [_cfg(h, "smplayer")]}+ hits = sorted(k for k, ps in c.items() if _ex(*ps))+ return {"present": True, "players": hits} if hits else None+++def _vlc_cfg(h):+ return _first(_cfg(h, "vlc"), _snapu(h, "vlc", "common", ".config", "vlc"), _flat(h, "org.videolan.VLC", "config", "vlc"))+++@_lp("media.vlc", level="L1", family=MEDIA, tier="T0", collect="core")+def media_vlc(h, facts):+ """VLC installed (deb/snap/flatpak) and whether a user config exists."""+ inst = _ex("/usr/bin/vlc", "/snap/vlc", "/var/lib/flatpak/app/org.videolan.VLC")+ cfg = _vlc_cfg(h)+ return {"present": True, "installed": inst, "user_config": bool(cfg)} if (inst or cfg) else None+++@_lp("media.vlc_recents", level="L2", family=MEDIA, tier="T2", collect="extended", gate="media.vlc")+def media_vlc_recents(h, facts):+ """VLC recent-media count, local vs stream split and extension histogram; the MRL list itself is not emitted."""+ d = _vlc_cfg(h)+ qi = os.path.join(d, "vlc-qt-interface.conf") if d else None+ t = ug._read(qi, 2_000_000) if qi else None+ if not t:+ return {"present": False}+ m = re.search(r"^\[RecentsMRL\][^\[]*?^list=(.*)$", t, re.M | re.S)+ items = [x.strip().strip('"') for x in m.group(1).split(",") if x.strip()] if m else []+ kinds = collections.Counter("local" if x.startswith("file:") else "stream" for x in items)+ exts = collections.Counter()+ for x in items:+ if x.startswith("file:"):+ m2 = re.search(r"\.([A-Za-z0-9]{1,5})$", x.split("?")[0])+ exts["." + m2.group(1).lower() if m2 else ""] += 1+ return {"present": bool(items), "count": len(items), "kinds": dict(kinds), "ext": dict(exts), "ini_mtime": _mtime(qi)}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_system.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_system.pyindex a17f0e41279..89abf0a00f5 100644--- a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_system.py+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_system.py@@ -1,5 +1,6 @@-"""Linux system-level probes: host, identity, install_age, locale, shell_prefs, security, network,-hardware, health, usage. Signal ids match the Windows modules where Linux has a source.+"""Linux system-level probes: host, identity, install_age, locale, shell_prefs, health, usage. Security and+network live in linux_system_security, hardware in linux_system_hardware; both share this module's helpers.+Signal ids match the Windows modules where Linux has a source.Per-user rule (CONTRACT.md): only the invoking user's home is read. /etc/passwd, /etc/group, wtmp and/var/crash are system files; from them this module emits counts, or rows for the invoking user only.@@ -12,7 +13,6 @@ import ctypesimport datetime as dtimport globimport gzip-import jsonimport osimport platformimport pwd@@ -21,7 +21,7 @@ import grpimport threadingimport time-from userscan.registry import probe+from ..registry import probeOS = "linux"@@ -751,21 +751,17 @@ _IMPERIAL = ("US", "LR", "MM")@lp("locale.user", level="L1", family="locale")def locale_user(h, facts):"""User format locale (Plasma Formats, then /etc/default/locale, then env) with date/time formats."""- import locale as _localechosen, src = _user_locale()if not chosen:return Noned = {"present": True, "locale": _bcp47(chosen), "LocaleName": _bcp47(chosen), "raw": chosen, "sources": src}- try:- old = _locale.setlocale(_locale.LC_TIME)- try:- _locale.setlocale(_locale.LC_TIME, chosen)- d["short_date"] = _locale.nl_langinfo(_locale.D_FMT)- d["time_format"] = _locale.nl_langinfo(_locale.T_FMT)- finally:- _locale.setlocale(_locale.LC_TIME, old)- except (_locale.Error, AttributeError):- pass+ # A child reads the formats: setlocale() is process-wide and this can run inside the Hermes+ # backend. `locale` falls back to C formats for a locale that is not installed, so check first.+ norm = lambda s: s.strip().lower().replace("-", "")+ if norm(chosen) in {norm(n) for n in (h.run(["locale", "-a"]) or "").splitlines()}:+ fmts = (h.run(["locale", "d_fmt", "t_fmt"], env={"LC_ALL": chosen}) or "").splitlines()+ if len(fmts) == 2:+ d["short_date"], d["time_format"] = fmtstf = d.get("time_format") or ""d["clock_24h"] = ("%H" in tf or "%T" in tf) if tf else Nonecountry = (d["locale"] or "").split("-")[-1]@@ -977,782 +973,6 @@ def desktop_env(h, facts):"plasma": os.path.exists("/usr/bin/plasmashell"), "gnome": os.path.exists("/usr/bin/gnome-shell")}-# ================================================================ security--def _sshd_directives():- out, unreadable = {}, 0- files = ["/etc/ssh/sshd_config"] + sorted(glob.glob("/etc/ssh/sshd_config.d/*.conf"))[:50]- for p in files:- txt = _read(p, 200_000)- if txt is None:- unreadable += os.path.exists(p)- continue- for line in txt.splitlines()[:2000]:- parts = line.strip().split(None, 1)- if not parts or parts[0].startswith("#"):- continue- k = parts[0].lower()- if k in ("port", "passwordauthentication", "pubkeyauthentication", "permitrootlogin",- "kbdinteractiveauthentication", "x11forwarding", "usepam"):- out.setdefault(k, parts[1] if len(parts) > 1 else "")- elif k in ("allowusers", "allowgroups", "match", "denyusers"):- out[k] = "<set>"- return out, len(files), unreadable---@lp("security.openssh_server", level="L1", family="security", tier="T3")-def openssh_server(h, facts):- """sshd installed and enabled (ssh.service/ssh.socket wants-links), non-secret sshd_config directives."""- exe = _which("sshd")- if not exe:- return None- en = _enabled_units()- d, nfiles, unreadable = _sshd_directives()- svc = "ssh.service" in en or "sshd.service" in en- sock = "ssh.socket" in en- return {"present": True, "installed": True, "sshd_auto": svc or sock, "service_enabled": svc, "socket_enabled": sock,- "sshd_config": d, "config_files": nfiles, "config_files_unreadable": unreadable}---@lp("dev.ssh_dir_presence", level="L1", family="security", tier="T3")-def ssh_dir_presence(h, facts):- """~/.ssh file kinds by name/stat only (keys never opened); known_hosts line count, config Host count."""- d = os.path.join(_home(), ".ssh")- names = h.list_dir(d, 200)- if not names:- return None- pub = [n for n in names if n.endswith(".pub")]- priv = [n for n in names if n.startswith("id_") and not n.endswith(".pub")]- out = {"present": True, "files": len(names), "private_keys": len(priv), "public_keys": len(pub),- "config": os.path.exists(os.path.join(d, "config")),- "authorized_keys": h.meta(os.path.join(d, "authorized_keys")).get("bytes"),- "known_hosts_lines": None, "config_host_entries": None, "agent_socket": bool(os.environ.get("SSH_AUTH_SOCK"))}- try:- with open(os.path.join(d, "known_hosts"), "rb") as f:- out["known_hosts_lines"] = sum(1 for ln in f if ln.strip())- except OSError:- pass- hosts = _ssh_hosts()- if hosts is not None:- out["config_host_entries"] = len(hosts)- return out---def _ssh_hosts():- """Host aliases from ~/.ssh/config and ~/.ssh/config.d/*; wildcard patterns dropped; no other keys read."""- d = os.path.join(_home(), ".ssh")- files = [os.path.join(d, "config")] + sorted(glob.glob(os.path.join(d, "config.d", "*")))[:20]- seen, any_file = [], False- for p in files:- txt = _read(p, 500_000)- if txt is None:- continue- any_file = True- for line in txt.splitlines()[:5000]:- m = re.match(r"\s*Host\s+(.+)", line, re.I)- if m:- for a in m.group(1).split():- if not any(c in a for c in "*?!") and a not in seen:- seen.append(a)- return seen if any_file else None---@lp("security.ssh_config_hosts", level="L2", family="security", tier="T2", gate="dev.ssh_dir_presence")-def ssh_config_hosts(h, facts):- """ssh config Host aliases (names only; HostName/User/IdentityFile never read). T2: machine names."""- hosts = _ssh_hosts()- if not hosts:- return None- return {"present": True, "count": len(hosts), "aliases": hosts[:50]}---@lp("security.firewall", level="L1", family="security")-def security_firewall(h, facts):- """Host firewall: ufw ENABLED in ufw.conf, firewalld/nftables/iptables-persistent enabled."""- en = _enabled_units()- ufw_conf = _kv(_read("/etc/ufw/ufw.conf") or "")- out = {"ufw_installed": os.path.exists("/usr/sbin/ufw"), "ufw": ufw_conf.get("ENABLED") == "yes" if ufw_conf else None,- "firewalld": "firewalld.service" in en, "nftables": "nftables.service" in en,- "iptables_persistent": "netfilter-persistent.service" in en}- out["present"] = any(v for v in out.values())- out["all_on"] = bool(out["ufw"] or out["firewalld"] or out["nftables"] or out["iptables_persistent"])- return out---@lp("security.secureboot", level="L1", family="security")-def security_secureboot(h, facts):- """UEFI boot and Secure Boot state from efivars (SecureBoot, SetupMode)."""- uefi = os.path.isdir("/sys/firmware/efi")- sb = None- for p in glob.glob("/sys/firmware/efi/efivars/SecureBoot-*")[:1]:- try:- with open(p, "rb") as f:- b = f.read(5)- sb = len(b) == 5 and b[4] == 1- except OSError:- pass- return {"present": True, "uefi": uefi, "secure_boot": sb, "enabled": bool(sb),- "mok_enrolled": os.path.exists("/var/lib/shim-signed/mok/MOK.der")}---@lp("security.uac", level="L1", family="security")-def security_uac(h, facts):- """Elevation path: invoking user in sudo/admin/wheel, sudoers.d drop-ins count, polkit rules count."""- try:- groups = sorted({grp.getgrgid(g).gr_name for g in os.getgroups()})- except KeyError:- groups = []- admin = [g for g in groups if g in ("sudo", "admin", "wheel", "root")]- return {"present": True, "mechanism": "sudo" if _which("sudo") else None, "in_admin_group": bool(admin),- "admin_groups": admin, "is_root": os.geteuid() == 0,- "sudo_used_before": os.path.exists(os.path.join(_home(), ".sudo_as_admin_successful")),- "sudoers_d_files": len([n for n in h.list_dir("/etc/sudoers.d", 200) if n != "README"]),- "polkit_rules": len(h.list_dir("/etc/polkit-1/rules.d", 200)),- "other_groups": [g for g in groups if g in ("docker", "lxd", "libvirt", "kvm", "adm", "wireshark")]}---@lp("security.sudo_nopasswd", level="L2", family="security", gate="security.uac", collect="extended")-def sudo_nopasswd(h, facts):- """sudo -n -l classification: password required / NOPASSWD rules / not allowed. Commands never emitted.- Side effect: when a password is required sudo logs one auth-log line per run; skipped for non-admins."""- uac = _fv(facts, "security.uac") or {}- if not _which("sudo") or not uac.get("in_admin_group"):- return None- out = _run(h, ["sudo", "-n", "-l"], 3000)- if out is None:- return {"present": True, "result": "error"}- low = out.lower()- if "a password is required" in low or not out.strip():- res = "password_required"- elif "may not run sudo" in low or "not allowed" in low:- res = "not_allowed"- else:- res = "listed"- nop = len(re.findall(r"NOPASSWD:", out))- nop_all = bool(re.search(r"NOPASSWD:\s*ALL\b", out))- return {"present": True, "result": res, "nopasswd_rules": nop, "nopasswd_all": nop_all}---@lp("acct.admins", level="L2", family="security", gate="security.uac")-def acct_admins(h, facts):- """Members of sudo/admin/wheel from /etc/group (counts only; names never emitted)."""- out = {}- for g in ("sudo", "admin", "wheel"):- try:- out[g] = len(grp.getgrnam(g).gr_mem)- except KeyError:- continue- if not out:- return None- return {"present": True, "members": out, "count": max(out.values())}---@lp("security.telemetry", level="L1", family="security")-def security_telemetry(h, facts):- """Crash/usage reporting: apport enabled flag, whoopsie, popularity-contest, ubuntu-report consent file."""- ap = _kv(_read("/etc/default/apport") or "")- pop = _kv(_read("/etc/popularity-contest.conf") or "")- en = _enabled_units()- apport_on = ap.get("enabled") == "1" if ap else None- return {"present": True, "apport_enabled": apport_on, "whoopsie": "whoopsie.service" in en,- "popcon": pop.get("PARTICIPATE") == "yes" if pop else None,- "ubuntu_report_file": os.path.isdir(os.path.join(_home(), ".cache/ubuntu-report")),- "ubuntu_pro_status_file": os.path.exists("/var/lib/ubuntu-advantage/status.json"),- "reduced": apport_on is False}---_REMOTE = {"xrdp": ["/usr/sbin/xrdp"], "krdp": ["/usr/bin/krdpserver"], "gnome-remote-desktop": ["/usr/libexec/gnome-remote-desktop-daemon"],- "krfb": ["/usr/bin/krfb"], "x11vnc": ["/usr/bin/x11vnc"], "tigervnc": ["/usr/bin/x0vncserver", "/usr/bin/Xtigervnc"],- "anydesk": ["/usr/bin/anydesk"], "teamviewer": ["/opt/teamviewer"], "rustdesk": ["/usr/bin/rustdesk"],- "sunshine": ["/usr/bin/sunshine"], "nomachine": ["/usr/NX"], "parsec": ["/usr/bin/parsecd"],- "chrome-remote-desktop": ["/opt/google/chrome-remote-desktop"], "et": ["/usr/bin/etserver"],- "mosh": ["/usr/bin/mosh-server"]}---@lp("security.rdp", level="L1", family="security")-def security_rdp(h, facts):- """RDP server (xrdp / KDE krdp / gnome-remote-desktop) installed and enabled."""- en = _enabled_units()- inst = [k for k in ("xrdp", "krdp", "gnome-remote-desktop") if any(os.path.exists(p) for p in _REMOTE[k])]- enabled = "xrdp.service" in en- return {"present": True, "installed": inst, "rdp_enabled": enabled or None}---@lp("security.remote_tools", level="L1", family="security")-def security_remote_tools(h, facts):- """Remote access tools present: VNC servers, AnyDesk, TeamViewer, RustDesk, Sunshine, EternalTerminal, mosh."""- found = sorted(k for k, ps in _REMOTE.items() if any(os.path.exists(p) for p in ps))- vnc_dir = h.meta(os.path.join(_home(), ".vnc"))- return {"present": True, "tools": found, "count": len(found), "user_vnc_dir": vnc_dir.get("present", False),- "user_vnc_passwd_bytes": h.meta(os.path.join(_home(), ".vnc/passwd")).get("bytes")}---@lp("security.apparmor", level="L1", family="security")-def security_apparmor(h, facts):- """Active LSMs (AppArmor/SELinux), kernel lockdown mode."""- lsm = (_read1("/sys/kernel/security/lsm") or "").split(",")- aa = _read1("/sys/module/apparmor/parameters/enabled")- lock = _read1("/sys/kernel/security/lockdown")- m = re.search(r"\[(\w+)\]", lock or "")- return {"present": True, "lsm": [x for x in lsm if x], "apparmor": aa == "Y" if aa else "apparmor" in lsm,- "selinux": "selinux" in lsm, "lockdown": m.group(1) if m else None,- "apparmor_profiles_dir": len(h.list_dir("/etc/apparmor.d", 2000))}---@lp("security.bitlocker", level="L1", family="security")-def security_disk_encryption(h, facts):- """Disk encryption (Linux: LUKS dm-crypt mappings from /sys/block/dm-*/dm/uuid; BitLocker equivalent)."""- crypt = 0- for u in glob.glob("/sys/block/dm-*/dm/uuid")[:200]:- if (_read1(u) or "").startswith("CRYPT-"):- crypt += 1- return {"present": True, "mechanism": "luks", "encrypted_volumes": crypt, "any_encrypted": crypt > 0,- "crypttab_lines": sum(1 for l in (_read("/etc/crypttab") or "").splitlines() if l.strip() and not l.startswith("#"))}---@lp("security.tpm", level="L1", family="security")-def security_tpm(h, facts):- """TPM present (/sys/class/tpm) and its major version; resource manager device for the user."""- devs = [n for n in h.list_dir("/sys/class/tpm", 10) if n.startswith("tpm")]- if not devs:- return {"present": False, "tpm": False}- ver = _read1(f"/sys/class/tpm/{devs[0]}/tpm_version_major")- return {"present": True, "tpm": True, "version": ver, "rm_device": os.path.exists("/dev/tpmrm0")}---@lp("acct.autologon", level="L1", family="security")-def acct_autologon(h, facts):- """Display-manager autologin (sddm/gdm/lightdm) and whether it logs in the invoking user. No names."""- me = _me()- user, dm = None, None- for p in ["/etc/sddm.conf"] + sorted(glob.glob("/etc/sddm.conf.d/*.conf")):- sec = _ini(_read(p) or "").get("Autologin") or {}- if sec.get("User"):- user, dm = sec["User"], "sddm"- g = _ini(_read("/etc/gdm3/custom.conf") or "").get("daemon") or {}- if g.get("AutomaticLoginEnable", "").lower() == "true":- user, dm = g.get("AutomaticLogin"), "gdm"- for p in ["/etc/lightdm/lightdm.conf"] + sorted(glob.glob("/etc/lightdm/lightdm.conf.d/*.conf")):- for s in _ini(_read(p) or "").values():- if s.get("autologin-user"):- user, dm = s["autologin-user"], "lightdm"- return {"present": True, "enabled": bool(user), "display_manager": dm,- "is_current_user": bool(user and me and user == me.pw_name)}---_PM = {"KeePassXC": ["/usr/bin/keepassxc", "~/.config/keepassxc"], "Bitwarden": ["/usr/bin/bitwarden", "/opt/Bitwarden", "~/.config/Bitwarden"],- "1Password": ["/opt/1Password", "/usr/bin/1password"], "Proton Pass": ["/usr/bin/proton-pass", "/opt/proton-pass"],- "Enpass": ["/opt/enpass"], "pass": ["~/.password-store"], "gopass": ["/usr/bin/gopass", "~/.config/gopass"],- "KWallet": ["~/.local/share/kwalletd"], "GNOME Keyring": ["~/.local/share/keyrings"]}---@lp("pm.desktop", level="L1", family="security")-def pm_desktop(h, facts):- """Password managers and OS keyrings by path presence (vault/keyring files never opened)."""- found = sorted(k for k, ps in _PM.items() if any(os.path.exists(os.path.expanduser(p)) for p in ps))- managers = [f for f in found if f not in ("KWallet", "GNOME Keyring")]- keyrings = [f for f in found if f not in managers]- return {"present": bool(managers or keyrings), "managers": managers, "keyrings": keyrings,- "count": len(managers)}---@lp("security.av_products", level="L2", family="security", gate="security.uac")-def av_products(h, facts):- """Anti-malware / EDR agents by path: ClamAV, Sophos, CrowdStrike, SentinelOne, Defender for Endpoint, Wazuh."""- paths = {"clamav": "/usr/bin/clamscan", "sophos": "/opt/sophos-spl", "crowdstrike": "/opt/CrowdStrike",- "sentinelone": "/opt/sentinelone", "mdatp": "/opt/microsoft/mdatp", "wazuh": "/var/ossec",- "rkhunter": "/usr/bin/rkhunter", "chkrootkit": "/usr/sbin/chkrootkit", "fail2ban": "/usr/bin/fail2ban-server"}- found = sorted(k for k, p in paths.items() if os.path.exists(p))- return {"present": True, "products": found, "count": len(found)}---_NOTABLE_SVC = ("ssh", "tailscaled", "docker", "containerd", "xrdp", "cups", "bluetooth", "avahi-daemon", "ufw",- "apparmor", "snapd", "libvirtd", "sddm", "gdm", "lightdm", "NetworkManager", "systemd-networkd",- "unattended-upgrades", "fail2ban", "nginx", "apache2", "caddy", "postgresql", "mysql", "mariadb",- "redis-server", "ollama", "smbd", "nfs-server", "cockpit", "zerotier-one", "wg-quick@wg0", "k3s",- "nvidia-persistenced", "power-profiles-daemon", "tlp", "thermald")---@lp("security.services_state", level="L2", family="security", gate="host.systemd", collect="extended")-def services_state(h, facts):- """systemd unit counts: enabled services/timers/sockets, failed units, notable services enabled/active."""- txt = _run(h, ["systemctl", "list-unit-files", "--no-legend", "--no-pager", "--type=service,timer,socket"], 4000) or ""- by = collections.Counter()- enabled = set()- for line in txt.splitlines()[:5000]:- p = line.split()- if len(p) >= 2:- kind = p[0].rsplit(".", 1)[-1]- by[f"{kind}:{p[1]}"] += 1- if p[1] == "enabled":- enabled.add(p[0].rsplit(".", 1)[0])- failed = _run(h, ["systemctl", "list-units", "--no-legend", "--no-pager", "--state=failed", "--plain"], 3000) or ""- act = _run(h, ["systemctl", "list-units", "--no-legend", "--no-pager", "--type=service", "--state=running", "--plain"], 3000) or ""- running = {l.split()[0].rsplit(".", 1)[0] for l in act.splitlines() if l.strip()}- if not by:- return None- return {"present": True, "unit_files": sum(by.values()), "by_kind_state": dict(sorted(by.items())),- "enabled_services": by.get("service:enabled", 0), "running_services": len(running),- "failed_units": sum(1 for l in failed.splitlines() if l.strip()),- "notable_enabled": sorted(s for s in _NOTABLE_SVC if s in enabled),- "notable_running": sorted(s for s in _NOTABLE_SVC if s in running)}---@lp("security.cert_roots", level="L2", family="security", gate="os.edition", collect="extended")-def cert_roots(h, facts):- """Locally added CA certificates (/usr/local/share/ca-certificates) vs system bundle size."""- local = [n for n in h.list_dir("/usr/local/share/ca-certificates", 500)]- return {"present": True, "local_added": len(local), "etc_ssl_certs": max(h.count_dir("/etc/ssl/certs", 5000), 0)}---# ================================================================ network--_PROXY_ENV = ("http_proxy", "https_proxy", "all_proxy", "no_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY")---@lp("net.hosts_proxy", level="L1", family="network")-def net_hosts_proxy(h, facts):- """/etc/hosts custom entries count, proxy variables set (names only), apt proxy config."""- lines = [l.split("#")[0].split() for l in (_read("/etc/hosts") or "").splitlines()]- lines = [l for l in lines if len(l) >= 2]- default = {"localhost", "ip6-localhost", "ip6-loopback", "ip6-allnodes", "ip6-allrouters", "ip6-localnet",- "ip6-mcastprefix", os.uname().nodename}- custom = [l for l in lines if not set(l[1:]) <= default and not l[0].startswith(("127.0.1.1", "::1", "fe00", "ff0"))]- envf = _kv(_read("/etc/environment") or "")- apt_proxy = any("proxy" in n.lower() for n in h.list_dir("/etc/apt/apt.conf.d", 200))- return {"present": True, "hosts_custom_entries": len(custom), "hosts_entries": len(lines),- "proxy_env": sorted({k.lower() for k in _PROXY_ENV if os.environ.get(k)}),- "proxy_etc_environment": sorted({k.lower() for k in envf if k in _PROXY_ENV}), "apt_proxy": apt_proxy}---_VPN_BINS = {"tailscale": "tailscale", "wireguard": "wg", "openvpn": "openvpn", "zerotier": "zerotier-cli",- "cloudflare-warp": "warp-cli", "netbird": "netbird", "mullvad": "mullvad", "nordvpn": "nordvpn",- "protonvpn": "protonvpn-cli", "expressvpn": "expressvpn", "headscale": "headscale", "nebula": "nebula"}---@lp("net.vpn_clients", level="L1", family="network")-def vpn_clients(h, facts):- """VPN/mesh clients by binary and enabled systemd service (tailscaled, wg-quick@, openvpn@, zerotier-one...)."""- found = sorted(k for k, b in _VPN_BINS.items() if _which(b))- en = _enabled_units()- svc = sorted(u for u in en if re.match(r"(tailscaled|wg-quick@|openvpn|zerotier-one|warp-svc|netbird|mullvad)", u))- return {"present": True, "clients": found, "dirs": found, "services": svc, "count": len(found),- "wireguard_dir": os.path.isdir("/etc/wireguard")}---@lp("net.networkmanager", level="L1", family="network")-def net_networkmanager(h, facts):- """Network stack: NetworkManager / systemd-networkd / netplan, profile file count (names never emitted)."""- en = _enabled_units()- nm = os.path.exists("/usr/sbin/NetworkManager")- files = h.list_dir("/etc/NetworkManager/system-connections", 2000)- netplan = [n for n in h.list_dir("/etc/netplan", 100) if n.endswith(".yaml")]- if not nm and not netplan and "systemd-networkd.service" not in en:- return None- return {"present": True, "networkmanager": nm, "nm_enabled": "NetworkManager.service" in en,- "nm_profile_files": len(files), "networkd_enabled": "systemd-networkd.service" in en,- "netplan_files": len(netplan)}---@lp("net.wifi_profiles", level="L2", family="network", gate="net.networkmanager")-def wifi_profiles(h, facts):- """Saved Wi-Fi profile count from nmcli TYPE column; SSIDs never read."""- rows = _nm_profiles(h)- if rows is None:- return None- n = sum(1 for r in rows if _nm_kind(r["type"]) == "wireless")- wifi_hw = any(os.path.isdir(os.path.join("/sys/class/net", i, "wireless")) for i in h.list_dir("/sys/class/net", 100))- return {"present": True, "count": n, "wifi_hardware": wifi_hw}---@lp("net.connection_profiles", level="L2", family="network", gate="net.networkmanager", collect="extended")-def connection_profiles(h, facts):- """NetworkManager profiles by kind and autoconnect count (names never requested)."""- rows = _nm_profiles(h)- if not rows:- return None- return {"present": True, "count": len(rows), "by_kind": dict(collections.Counter(_nm_kind(r["type"]) for r in rows)),- "autoconnect": sum(1 for r in rows if r["autoconnect"])}---def _if_kind(name):- base = os.path.join("/sys/class/net", name)- if name == "lo":- return "loopback"- if os.path.isdir(os.path.join(base, "wireless")) or os.path.exists(os.path.join(base, "phy80211")):- return "wifi"- if name.startswith(("tailscale", "wg", "tun", "zt", "nb-")):- return "tunnel"- if name.startswith(("docker", "br-", "veth", "virbr", "lxc", "lxd", "cni", "flannel", "vnet")) or \- os.path.isdir(os.path.join(base, "bridge")):- return "virtual"- if name.startswith(("wwan", "ww")):- return "mobile"- if os.path.exists(os.path.join(base, "device")):- return "ethernet"- return "other"---@lp("net.adapters", level="L2", family="network", gate="net.hosts_proxy", collect="extended")-def net_adapters(h, facts):- """Network interfaces from /sys/class/net: count by kind, up count, physical link speeds."""- kinds, up, speeds = collections.Counter(), collections.Counter(), []- for n in h.list_dir("/sys/class/net", 500):- k = _if_kind(n)- kinds[k] += 1- if _read1(os.path.join("/sys/class/net", n, "operstate")) == "up":- up[k] += 1- if k in ("ethernet", "wifi"):- s = _read1(os.path.join("/sys/class/net", n, "speed"))- if s and s.lstrip("-").isdigit() and int(s) > 0:- speeds.append(int(s))- if not kinds:- return None- return {"present": True, "by_kind": dict(kinds), "up_by_kind": dict(up), "link_speeds_mbps": sorted(speeds)}---@lp("net.dns", level="L2", family="network", gate="net.hosts_proxy", collect="extended")-def net_dns(h, facts):- """Resolver: resolv.conf nameserver count, systemd-resolved stub, Tailscale MagicDNS server, custom upstreams."""- rc = _read("/etc/resolv.conf") or ""- ns = re.findall(r"^\s*nameserver\s+(\S+)", rc, re.M)- stub = "127.0.0.53" in ns- try:- resolved = "systemd/resolve" in os.readlink("/etc/resolv.conf")- except OSError:- resolved = False- ups = []- if stub and _which("resolvectl"):- out = _run(h, ["resolvectl", "dns"], 2000) or ""- ups = re.findall(r"(\d+\.\d+\.\d+\.\d+|[0-9a-f:]{6,})", out)- public = {"1.1.1.1": "cloudflare", "1.0.0.1": "cloudflare", "8.8.8.8": "google", "8.8.4.4": "google",- "9.9.9.9": "quad9", "208.67.222.222": "opendns"}- return {"present": bool(ns), "nameservers": len(ns), "resolved_stub": stub, "resolved_managed": resolved,- "upstreams": len(set(ups)), "magicdns": "100.100.100.100" in ups or "100.100.100.100" in ns,- "public_resolvers": sorted({public[u] for u in set(ups) | set(ns) if u in public}),- "search_domains": len(re.findall(r"^\s*search\s+(.+)", rc, re.M))}---@lp("net.tailscale", level="L2", family="network", tier="T1", gate="net.vpn_clients", collect="extended")-def net_tailscale(h, facts):- """Tailscale state via 'tailscale status --json': peer counts by OS and online count; peer names never emitted."""- exe = _which("tailscale")- if not exe:- return None- out = _run(h, [exe, "status", "--json"], 3000)- try:- j = json.loads(out) if out else None- except ValueError:- j = None- if not isinstance(j, dict):- return {"present": True, "status": "unparsed"}- peers = list((j.get("Peer") or {}).values())- by_os = collections.Counter(p.get("OS") or "?" for p in peers)- return {"present": True, "version": (j.get("Version") or "").split("-")[0], "backend": j.get("BackendState"),- "peers": len(peers), "online": sum(1 for p in peers if p.get("Online")), "peers_by_os": dict(by_os),- "exit_node_in_use": any(p.get("ExitNode") for p in peers),- "magicdns": bool((j.get("CurrentTailnet") or {}).get("MagicDNSEnabled"))}---# ================================================================ hardware--_CHASSIS = {1: "other", 2: "unknown", 3: "desktop", 4: "low-profile desktop", 6: "mini tower", 7: "tower",- 8: "portable", 9: "laptop", 10: "notebook", 13: "all-in-one", 14: "sub-notebook", 17: "main server chassis",- 23: "rack mount", 30: "tablet", 31: "convertible", 32: "detachable", 35: "mini pc", 36: "stick pc"}---def _meminfo():- out = {}- for line in (_read("/proc/meminfo") or "").splitlines():- p = line.split()- if len(p) >= 2 and p[1].isdigit():- out[p[0].rstrip(":")] = int(p[1]) * 1024- return out---_REAL_FS = {"ext4", "ext3", "ext2", "xfs", "btrfs", "zfs", "f2fs", "vfat", "exfat", "ntfs", "ntfs3", "fuseblk", "bcachefs"}---def _volumes():- vols, seen = [], set()- for line in (_read("/proc/mounts") or "").splitlines()[:2000]:- p = line.split()- if len(p) < 3 or p[2] not in _REAL_FS or p[0] in seen:- continue- seen.add(p[0])- mp = p[1].replace("\\040", " ")- try:- st = os.statvfs(mp)- except OSError:- continue- size = st.f_blocks * st.f_frsize- if size <= 0:- continue- free = st.f_bavail * st.f_frsize- vols.append({"name": mp, "fstype": p[2], "size_gb": round(size / 1e9, 1), "free_gb": round(free / 1e9, 1),- "free_pct": round(100 * free / size, 1)})- return vols---@lp("hw.system", level="L1", family="hardware")-def hw_system(h, facts):- """DMI system/board/BIOS, chassis type, visible RAM, fixed volumes with free space."""- d = "/sys/class/dmi/id"- r = lambda n: _read1(os.path.join(d, n)) or None- mi = _meminfo()- ct = r("chassis_type")- ram = round(mi.get("MemTotal", 0) / 2 ** 30, 1) or None- vols = _volumes()- return {"present": True, "manufacturer": r("sys_vendor"), "product": r("product_name"), "family": r("product_family"),- "version": r("product_version"), "board_vendor": r("board_vendor"), "board": r("board_name"),- "bios_vendor": r("bios_vendor"), "bios_version": r("bios_version"), "bios_date": r("bios_date"),- "chassis": _CHASSIS.get(int(ct), ct) if ct and ct.isdigit() else ct, "visible_ram_gb": ram,- "memory_load_pct": round(100 * (1 - mi["MemAvailable"] / mi["MemTotal"])) if mi.get("MemTotal") and "MemAvailable" in mi else None,- "fixed_drives_total_free_gb_pct": [[v["name"], v["size_gb"], v["free_gb"], v["free_pct"]] for v in vols]}---@lp("hw.ram", level="L1", family="hardware")-def hw_ram(h, facts):- """RAM and swap from /proc/meminfo (module count and speed need root dmidecode: not collected)."""- mi = _meminfo()- if not mi.get("MemTotal"):- return None- return {"present": True, "total_gb": round(mi["MemTotal"] / 2 ** 30, 1),- "available_gb": round(mi.get("MemAvailable", 0) / 2 ** 30, 1),- "swap_gb": round(mi.get("SwapTotal", 0) / 2 ** 30, 1), "swap_used_gb": round((mi.get("SwapTotal", 0) - mi.get("SwapFree", 0)) / 2 ** 30, 1),- "zram": any(n.startswith("zram") for n in h.list_dir("/sys/block", 500))}---@lp("hw.disks", level="L2", family="hardware", gate="hw.system")-def hw_disks(h, facts):- """Physical disks (lsblk: size, rotational, transport, model, LUKS) and mounted volumes with free space."""- disks = []- out = _run(h, ["lsblk", "-J", "-b", "-d", "-o", "NAME,TYPE,SIZE,ROTA,RM,TRAN,MODEL"], 3000) if _which("lsblk") else None- try:- for b in (json.loads(out).get("blockdevices") or []) if out else []:- if b.get("type") != "disk" or str(b.get("name", "")).startswith(("loop", "zram", "ram")):- continue- disks.append({"name": b.get("name"), "size_gb": round(int(b.get("size") or 0) / 1e9, 1),- "ssd": not _truthy_flag(b.get("rota")), "removable": _truthy_flag(b.get("rm")),- "transport": b.get("tran"), "model": (b.get("model") or "").strip() or None})- except (ValueError, AttributeError):- disks = []- if not disks:- for n in h.list_dir("/sys/block", 200):- if n.startswith(("loop", "zram", "ram", "dm-", "md", "sr")):- continue- sz = _read1(f"/sys/block/{n}/size")- disks.append({"name": n, "size_gb": round(int(sz) * 512 / 1e9, 1) if sz and sz.isdigit() else None,- "ssd": _read1(f"/sys/block/{n}/queue/rotational") == "0",- "removable": _read1(f"/sys/block/{n}/removable") == "1",- "model": _read1(f"/sys/block/{n}/device/model")})- vols = _volumes()- return {"present": bool(disks or vols), "disks": disks, "volumes": vols,- "virtio": any(d.get("transport") == "virtio" or str(d.get("name", "")).startswith("vd") for d in disks)}---def _truthy_flag(v):- return v in (True, 1, "1", "true")---@lp("hw.cpu", level="L2", family="hardware", gate="hw.system")-def hw_cpu(h, facts):- """CPU model, vendor, sockets/cores/threads, max MHz, virtualization from lscpu -J (cpuinfo fallback)."""- out = _run(h, ["lscpu", "-J"], 3000) if _which("lscpu") else None- f = {}- try:- for e in (json.loads(out).get("lscpu") or []) if out else []:- f[e.get("field", "").rstrip(":")] = e.get("data")- for c in e.get("children") or []:- f[c.get("field", "").rstrip(":")] = c.get("data")- except (ValueError, AttributeError):- f = {}- if not f:- ci = _read("/proc/cpuinfo", 1 << 20) or ""- m = re.search(r"^model name\s*:\s*(.+)$", ci, re.M)- return {"present": bool(ci), "name": m.group(1).strip() if m else None,- "logical_processors": len(re.findall(r"^processor\s*:", ci, re.M)), "via": "cpuinfo"}- num = lambda k: int(f[k]) if str(f.get(k, "")).isdigit() else None- return {"present": True, "name": f.get("Model name"), "vendor": f.get("Vendor ID"),- "logical_processors": num("CPU(s)"), "sockets": num("Socket(s)"), "cores_per_socket": num("Core(s) per socket"),- "threads_per_core": num("Thread(s) per core"), "max_mhz": f.get("CPU max MHz"),- "virtualization": f.get("Virtualization"), "hypervisor": f.get("Hypervisor vendor"),- "virt_type": f.get("Virtualization type"), "native_arch": _ARCH.get(os.uname().machine, os.uname().machine)}---_PCI_VENDOR = {"0x10de": "NVIDIA", "0x1002": "AMD", "0x8086": "Intel", "0x1af4": "Red Hat (virtio)", "0x1234": "QEMU",- "0x15ad": "VMware", "0x80ee": "VirtualBox", "0x1414": "Microsoft", "0x1a03": "ASPEED", "0x5143": "Qualcomm"}---@lp("hw.gpu", level="L2", family="hardware", gate="hw.system")-def hw_gpu(h, facts):- """Display adapters: PCI class 03 devices from sysfs (vendor, driver, VRAM for amdgpu), names from lspci -mm."""- adapters = []- for dev in glob.glob("/sys/bus/pci/devices/*")[:512]:- cls = _read1(os.path.join(dev, "class")) or ""- if not cls.startswith("0x03"):- continue- ven = _read1(os.path.join(dev, "vendor")) or ""- drv = None- try:- drv = os.path.basename(os.readlink(os.path.join(dev, "driver")))- except OSError:- pass- vram = _read1(os.path.join(dev, "mem_info_vram_total"))- adapters.append({"slot": os.path.basename(dev), "vendor": _PCI_VENDOR.get(ven, ven), "device_id": _read1(os.path.join(dev, "device")),- "driver": drv, "boot_vga": _read1(os.path.join(dev, "boot_vga")) == "1",- "vram_gb": round(int(vram) / 2 ** 30, 1) if vram and vram.isdigit() else None, "name": None})- if adapters and _which("lspci"):- out = _run(h, ["lspci", "-mm", "-D"], 2000) or ""- for line in out.splitlines():- m = re.match(r'(\S+) "([^"]*)" "([^"]*)" "([^"]*)"', line)- if m:- for a in adapters:- if a["slot"] == m.group(1):- a["name"] = f"{m.group(3)} {m.group(4)}".strip()- if not adapters:- return None- virtual = [a for a in adapters if a["vendor"] in ("Red Hat (virtio)", "QEMU", "VMware", "VirtualBox", "Microsoft")]- real = [a for a in adapters if a not in virtual]- vr = [a["vram_gb"] for a in real if a["vram_gb"]]- return {"present": True, "max_vram_gb": max(vr) if vr else None, "adapters": real, "virtual_adapters": virtual,- "other": len(virtual), "nvidia": any(a["vendor"] == "NVIDIA" for a in real)}---@lp("hw.battery", level="L1", family="hardware")-def hw_battery(h, facts):- """Battery present in /sys/class/power_supply: laptop vs desktop, charge, wear."""- for n in h.list_dir("/sys/class/power_supply", 50):- b = os.path.join("/sys/class/power_supply", n)- if _read1(os.path.join(b, "type")) != "Battery" or _read1(os.path.join(b, "scope")) == "Device":- continue- full = _read1(os.path.join(b, "energy_full")) or _read1(os.path.join(b, "charge_full"))- design = _read1(os.path.join(b, "energy_full_design")) or _read1(os.path.join(b, "charge_full_design"))- wear = round(100 * int(full) / int(design), 1) if full and design and full.isdigit() and design.isdigit() and int(design) else None- ac = [_read1(os.path.join("/sys/class/power_supply", m, "online")) for m in h.list_dir("/sys/class/power_supply", 50)- if _read1(os.path.join("/sys/class/power_supply", m, "type")) == "Mains"]- cap = _read1(os.path.join(b, "capacity"))- return {"present": True, "on_ac": "1" in ac if ac else None, "charge_pct": int(cap) if cap and cap.isdigit() else None,- "status": _read1(os.path.join(b, "status")), "health_pct": wear,- "cycle_count": _read1(os.path.join(b, "cycle_count"))}- return None---@lp("periph.rgb_suites", level="L2", family="hardware", gate="hw.system")-def periph_rgb_suites(h, facts):- """RGB / peripheral suites: OpenRGB, ckb-next, Piper/ratbagd, Solaar, polychromatic (by path)."""- paths = {"OpenRGB": ["/usr/bin/openrgb", "~/.config/OpenRGB"], "ckb-next": ["/usr/bin/ckb-next"],- "Piper": ["/usr/bin/piper"], "Solaar": ["/usr/bin/solaar", "~/.config/solaar"],- "polychromatic": ["/usr/bin/polychromatic-controller"], "liquidctl": ["/usr/bin/liquidctl"]}- found = sorted(k for k, ps in paths.items() if any(os.path.exists(os.path.expanduser(p)) for p in ps))- return {"present": bool(found), "suites": found} if found else None---@lp("hw.power_plan", level="L2", family="hardware", gate="hw.system")-def hw_power_plan(h, facts):- """Power profile (power-profiles-daemon / ACPI platform_profile / tuned / TLP) and CPU governor."""- prof = None- if _which("powerprofilesctl"):- prof = (_run(h, ["powerprofilesctl", "get"], 2000) or "").strip() or None- gov = _read1("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor")- plat = _read1("/sys/firmware/acpi/platform_profile")- tuned = _read1("/etc/tuned/active_profile")- if not any((prof, gov, plat, tuned)):- return None- return {"present": True, "active": prof or plat or tuned or gov, "power_profile": prof, "platform_profile": plat,- "governor": gov, "tuned": tuned, "tlp": os.path.exists("/usr/sbin/tlp")}---@lp("hw.audio", level="L2", family="hardware", tier="T1", gate="hw.system", collect="extended")-def hw_audio(h, facts):- """Sound cards from /proc/asound/cards; PipeWire vs PulseAudio user service."""- cards = re.findall(r"^\s*\d+\s+\[[^\]]*\]:\s*(.+)$", _read("/proc/asound/cards") or "", re.M)- return {"present": bool(cards), "cards": [c.strip() for c in cards][:10], "count": len(cards),- "pipewire": os.path.exists("/usr/bin/pipewire"), "pulseaudio": os.path.exists("/usr/bin/pulseaudio")}---@lp("hw.bluetooth", level="L2", family="hardware", tier="T1", gate="hw.system", collect="extended")-def hw_bluetooth(h, facts):- """Bluetooth adapters in /sys/class/bluetooth and bluetooth.service; paired devices need root (not read)."""- ad = [n for n in h.list_dir("/sys/class/bluetooth", 20) if ":" not in n]- return {"present": bool(ad), "adapters": len(ad), "service_enabled": "bluetooth.service" in _enabled_units(),- "paired_devices": None}---@lp("hw.usb_devices", level="L2", family="hardware", tier="T2", gate="hw.system", collect="extended")-def hw_usb_devices(h, facts):- """USB devices attached now (not history): count by class, product names at T2."""- names, classes = [], collections.Counter()- for d in glob.glob("/sys/bus/usb/devices/*")[:500]:- if ":" in os.path.basename(d) or os.path.basename(d).startswith("usb"):- continue- cls = _read1(os.path.join(d, "bDeviceClass"))- classes[cls or "?"] += 1- p = _read1(os.path.join(d, "product"))- if p:- names.append(p)- return {"present": bool(names or classes), "count": sum(classes.values()), "by_class": dict(classes),- "names": sorted(set(names))[:30]}---@lp("hw.monitor_mode", level="L2", family="hardware", gate="hw.system", collect="extended")-def hw_monitor_mode(h, facts):- """Connected display outputs from /sys/class/drm: connector types, preferred mode, virtual vs physical."""- outs = []- for c in glob.glob("/sys/class/drm/card*-*")[:64]:- if _read1(os.path.join(c, "status")) != "connected":- continue- name = os.path.basename(c).split("-", 1)[1]- modes = (_read(os.path.join(c, "modes"), 4096) or "").split()- outs.append({"connector": re.sub(r"-\d+$", "", name), "preferred_mode": modes[0] if modes else None,- "edid": (h.meta(os.path.join(c, "edid")).get("bytes") or 0) > 0})- if not outs:- return None- return {"present": True, "connected": len(outs), "outputs": outs,- "virtual_only": all(o["connector"].lower().startswith("virtual") for o in outs)}---@lp("hw.nvidia_smi", level="L2", family="hardware", gate="hw.system", collect="extended")-def hw_nvidia_smi(h, facts):- """nvidia-smi query: VRAM, power draw/limit, temperature, pstate, driver."""- exe = _which("nvidia-smi")- if not exe:- return None- fields = "name,memory.total,power.draw,power.limit,power.default_limit,power.max_limit,temperature.gpu,pstate,driver_version,fan.speed"- out = h.run([exe, "--query-gpu=" + fields, "--format=csv,noheader,nounits"], timeout_ms=5000)- if not out:- return {"present": False, "exe": True}- gpus = []- for line in out.strip().splitlines()[:8]:- vals = [x.strip() for x in line.split(",")]- gpus.append({k: (None if v in ("[N/A]", "N/A", "[Not Supported]") else v) for k, v in zip(fields.split(","), vals)})- try:- vram = round(max(float(g["memory.total"]) for g in gpus if g.get("memory.total")) / 1024, 1)- except ValueError:- vram = None- return {"present": bool(gpus), "vram_gb": vram, "gpus": gpus}---@lp("hw.fonts", level="L2", family="hardware", tier="T1", gate="hw.system", collect="extended")-def hw_fonts(h, facts):- """Font inventory: fontconfig family count, user-installed font files, fonts-* packages, Nerd/coding fonts."""- fams = set()- if _which("fc-list"):- for line in (_run(h, ["fc-list", ":", "family"], 3000) or "").splitlines()[:20000]:- if line.strip():- fams.add(line.split(",")[0].strip())- user = 0- for d in (os.path.join(_home(), ".local/share/fonts"), os.path.join(_home(), ".fonts")):- for root, dirs, files in os.walk(d):- user += sum(1 for f in files if f.lower().endswith((".ttf", ".otf", ".woff2", ".pcf.gz")))- if user > 5000 or root.count(os.sep) - d.count(os.sep) > 3:- break- pk = [n for n in _dpkg_names(h) if n.startswith("fonts-")]- coding = sorted({f for f in fams if re.search(r"nerd|jetbrains mono|fira code|cascadia|iosevka|hack\b|meslo", f, re.I)})- return {"present": bool(fams or user), "families": len(fams), "user_font_files": user, "font_packages": len(pk),- "coding_fonts": coding[:10]}--# ================================================================ healthdef _crash_app(mangled):diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_system_hardware.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_system_hardware.pynew file mode 100644index 00000000000..9c6dc189e51--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_system_hardware.py@@ -0,0 +1,312 @@+"""Linux system-level probes: hardware.++Registration only at import time. Shared helpers live in linux_system.+"""+from __future__ import annotations++import collections+import glob+import json+import os+import re++from .linux_system import (_ARCH, _dpkg_names, _enabled_units, _home, _read, _read1, _run,+ _which, lp)++# ================================================================ hardware++_CHASSIS = {1: "other", 2: "unknown", 3: "desktop", 4: "low-profile desktop", 6: "mini tower", 7: "tower",+ 8: "portable", 9: "laptop", 10: "notebook", 13: "all-in-one", 14: "sub-notebook", 17: "main server chassis",+ 23: "rack mount", 30: "tablet", 31: "convertible", 32: "detachable", 35: "mini pc", 36: "stick pc"}+++def _meminfo():+ out = {}+ for line in (_read("/proc/meminfo") or "").splitlines():+ p = line.split()+ if len(p) >= 2 and p[1].isdigit():+ out[p[0].rstrip(":")] = int(p[1]) * 1024+ return out+++_REAL_FS = {"ext4", "ext3", "ext2", "xfs", "btrfs", "zfs", "f2fs", "vfat", "exfat", "ntfs", "ntfs3", "fuseblk", "bcachefs"}+++def _volumes():+ vols, seen = [], set()+ for line in (_read("/proc/mounts") or "").splitlines()[:2000]:+ p = line.split()+ if len(p) < 3 or p[2] not in _REAL_FS or p[0] in seen:+ continue+ seen.add(p[0])+ mp = p[1].replace("\\040", " ")+ try:+ st = os.statvfs(mp)+ except OSError:+ continue+ size = st.f_blocks * st.f_frsize+ if size <= 0:+ continue+ free = st.f_bavail * st.f_frsize+ vols.append({"name": mp, "fstype": p[2], "size_gb": round(size / 1e9, 1), "free_gb": round(free / 1e9, 1),+ "free_pct": round(100 * free / size, 1)})+ return vols+++@lp("hw.system", level="L1", family="hardware")+def hw_system(h, facts):+ """DMI system/board/BIOS, chassis type, visible RAM, fixed volumes with free space."""+ d = "/sys/class/dmi/id"+ r = lambda n: _read1(os.path.join(d, n)) or None+ mi = _meminfo()+ ct = r("chassis_type")+ ram = round(mi.get("MemTotal", 0) / 2 ** 30, 1) or None+ vols = _volumes()+ return {"present": True, "manufacturer": r("sys_vendor"), "product": r("product_name"), "family": r("product_family"),+ "version": r("product_version"), "board_vendor": r("board_vendor"), "board": r("board_name"),+ "bios_vendor": r("bios_vendor"), "bios_version": r("bios_version"), "bios_date": r("bios_date"),+ "chassis": _CHASSIS.get(int(ct), ct) if ct and ct.isdigit() else ct, "visible_ram_gb": ram,+ "memory_load_pct": round(100 * (1 - mi["MemAvailable"] / mi["MemTotal"])) if mi.get("MemTotal") and "MemAvailable" in mi else None,+ "fixed_drives_total_free_gb_pct": [[v["name"], v["size_gb"], v["free_gb"], v["free_pct"]] for v in vols]}+++@lp("hw.ram", level="L1", family="hardware")+def hw_ram(h, facts):+ """RAM and swap from /proc/meminfo (module count and speed need root dmidecode: not collected)."""+ mi = _meminfo()+ if not mi.get("MemTotal"):+ return None+ return {"present": True, "total_gb": round(mi["MemTotal"] / 2 ** 30, 1),+ "available_gb": round(mi.get("MemAvailable", 0) / 2 ** 30, 1),+ "swap_gb": round(mi.get("SwapTotal", 0) / 2 ** 30, 1), "swap_used_gb": round((mi.get("SwapTotal", 0) - mi.get("SwapFree", 0)) / 2 ** 30, 1),+ "zram": any(n.startswith("zram") for n in h.list_dir("/sys/block", 500))}+++@lp("hw.disks", level="L2", family="hardware", gate="hw.system")+def hw_disks(h, facts):+ """Physical disks (lsblk: size, rotational, transport, model, LUKS) and mounted volumes with free space."""+ disks = []+ out = _run(h, ["lsblk", "-J", "-b", "-d", "-o", "NAME,TYPE,SIZE,ROTA,RM,TRAN,MODEL"], 3000) if _which("lsblk") else None+ try:+ for b in (json.loads(out).get("blockdevices") or []) if out else []:+ if b.get("type") != "disk" or str(b.get("name", "")).startswith(("loop", "zram", "ram")):+ continue+ disks.append({"name": b.get("name"), "size_gb": round(int(b.get("size") or 0) / 1e9, 1),+ "ssd": not _truthy_flag(b.get("rota")), "removable": _truthy_flag(b.get("rm")),+ "transport": b.get("tran"), "model": (b.get("model") or "").strip() or None})+ except (ValueError, AttributeError):+ disks = []+ if not disks:+ for n in h.list_dir("/sys/block", 200):+ if n.startswith(("loop", "zram", "ram", "dm-", "md", "sr")):+ continue+ sz = _read1(f"/sys/block/{n}/size")+ disks.append({"name": n, "size_gb": round(int(sz) * 512 / 1e9, 1) if sz and sz.isdigit() else None,+ "ssd": _read1(f"/sys/block/{n}/queue/rotational") == "0",+ "removable": _read1(f"/sys/block/{n}/removable") == "1",+ "model": _read1(f"/sys/block/{n}/device/model")})+ vols = _volumes()+ return {"present": bool(disks or vols), "disks": disks, "volumes": vols,+ "virtio": any(d.get("transport") == "virtio" or str(d.get("name", "")).startswith("vd") for d in disks)}+++def _truthy_flag(v):+ return v in (True, 1, "1", "true")+++@lp("hw.cpu", level="L2", family="hardware", gate="hw.system")+def hw_cpu(h, facts):+ """CPU model, vendor, sockets/cores/threads, max MHz, virtualization from lscpu -J (cpuinfo fallback)."""+ out = _run(h, ["lscpu", "-J"], 3000) if _which("lscpu") else None+ f = {}+ try:+ for e in (json.loads(out).get("lscpu") or []) if out else []:+ f[e.get("field", "").rstrip(":")] = e.get("data")+ for c in e.get("children") or []:+ f[c.get("field", "").rstrip(":")] = c.get("data")+ except (ValueError, AttributeError):+ f = {}+ if not f:+ ci = _read("/proc/cpuinfo", 1 << 20) or ""+ m = re.search(r"^model name\s*:\s*(.+)$", ci, re.M)+ return {"present": bool(ci), "name": m.group(1).strip() if m else None,+ "logical_processors": len(re.findall(r"^processor\s*:", ci, re.M)), "via": "cpuinfo"}+ num = lambda k: int(f[k]) if str(f.get(k, "")).isdigit() else None+ return {"present": True, "name": f.get("Model name"), "vendor": f.get("Vendor ID"),+ "logical_processors": num("CPU(s)"), "sockets": num("Socket(s)"), "cores_per_socket": num("Core(s) per socket"),+ "threads_per_core": num("Thread(s) per core"), "max_mhz": f.get("CPU max MHz"),+ "virtualization": f.get("Virtualization"), "hypervisor": f.get("Hypervisor vendor"),+ "virt_type": f.get("Virtualization type"), "native_arch": _ARCH.get(os.uname().machine, os.uname().machine)}+++_PCI_VENDOR = {"0x10de": "NVIDIA", "0x1002": "AMD", "0x8086": "Intel", "0x1af4": "Red Hat (virtio)", "0x1234": "QEMU",+ "0x15ad": "VMware", "0x80ee": "VirtualBox", "0x1414": "Microsoft", "0x1a03": "ASPEED", "0x5143": "Qualcomm"}+++@lp("hw.gpu", level="L2", family="hardware", gate="hw.system")+def hw_gpu(h, facts):+ """Display adapters: PCI class 03 devices from sysfs (vendor, driver, VRAM for amdgpu), names from lspci -mm."""+ adapters = []+ for dev in glob.glob("/sys/bus/pci/devices/*")[:512]:+ cls = _read1(os.path.join(dev, "class")) or ""+ if not cls.startswith("0x03"):+ continue+ ven = _read1(os.path.join(dev, "vendor")) or ""+ drv = None+ try:+ drv = os.path.basename(os.readlink(os.path.join(dev, "driver")))+ except OSError:+ pass+ vram = _read1(os.path.join(dev, "mem_info_vram_total"))+ adapters.append({"slot": os.path.basename(dev), "vendor": _PCI_VENDOR.get(ven, ven), "device_id": _read1(os.path.join(dev, "device")),+ "driver": drv, "boot_vga": _read1(os.path.join(dev, "boot_vga")) == "1",+ "vram_gb": round(int(vram) / 2 ** 30, 1) if vram and vram.isdigit() else None, "name": None})+ if adapters and _which("lspci"):+ out = _run(h, ["lspci", "-mm", "-D"], 2000) or ""+ for line in out.splitlines():+ m = re.match(r'(\S+) "([^"]*)" "([^"]*)" "([^"]*)"', line)+ if m:+ for a in adapters:+ if a["slot"] == m.group(1):+ a["name"] = f"{m.group(3)} {m.group(4)}".strip()+ if not adapters:+ return None+ virtual = [a for a in adapters if a["vendor"] in ("Red Hat (virtio)", "QEMU", "VMware", "VirtualBox", "Microsoft")]+ real = [a for a in adapters if a not in virtual]+ vr = [a["vram_gb"] for a in real if a["vram_gb"]]+ return {"present": True, "max_vram_gb": max(vr) if vr else None, "adapters": real, "virtual_adapters": virtual,+ "other": len(virtual), "nvidia": any(a["vendor"] == "NVIDIA" for a in real)}+++@lp("hw.battery", level="L1", family="hardware")+def hw_battery(h, facts):+ """Battery present in /sys/class/power_supply: laptop vs desktop, charge, wear."""+ for n in h.list_dir("/sys/class/power_supply", 50):+ b = os.path.join("/sys/class/power_supply", n)+ if _read1(os.path.join(b, "type")) != "Battery" or _read1(os.path.join(b, "scope")) == "Device":+ continue+ full = _read1(os.path.join(b, "energy_full")) or _read1(os.path.join(b, "charge_full"))+ design = _read1(os.path.join(b, "energy_full_design")) or _read1(os.path.join(b, "charge_full_design"))+ wear = round(100 * int(full) / int(design), 1) if full and design and full.isdigit() and design.isdigit() and int(design) else None+ ac = [_read1(os.path.join("/sys/class/power_supply", m, "online")) for m in h.list_dir("/sys/class/power_supply", 50)+ if _read1(os.path.join("/sys/class/power_supply", m, "type")) == "Mains"]+ cap = _read1(os.path.join(b, "capacity"))+ return {"present": True, "on_ac": "1" in ac if ac else None, "charge_pct": int(cap) if cap and cap.isdigit() else None,+ "status": _read1(os.path.join(b, "status")), "health_pct": wear,+ "cycle_count": _read1(os.path.join(b, "cycle_count"))}+ return None+++@lp("periph.rgb_suites", level="L2", family="hardware", gate="hw.system")+def periph_rgb_suites(h, facts):+ """RGB / peripheral suites: OpenRGB, ckb-next, Piper/ratbagd, Solaar, polychromatic (by path)."""+ paths = {"OpenRGB": ["/usr/bin/openrgb", "~/.config/OpenRGB"], "ckb-next": ["/usr/bin/ckb-next"],+ "Piper": ["/usr/bin/piper"], "Solaar": ["/usr/bin/solaar", "~/.config/solaar"],+ "polychromatic": ["/usr/bin/polychromatic-controller"], "liquidctl": ["/usr/bin/liquidctl"]}+ found = sorted(k for k, ps in paths.items() if any(os.path.exists(os.path.expanduser(p)) for p in ps))+ return {"present": bool(found), "suites": found} if found else None+++@lp("hw.power_plan", level="L2", family="hardware", gate="hw.system")+def hw_power_plan(h, facts):+ """Power profile (power-profiles-daemon / ACPI platform_profile / tuned / TLP) and CPU governor."""+ prof = None+ if _which("powerprofilesctl"):+ prof = (_run(h, ["powerprofilesctl", "get"], 2000) or "").strip() or None+ gov = _read1("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor")+ plat = _read1("/sys/firmware/acpi/platform_profile")+ tuned = _read1("/etc/tuned/active_profile")+ if not any((prof, gov, plat, tuned)):+ return None+ return {"present": True, "active": prof or plat or tuned or gov, "power_profile": prof, "platform_profile": plat,+ "governor": gov, "tuned": tuned, "tlp": os.path.exists("/usr/sbin/tlp")}+++@lp("hw.audio", level="L2", family="hardware", tier="T1", gate="hw.system", collect="extended")+def hw_audio(h, facts):+ """Sound cards from /proc/asound/cards; PipeWire vs PulseAudio user service."""+ cards = re.findall(r"^\s*\d+\s+\[[^\]]*\]:\s*(.+)$", _read("/proc/asound/cards") or "", re.M)+ return {"present": bool(cards), "cards": [c.strip() for c in cards][:10], "count": len(cards),+ "pipewire": os.path.exists("/usr/bin/pipewire"), "pulseaudio": os.path.exists("/usr/bin/pulseaudio")}+++@lp("hw.bluetooth", level="L2", family="hardware", tier="T1", gate="hw.system", collect="extended")+def hw_bluetooth(h, facts):+ """Bluetooth adapters in /sys/class/bluetooth and bluetooth.service; paired devices need root (not read)."""+ ad = [n for n in h.list_dir("/sys/class/bluetooth", 20) if ":" not in n]+ return {"present": bool(ad), "adapters": len(ad), "service_enabled": "bluetooth.service" in _enabled_units(),+ "paired_devices": None}+++@lp("hw.usb_devices", level="L2", family="hardware", tier="T2", gate="hw.system", collect="extended")+def hw_usb_devices(h, facts):+ """USB devices attached now (not history): count by class, product names at T2."""+ names, classes = [], collections.Counter()+ for d in glob.glob("/sys/bus/usb/devices/*")[:500]:+ if ":" in os.path.basename(d) or os.path.basename(d).startswith("usb"):+ continue+ cls = _read1(os.path.join(d, "bDeviceClass"))+ classes[cls or "?"] += 1+ p = _read1(os.path.join(d, "product"))+ if p:+ names.append(p)+ return {"present": bool(names or classes), "count": sum(classes.values()), "by_class": dict(classes),+ "names": sorted(set(names))[:30]}+++@lp("hw.monitor_mode", level="L2", family="hardware", gate="hw.system", collect="extended")+def hw_monitor_mode(h, facts):+ """Connected display outputs from /sys/class/drm: connector types, preferred mode, virtual vs physical."""+ outs = []+ for c in glob.glob("/sys/class/drm/card*-*")[:64]:+ if _read1(os.path.join(c, "status")) != "connected":+ continue+ name = os.path.basename(c).split("-", 1)[1]+ modes = (_read(os.path.join(c, "modes"), 4096) or "").split()+ outs.append({"connector": re.sub(r"-\d+$", "", name), "preferred_mode": modes[0] if modes else None,+ "edid": (h.meta(os.path.join(c, "edid")).get("bytes") or 0) > 0})+ if not outs:+ return None+ return {"present": True, "connected": len(outs), "outputs": outs,+ "virtual_only": all(o["connector"].lower().startswith("virtual") for o in outs)}+++@lp("hw.nvidia_smi", level="L2", family="hardware", gate="hw.system", collect="extended")+def hw_nvidia_smi(h, facts):+ """nvidia-smi query: VRAM, power draw/limit, temperature, pstate, driver."""+ exe = _which("nvidia-smi")+ if not exe:+ return None+ fields = "name,memory.total,power.draw,power.limit,power.default_limit,power.max_limit,temperature.gpu,pstate,driver_version,fan.speed"+ out = h.run([exe, "--query-gpu=" + fields, "--format=csv,noheader,nounits"], timeout_ms=5000)+ if not out:+ return {"present": False, "exe": True}+ gpus = []+ for line in out.strip().splitlines()[:8]:+ vals = [x.strip() for x in line.split(",")]+ gpus.append({k: (None if v in ("[N/A]", "N/A", "[Not Supported]") else v) for k, v in zip(fields.split(","), vals)})+ try:+ vram = round(max(float(g["memory.total"]) for g in gpus if g.get("memory.total")) / 1024, 1)+ except ValueError:+ vram = None+ return {"present": bool(gpus), "vram_gb": vram, "gpus": gpus}+++@lp("hw.fonts", level="L2", family="hardware", tier="T1", gate="hw.system", collect="extended")+def hw_fonts(h, facts):+ """Font inventory: fontconfig family count, user-installed font files, fonts-* packages, Nerd/coding fonts."""+ fams = set()+ if _which("fc-list"):+ for line in (_run(h, ["fc-list", ":", "family"], 3000) or "").splitlines()[:20000]:+ if line.strip():+ fams.add(line.split(",")[0].strip())+ user = 0+ for d in (os.path.join(_home(), ".local/share/fonts"), os.path.join(_home(), ".fonts")):+ for root, dirs, files in os.walk(d):+ user += sum(1 for f in files if f.lower().endswith((".ttf", ".otf", ".woff2", ".pcf.gz")))+ if user > 5000 or root.count(os.sep) - d.count(os.sep) > 3:+ break+ pk = [n for n in _dpkg_names(h) if n.startswith("fonts-")]+ coding = sorted({f for f in fams if re.search(r"nerd|jetbrains mono|fira code|cascadia|iosevka|hack\b|meslo", f, re.I)})+ return {"present": bool(fams or user), "families": len(fams), "user_font_files": user, "font_packages": len(pk),+ "coding_fonts": coding[:10]}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_system_security.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_system_security.pynew file mode 100644index 00000000000..9caa1df8529--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_system_security.py@@ -0,0 +1,491 @@+"""Linux system-level probes: security, network.++Registration only at import time. Shared helpers live in linux_system.+"""+from __future__ import annotations++import collections+import glob+import json+import os+import re+import grp++from .linux_system import (_enabled_units, _fv, _home, _ini, _kv, _me, _nm_kind, _nm_profiles,+ _read, _read1, _run, _which, lp)++# ================================================================ security++def _sshd_directives():+ out, unreadable = {}, 0+ files = ["/etc/ssh/sshd_config"] + sorted(glob.glob("/etc/ssh/sshd_config.d/*.conf"))[:50]+ for p in files:+ txt = _read(p, 200_000)+ if txt is None:+ unreadable += os.path.exists(p)+ continue+ for line in txt.splitlines()[:2000]:+ parts = line.strip().split(None, 1)+ if not parts or parts[0].startswith("#"):+ continue+ k = parts[0].lower()+ if k in ("port", "passwordauthentication", "pubkeyauthentication", "permitrootlogin",+ "kbdinteractiveauthentication", "x11forwarding", "usepam"):+ out.setdefault(k, parts[1] if len(parts) > 1 else "")+ elif k in ("allowusers", "allowgroups", "match", "denyusers"):+ out[k] = "<set>"+ return out, len(files), unreadable+++@lp("security.openssh_server", level="L1", family="security", tier="T3")+def openssh_server(h, facts):+ """sshd installed and enabled (ssh.service/ssh.socket wants-links), non-secret sshd_config directives."""+ exe = _which("sshd")+ if not exe:+ return None+ en = _enabled_units()+ d, nfiles, unreadable = _sshd_directives()+ svc = "ssh.service" in en or "sshd.service" in en+ sock = "ssh.socket" in en+ return {"present": True, "installed": True, "sshd_auto": svc or sock, "service_enabled": svc, "socket_enabled": sock,+ "sshd_config": d, "config_files": nfiles, "config_files_unreadable": unreadable}+++@lp("dev.ssh_dir_presence", level="L1", family="security", tier="T3")+def ssh_dir_presence(h, facts):+ """~/.ssh file kinds by name/stat only (keys never opened); known_hosts line count, config Host count."""+ d = os.path.join(_home(), ".ssh")+ names = h.list_dir(d, 200)+ if not names:+ return None+ pub = [n for n in names if n.endswith(".pub")]+ priv = [n for n in names if n.startswith("id_") and not n.endswith(".pub")]+ out = {"present": True, "files": len(names), "private_keys": len(priv), "public_keys": len(pub),+ "config": os.path.exists(os.path.join(d, "config")),+ "authorized_keys": h.meta(os.path.join(d, "authorized_keys")).get("bytes"),+ "known_hosts_lines": None, "config_host_entries": None, "agent_socket": bool(os.environ.get("SSH_AUTH_SOCK"))}+ try:+ with open(os.path.join(d, "known_hosts"), "rb") as f:+ out["known_hosts_lines"] = sum(1 for ln in f if ln.strip())+ except OSError:+ pass+ hosts = _ssh_hosts()+ if hosts is not None:+ out["config_host_entries"] = len(hosts)+ return out+++def _ssh_hosts():+ """Host aliases from ~/.ssh/config and ~/.ssh/config.d/*; wildcard patterns dropped; no other keys read."""+ d = os.path.join(_home(), ".ssh")+ files = [os.path.join(d, "config")] + sorted(glob.glob(os.path.join(d, "config.d", "*")))[:20]+ seen, any_file = [], False+ for p in files:+ txt = _read(p, 500_000)+ if txt is None:+ continue+ any_file = True+ for line in txt.splitlines()[:5000]:+ m = re.match(r"\s*Host\s+(.+)", line, re.I)+ if m:+ for a in m.group(1).split():+ if not any(c in a for c in "*?!") and a not in seen:+ seen.append(a)+ return seen if any_file else None+++@lp("security.ssh_config_hosts", level="L2", family="security", tier="T2", gate="dev.ssh_dir_presence")+def ssh_config_hosts(h, facts):+ """ssh config Host aliases (names only; HostName/User/IdentityFile never read). T2: machine names."""+ hosts = _ssh_hosts()+ if not hosts:+ return None+ return {"present": True, "count": len(hosts), "aliases": hosts[:50]}+++@lp("security.firewall", level="L1", family="security")+def security_firewall(h, facts):+ """Host firewall: ufw ENABLED in ufw.conf, firewalld/nftables/iptables-persistent enabled."""+ en = _enabled_units()+ ufw_conf = _kv(_read("/etc/ufw/ufw.conf") or "")+ out = {"ufw_installed": os.path.exists("/usr/sbin/ufw"), "ufw": ufw_conf.get("ENABLED") == "yes" if ufw_conf else None,+ "firewalld": "firewalld.service" in en, "nftables": "nftables.service" in en,+ "iptables_persistent": "netfilter-persistent.service" in en}+ out["present"] = any(v for v in out.values())+ out["all_on"] = bool(out["ufw"] or out["firewalld"] or out["nftables"] or out["iptables_persistent"])+ return out+++@lp("security.secureboot", level="L1", family="security")+def security_secureboot(h, facts):+ """UEFI boot and Secure Boot state from efivars (SecureBoot, SetupMode)."""+ uefi = os.path.isdir("/sys/firmware/efi")+ sb = None+ for p in glob.glob("/sys/firmware/efi/efivars/SecureBoot-*")[:1]:+ try:+ with open(p, "rb") as f:+ b = f.read(5)+ sb = len(b) == 5 and b[4] == 1+ except OSError:+ pass+ return {"present": True, "uefi": uefi, "secure_boot": sb, "enabled": bool(sb),+ "mok_enrolled": os.path.exists("/var/lib/shim-signed/mok/MOK.der")}+++@lp("security.uac", level="L1", family="security")+def security_uac(h, facts):+ """Elevation path: invoking user in sudo/admin/wheel, sudoers.d drop-ins count, polkit rules count."""+ try:+ groups = sorted({grp.getgrgid(g).gr_name for g in os.getgroups()})+ except KeyError:+ groups = []+ admin = [g for g in groups if g in ("sudo", "admin", "wheel", "root")]+ return {"present": True, "mechanism": "sudo" if _which("sudo") else None, "in_admin_group": bool(admin),+ "admin_groups": admin, "is_root": os.geteuid() == 0,+ "sudo_used_before": os.path.exists(os.path.join(_home(), ".sudo_as_admin_successful")),+ "sudoers_d_files": len([n for n in h.list_dir("/etc/sudoers.d", 200) if n != "README"]),+ "polkit_rules": len(h.list_dir("/etc/polkit-1/rules.d", 200)),+ "other_groups": [g for g in groups if g in ("docker", "lxd", "libvirt", "kvm", "adm", "wireshark")]}+++@lp("security.sudo_nopasswd", level="L2", family="security", gate="security.uac", collect="extended")+def sudo_nopasswd(h, facts):+ """sudo -n -l classification: password required / NOPASSWD rules / not allowed. Commands never emitted.+ Side effect: when a password is required sudo logs one auth-log line per run; skipped for non-admins."""+ uac = _fv(facts, "security.uac") or {}+ if not _which("sudo") or not uac.get("in_admin_group"):+ return None+ out = _run(h, ["sudo", "-n", "-l"], 3000)+ if out is None:+ return {"present": True, "result": "error"}+ low = out.lower()+ if "a password is required" in low or not out.strip():+ res = "password_required"+ elif "may not run sudo" in low or "not allowed" in low:+ res = "not_allowed"+ else:+ res = "listed"+ nop = len(re.findall(r"NOPASSWD:", out))+ nop_all = bool(re.search(r"NOPASSWD:\s*ALL\b", out))+ return {"present": True, "result": res, "nopasswd_rules": nop, "nopasswd_all": nop_all}+++@lp("acct.admins", level="L2", family="security", gate="security.uac")+def acct_admins(h, facts):+ """Members of sudo/admin/wheel from /etc/group (counts only; names never emitted)."""+ out = {}+ for g in ("sudo", "admin", "wheel"):+ try:+ out[g] = len(grp.getgrnam(g).gr_mem)+ except KeyError:+ continue+ if not out:+ return None+ return {"present": True, "members": out, "count": max(out.values())}+++@lp("security.telemetry", level="L1", family="security")+def security_telemetry(h, facts):+ """Crash/usage reporting: apport enabled flag, whoopsie, popularity-contest, ubuntu-report consent file."""+ ap = _kv(_read("/etc/default/apport") or "")+ pop = _kv(_read("/etc/popularity-contest.conf") or "")+ en = _enabled_units()+ apport_on = ap.get("enabled") == "1" if ap else None+ return {"present": True, "apport_enabled": apport_on, "whoopsie": "whoopsie.service" in en,+ "popcon": pop.get("PARTICIPATE") == "yes" if pop else None,+ "ubuntu_report_file": os.path.isdir(os.path.join(_home(), ".cache/ubuntu-report")),+ "ubuntu_pro_status_file": os.path.exists("/var/lib/ubuntu-advantage/status.json"),+ "reduced": apport_on is False}+++_REMOTE = {"xrdp": ["/usr/sbin/xrdp"], "krdp": ["/usr/bin/krdpserver"], "gnome-remote-desktop": ["/usr/libexec/gnome-remote-desktop-daemon"],+ "krfb": ["/usr/bin/krfb"], "x11vnc": ["/usr/bin/x11vnc"], "tigervnc": ["/usr/bin/x0vncserver", "/usr/bin/Xtigervnc"],+ "anydesk": ["/usr/bin/anydesk"], "teamviewer": ["/opt/teamviewer"], "rustdesk": ["/usr/bin/rustdesk"],+ "sunshine": ["/usr/bin/sunshine"], "nomachine": ["/usr/NX"], "parsec": ["/usr/bin/parsecd"],+ "chrome-remote-desktop": ["/opt/google/chrome-remote-desktop"], "et": ["/usr/bin/etserver"],+ "mosh": ["/usr/bin/mosh-server"]}+++@lp("security.rdp", level="L1", family="security")+def security_rdp(h, facts):+ """RDP server (xrdp / KDE krdp / gnome-remote-desktop) installed and enabled."""+ en = _enabled_units()+ inst = [k for k in ("xrdp", "krdp", "gnome-remote-desktop") if any(os.path.exists(p) for p in _REMOTE[k])]+ enabled = "xrdp.service" in en+ return {"present": True, "installed": inst, "rdp_enabled": enabled or None}+++@lp("security.remote_tools", level="L1", family="security")+def security_remote_tools(h, facts):+ """Remote access tools present: VNC servers, AnyDesk, TeamViewer, RustDesk, Sunshine, EternalTerminal, mosh."""+ found = sorted(k for k, ps in _REMOTE.items() if any(os.path.exists(p) for p in ps))+ vnc_dir = h.meta(os.path.join(_home(), ".vnc"))+ return {"present": True, "tools": found, "count": len(found), "user_vnc_dir": vnc_dir.get("present", False),+ "user_vnc_passwd_bytes": h.meta(os.path.join(_home(), ".vnc/passwd")).get("bytes")}+++@lp("security.apparmor", level="L1", family="security")+def security_apparmor(h, facts):+ """Active LSMs (AppArmor/SELinux), kernel lockdown mode."""+ lsm = (_read1("/sys/kernel/security/lsm") or "").split(",")+ aa = _read1("/sys/module/apparmor/parameters/enabled")+ lock = _read1("/sys/kernel/security/lockdown")+ m = re.search(r"\[(\w+)\]", lock or "")+ return {"present": True, "lsm": [x for x in lsm if x], "apparmor": aa == "Y" if aa else "apparmor" in lsm,+ "selinux": "selinux" in lsm, "lockdown": m.group(1) if m else None,+ "apparmor_profiles_dir": len(h.list_dir("/etc/apparmor.d", 2000))}+++@lp("security.bitlocker", level="L1", family="security")+def security_disk_encryption(h, facts):+ """Disk encryption (Linux: LUKS dm-crypt mappings from /sys/block/dm-*/dm/uuid; BitLocker equivalent)."""+ crypt = 0+ for u in glob.glob("/sys/block/dm-*/dm/uuid")[:200]:+ if (_read1(u) or "").startswith("CRYPT-"):+ crypt += 1+ return {"present": True, "mechanism": "luks", "encrypted_volumes": crypt, "any_encrypted": crypt > 0,+ "crypttab_lines": sum(1 for l in (_read("/etc/crypttab") or "").splitlines() if l.strip() and not l.startswith("#"))}+++@lp("security.tpm", level="L1", family="security")+def security_tpm(h, facts):+ """TPM present (/sys/class/tpm) and its major version; resource manager device for the user."""+ devs = [n for n in h.list_dir("/sys/class/tpm", 10) if n.startswith("tpm")]+ if not devs:+ return {"present": False, "tpm": False}+ ver = _read1(f"/sys/class/tpm/{devs[0]}/tpm_version_major")+ return {"present": True, "tpm": True, "version": ver, "rm_device": os.path.exists("/dev/tpmrm0")}+++@lp("acct.autologon", level="L1", family="security")+def acct_autologon(h, facts):+ """Display-manager autologin (sddm/gdm/lightdm) and whether it logs in the invoking user. No names."""+ me = _me()+ user, dm = None, None+ for p in ["/etc/sddm.conf"] + sorted(glob.glob("/etc/sddm.conf.d/*.conf")):+ sec = _ini(_read(p) or "").get("Autologin") or {}+ if sec.get("User"):+ user, dm = sec["User"], "sddm"+ g = _ini(_read("/etc/gdm3/custom.conf") or "").get("daemon") or {}+ if g.get("AutomaticLoginEnable", "").lower() == "true":+ user, dm = g.get("AutomaticLogin"), "gdm"+ for p in ["/etc/lightdm/lightdm.conf"] + sorted(glob.glob("/etc/lightdm/lightdm.conf.d/*.conf")):+ for s in _ini(_read(p) or "").values():+ if s.get("autologin-user"):+ user, dm = s["autologin-user"], "lightdm"+ return {"present": True, "enabled": bool(user), "display_manager": dm,+ "is_current_user": bool(user and me and user == me.pw_name)}+++_PM = {"KeePassXC": ["/usr/bin/keepassxc", "~/.config/keepassxc"], "Bitwarden": ["/usr/bin/bitwarden", "/opt/Bitwarden", "~/.config/Bitwarden"],+ "1Password": ["/opt/1Password", "/usr/bin/1password"], "Proton Pass": ["/usr/bin/proton-pass", "/opt/proton-pass"],+ "Enpass": ["/opt/enpass"], "pass": ["~/.password-store"], "gopass": ["/usr/bin/gopass", "~/.config/gopass"],+ "KWallet": ["~/.local/share/kwalletd"], "GNOME Keyring": ["~/.local/share/keyrings"]}+++@lp("pm.desktop", level="L1", family="security")+def pm_desktop(h, facts):+ """Password managers and OS keyrings by path presence (vault/keyring files never opened)."""+ found = sorted(k for k, ps in _PM.items() if any(os.path.exists(os.path.expanduser(p)) for p in ps))+ managers = [f for f in found if f not in ("KWallet", "GNOME Keyring")]+ keyrings = [f for f in found if f not in managers]+ return {"present": bool(managers or keyrings), "managers": managers, "keyrings": keyrings,+ "count": len(managers)}+++@lp("security.av_products", level="L2", family="security", gate="security.uac")+def av_products(h, facts):+ """Anti-malware / EDR agents by path: ClamAV, Sophos, CrowdStrike, SentinelOne, Defender for Endpoint, Wazuh."""+ paths = {"clamav": "/usr/bin/clamscan", "sophos": "/opt/sophos-spl", "crowdstrike": "/opt/CrowdStrike",+ "sentinelone": "/opt/sentinelone", "mdatp": "/opt/microsoft/mdatp", "wazuh": "/var/ossec",+ "rkhunter": "/usr/bin/rkhunter", "chkrootkit": "/usr/sbin/chkrootkit", "fail2ban": "/usr/bin/fail2ban-server"}+ found = sorted(k for k, p in paths.items() if os.path.exists(p))+ return {"present": True, "products": found, "count": len(found)}+++_NOTABLE_SVC = ("ssh", "tailscaled", "docker", "containerd", "xrdp", "cups", "bluetooth", "avahi-daemon", "ufw",+ "apparmor", "snapd", "libvirtd", "sddm", "gdm", "lightdm", "NetworkManager", "systemd-networkd",+ "unattended-upgrades", "fail2ban", "nginx", "apache2", "caddy", "postgresql", "mysql", "mariadb",+ "redis-server", "ollama", "smbd", "nfs-server", "cockpit", "zerotier-one", "wg-quick@wg0", "k3s",+ "nvidia-persistenced", "power-profiles-daemon", "tlp", "thermald")+++@lp("security.services_state", level="L2", family="security", gate="host.systemd", collect="extended")+def services_state(h, facts):+ """systemd unit counts: enabled services/timers/sockets, failed units, notable services enabled/active."""+ txt = _run(h, ["systemctl", "list-unit-files", "--no-legend", "--no-pager", "--type=service,timer,socket"], 4000) or ""+ by = collections.Counter()+ enabled = set()+ for line in txt.splitlines()[:5000]:+ p = line.split()+ if len(p) >= 2:+ kind = p[0].rsplit(".", 1)[-1]+ by[f"{kind}:{p[1]}"] += 1+ if p[1] == "enabled":+ enabled.add(p[0].rsplit(".", 1)[0])+ failed = _run(h, ["systemctl", "list-units", "--no-legend", "--no-pager", "--state=failed", "--plain"], 3000) or ""+ act = _run(h, ["systemctl", "list-units", "--no-legend", "--no-pager", "--type=service", "--state=running", "--plain"], 3000) or ""+ running = {l.split()[0].rsplit(".", 1)[0] for l in act.splitlines() if l.strip()}+ if not by:+ return None+ return {"present": True, "unit_files": sum(by.values()), "by_kind_state": dict(sorted(by.items())),+ "enabled_services": by.get("service:enabled", 0), "running_services": len(running),+ "failed_units": sum(1 for l in failed.splitlines() if l.strip()),+ "notable_enabled": sorted(s for s in _NOTABLE_SVC if s in enabled),+ "notable_running": sorted(s for s in _NOTABLE_SVC if s in running)}+++@lp("security.cert_roots", level="L2", family="security", gate="os.edition", collect="extended")+def cert_roots(h, facts):+ """Locally added CA certificates (/usr/local/share/ca-certificates) vs system bundle size."""+ local = [n for n in h.list_dir("/usr/local/share/ca-certificates", 500)]+ return {"present": True, "local_added": len(local), "etc_ssl_certs": max(h.count_dir("/etc/ssl/certs", 5000), 0)}+++# ================================================================ network++_PROXY_ENV = ("http_proxy", "https_proxy", "all_proxy", "no_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY")+++@lp("net.hosts_proxy", level="L1", family="network")+def net_hosts_proxy(h, facts):+ """/etc/hosts custom entries count, proxy variables set (names only), apt proxy config."""+ lines = [l.split("#")[0].split() for l in (_read("/etc/hosts") or "").splitlines()]+ lines = [l for l in lines if len(l) >= 2]+ default = {"localhost", "ip6-localhost", "ip6-loopback", "ip6-allnodes", "ip6-allrouters", "ip6-localnet",+ "ip6-mcastprefix", os.uname().nodename}+ custom = [l for l in lines if not set(l[1:]) <= default and not l[0].startswith(("127.0.1.1", "::1", "fe00", "ff0"))]+ envf = _kv(_read("/etc/environment") or "")+ apt_proxy = any("proxy" in n.lower() for n in h.list_dir("/etc/apt/apt.conf.d", 200))+ return {"present": True, "hosts_custom_entries": len(custom), "hosts_entries": len(lines),+ "proxy_env": sorted({k.lower() for k in _PROXY_ENV if os.environ.get(k)}),+ "proxy_etc_environment": sorted({k.lower() for k in envf if k in _PROXY_ENV}), "apt_proxy": apt_proxy}+++_VPN_BINS = {"tailscale": "tailscale", "wireguard": "wg", "openvpn": "openvpn", "zerotier": "zerotier-cli",+ "cloudflare-warp": "warp-cli", "netbird": "netbird", "mullvad": "mullvad", "nordvpn": "nordvpn",+ "protonvpn": "protonvpn-cli", "expressvpn": "expressvpn", "headscale": "headscale", "nebula": "nebula"}+++@lp("net.vpn_clients", level="L1", family="network")+def vpn_clients(h, facts):+ """VPN/mesh clients by binary and enabled systemd service (tailscaled, wg-quick@, openvpn@, zerotier-one...)."""+ found = sorted(k for k, b in _VPN_BINS.items() if _which(b))+ en = _enabled_units()+ svc = sorted(u for u in en if re.match(r"(tailscaled|wg-quick@|openvpn|zerotier-one|warp-svc|netbird|mullvad)", u))+ return {"present": True, "clients": found, "dirs": found, "services": svc, "count": len(found),+ "wireguard_dir": os.path.isdir("/etc/wireguard")}+++@lp("net.networkmanager", level="L1", family="network")+def net_networkmanager(h, facts):+ """Network stack: NetworkManager / systemd-networkd / netplan, profile file count (names never emitted)."""+ en = _enabled_units()+ nm = os.path.exists("/usr/sbin/NetworkManager")+ files = h.list_dir("/etc/NetworkManager/system-connections", 2000)+ netplan = [n for n in h.list_dir("/etc/netplan", 100) if n.endswith(".yaml")]+ if not nm and not netplan and "systemd-networkd.service" not in en:+ return None+ return {"present": True, "networkmanager": nm, "nm_enabled": "NetworkManager.service" in en,+ "nm_profile_files": len(files), "networkd_enabled": "systemd-networkd.service" in en,+ "netplan_files": len(netplan)}+++@lp("net.wifi_profiles", level="L2", family="network", gate="net.networkmanager")+def wifi_profiles(h, facts):+ """Saved Wi-Fi profile count from nmcli TYPE column; SSIDs never read."""+ rows = _nm_profiles(h)+ if rows is None:+ return None+ n = sum(1 for r in rows if _nm_kind(r["type"]) == "wireless")+ wifi_hw = any(os.path.isdir(os.path.join("/sys/class/net", i, "wireless")) for i in h.list_dir("/sys/class/net", 100))+ return {"present": True, "count": n, "wifi_hardware": wifi_hw}+++@lp("net.connection_profiles", level="L2", family="network", gate="net.networkmanager", collect="extended")+def connection_profiles(h, facts):+ """NetworkManager profiles by kind and autoconnect count (names never requested)."""+ rows = _nm_profiles(h)+ if not rows:+ return None+ return {"present": True, "count": len(rows), "by_kind": dict(collections.Counter(_nm_kind(r["type"]) for r in rows)),+ "autoconnect": sum(1 for r in rows if r["autoconnect"])}+++def _if_kind(name):+ base = os.path.join("/sys/class/net", name)+ if name == "lo":+ return "loopback"+ if os.path.isdir(os.path.join(base, "wireless")) or os.path.exists(os.path.join(base, "phy80211")):+ return "wifi"+ if name.startswith(("tailscale", "wg", "tun", "zt", "nb-")):+ return "tunnel"+ if name.startswith(("docker", "br-", "veth", "virbr", "lxc", "lxd", "cni", "flannel", "vnet")) or \+ os.path.isdir(os.path.join(base, "bridge")):+ return "virtual"+ if name.startswith(("wwan", "ww")):+ return "mobile"+ if os.path.exists(os.path.join(base, "device")):+ return "ethernet"+ return "other"+++@lp("net.adapters", level="L2", family="network", gate="net.hosts_proxy", collect="extended")+def net_adapters(h, facts):+ """Network interfaces from /sys/class/net: count by kind, up count, physical link speeds."""+ kinds, up, speeds = collections.Counter(), collections.Counter(), []+ for n in h.list_dir("/sys/class/net", 500):+ k = _if_kind(n)+ kinds[k] += 1+ if _read1(os.path.join("/sys/class/net", n, "operstate")) == "up":+ up[k] += 1+ if k in ("ethernet", "wifi"):+ s = _read1(os.path.join("/sys/class/net", n, "speed"))+ if s and s.lstrip("-").isdigit() and int(s) > 0:+ speeds.append(int(s))+ if not kinds:+ return None+ return {"present": True, "by_kind": dict(kinds), "up_by_kind": dict(up), "link_speeds_mbps": sorted(speeds)}+++@lp("net.dns", level="L2", family="network", gate="net.hosts_proxy", collect="extended")+def net_dns(h, facts):+ """Resolver: resolv.conf nameserver count, systemd-resolved stub, Tailscale MagicDNS server, custom upstreams."""+ rc = _read("/etc/resolv.conf") or ""+ ns = re.findall(r"^\s*nameserver\s+(\S+)", rc, re.M)+ stub = "127.0.0.53" in ns+ try:+ resolved = "systemd/resolve" in os.readlink("/etc/resolv.conf")+ except OSError:+ resolved = False+ ups = []+ if stub and _which("resolvectl"):+ out = _run(h, ["resolvectl", "dns"], 2000) or ""+ ups = re.findall(r"(\d+\.\d+\.\d+\.\d+|[0-9a-f:]{6,})", out)+ public = {"1.1.1.1": "cloudflare", "1.0.0.1": "cloudflare", "8.8.8.8": "google", "8.8.4.4": "google",+ "9.9.9.9": "quad9", "208.67.222.222": "opendns"}+ return {"present": bool(ns), "nameservers": len(ns), "resolved_stub": stub, "resolved_managed": resolved,+ "upstreams": len(set(ups)), "magicdns": "100.100.100.100" in ups or "100.100.100.100" in ns,+ "public_resolvers": sorted({public[u] for u in set(ups) | set(ns) if u in public}),+ "search_domains": len(re.findall(r"^\s*search\s+(.+)", rc, re.M))}+++@lp("net.tailscale", level="L2", family="network", tier="T1", gate="net.vpn_clients", collect="extended")+def net_tailscale(h, facts):+ """Tailscale state via 'tailscale status --json': peer counts by OS and online count; peer names never emitted."""+ exe = _which("tailscale")+ if not exe:+ return None+ out = _run(h, [exe, "status", "--json"], 3000)+ try:+ j = json.loads(out) if out else None+ except ValueError:+ j = None+ if not isinstance(j, dict):+ return {"present": True, "status": "unparsed"}+ peers = list((j.get("Peer") or {}).values())+ by_os = collections.Counter(p.get("OS") or "?" for p in peers)+ return {"present": True, "version": (j.get("Version") or "").split("-")[0], "backend": j.get("BackendState"),+ "peers": len(peers), "online": sum(1 for p in peers if p.get("Online")), "peers_by_os": dict(by_os),+ "exit_node_in_use": any(p.get("ExitNode") for p in peers),+ "magicdns": bool((j.get("CurrentTailnet") or {}).get("MagicDNSEnabled"))}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/usage_gaming.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/usage_gaming.pyindex 53104d56fcb..433198b7934 100644--- a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/usage_gaming.py+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/usage_gaming.py@@ -1,4 +1,4 @@-"""Usage habits, gaming, media, hardware and health probes (Windows).+"""Usage habit probes (Windows), plus the helpers usage_gaming_games and usage_gaming_hardware share.Registration only at import time. Routes follow reports/14-triage.json: registry and file reads in core,the batched PowerShell sidecar for event logs and CIM, SRUM and PnP history in deep.@@ -7,7 +7,6 @@ from __future__ import annotationsimport collectionsimport datetime as dt-import jsonimport osimport reimport struct@@ -15,7 +14,7 @@ import sysimport threadingimport time-from userscan.registry import probe, ps_probe+from ..registry import probe_T0 = time.time()_LOCK = threading.Lock()@@ -867,1466 +866,3 @@ def eventlog_security_logons(h, facts):return {"present": bool(by), "events": sum(by.values()), "by_id": dict(by), "logon_types_4624": dict(types),"interactive_unlock": types["2"] + types["7"] + types["11"], "remote_interactive": types["10"],"span": [_iso(first), _iso(last)]}---# ================================================================= GAMING--def _steam(h):- """Shared Steam state: path, libraries, manifests, userdata ids, localconfig apps, appinfo buffer."""- def load():- sp = h.reg(r"HKCU\Software\Valve\Steam", "SteamPath")- if not sp:- cand = os.path.join(_paths()["PF86"], "Steam")- sp = cand if _ex(cand) else None- if not sp:- return None- sp = os.path.normpath(sp)- libs = []- txt = _read(os.path.join(sp, "steamapps", "libraryfolders.vdf"))- if txt:- for _k, v in (_ci(_vdf(txt), "libraryfolders") or {}).items():- if isinstance(v, dict) and v.get("path"):- libs.append(os.path.normpath(v["path"]))- libs = libs or [sp]- installed = []- for lib in libs[:20]:- sa = os.path.join(lib, "steamapps")- for n in h.list_dir(sa, 2000):- if n.startswith("appmanifest_") and n.endswith(".acf"):- st = _ci(_vdf(_read(os.path.join(sa, n)) or ""), "AppState") or {}- installed.append({"appid": int(st.get("appid", 0) or 0), "name": st.get("name"),- "size_gb": round(int(st.get("SizeOnDisk", 0) or 0) / 1e9, 1), "drive": lib[:2].upper(),- "last_played": int(st.get("LastPlayed", 0) or 0)})- ud = os.path.join(sp, "userdata")- uids = [u for u in h.list_dir(ud, 50) if u.isdigit()]- users = {}- for uid in uids:- lc = os.path.join(ud, uid, "config", "localconfig.vdf")- apps = {}- t = _read(lc)- if t:- d = _vdf(t)- node = _ci(d, "UserLocalConfigStore", "Software", "Valve", "Steam", "apps") or {}- for aid, v in node.items():- if isinstance(v, dict) and aid.isdigit() and ("Playtime" in v or "LastPlayed" in v):- apps[int(aid)] = {"min": int(v.get("Playtime", 0) or 0), "min2wk": int(v.get("Playtime2wks", 0) or 0),- "last": int(v.get("LastPlayed", 0) or 0)}- users[uid] = apps- return {"path": sp, "libs": libs, "installed": installed, "uids": uids, "users": users,- "appinfo_path": os.path.join(sp, "appcache", "appinfo.vdf")}- return _cached(("steam", h.l0.get("run_id")), load)---_TOK = re.compile(r'"((?:[^"\\]|\\.)*)"|(\{)|(\})', re.S)---def _vdf(text):- stack, key = [{}], None- for m in _TOK.finditer(text):- s, ob, cb = m.groups()- if ob:- d = {}- stack[-1][key] = d- stack.append(d)- key = None- elif cb:- if len(stack) > 1:- stack.pop()- else:- s = s.replace("\\\\", "\\")- if key is None:- key = s- else:- stack[-1][key] = s- key = None- return stack[0]---def _ci(d, *keys):- for k in keys:- if not isinstance(d, dict):- return None- lk = {kk.lower(): kk for kk in d}- if k.lower() not in lk:- return None- d = d[lk[k.lower()]]- return d---_GENRES = {"1": "Action", "2": "Strategy", "3": "RPG", "4": "Casual", "9": "Racing", "18": "Sports", "23": "Indie",- "25": "Adventure", "28": "Simulation", "29": "Massively Multiplayer", "37": "Free to Play", "70": "Early Access",- "51": "Animation & Modeling", "52": "Audio Production", "53": "Design & Illustration", "54": "Education",- "55": "Photo Editing", "56": "Software Training", "57": "Utilities", "58": "Video Production",- "59": "Web Publishing", "60": "Game Development"}---def _cstr(buf, i):- j = buf.index(b"\x00", i)- return buf[i:j].decode("utf-8", "replace"), j + 1---def _bkv(buf, i, strtab, depth=0):- d = {}- while True:- t = buf[i]- i += 1- if t in (8, 11):- return d, i- if strtab is not None:- (idx,) = struct.unpack_from("<I", buf, i)- i += 4- key = strtab[idx] if idx < len(strtab) else str(idx)- else:- key, i = _cstr(buf, i)- if t == 0:- if depth > 30:- raise ValueError("bkv too deep")- v, i = _bkv(buf, i, strtab, depth + 1)- elif t == 1:- v, i = _cstr(buf, i)- elif t in (2, 4, 6):- (v,) = struct.unpack_from("<i", buf, i)- i += 4- elif t == 3:- (v,) = struct.unpack_from("<f", buf, i)- i += 4- elif t == 7:- (v,) = struct.unpack_from("<Q", buf, i)- i += 8- elif t == 10:- (v,) = struct.unpack_from("<q", buf, i)- i += 8- elif t == 5:- j = i- while buf[j:j + 2] != b"\x00\x00":- j += 2- v = buf[i:j].decode("utf-16-le", "replace")- i = j + 2- else:- raise ValueError(f"bkv type {t}")- d[key] = v---def _appinfo(h, want):- """{appid: {name, type, genres}} for wanted appids, reading appinfo.vdf once per run."""- st = _steam(h) or {}- path = st.get("appinfo_path")-- def load():- with open(path, "rb") as f:- return f.read(200_000_000)- buf = _cached(("appinfo_buf", h.l0.get("run_id")), load) if path and _ex(path) else None- if not isinstance(buf, (bytes, bytearray)):- return {}- magic, _u = struct.unpack_from("<II", buf, 0)- ver = magic & 0xFF- off, strtab, end = 8, None, len(buf)- if ver >= 0x29:- (st_off,) = struct.unpack_from("<q", buf, 8)- off, end = 16, st_off- (n,) = struct.unpack_from("<I", buf, st_off)- strtab, j = [], st_off + 4- for _ in range(min(n, 500000)):- s, j = _cstr(buf, j)- strtab.append(s)- out = {}- while off < end - 8:- appid, size = struct.unpack_from("<II", buf, off)- if appid == 0:- break- body = off + 8- if appid in want:- kv_start = body + 4 + 4 + 8 + 20 + 4 + (20 if ver >= 0x28 else 0)- try:- kv, _ = _bkv(buf, kv_start, strtab)- common = _ci(kv, "appinfo", "common") or {}- g = common.get("genres") or {}- out[appid] = {"name": common.get("name"), "type": common.get("type"),- "genres": [_GENRES.get(str(x), str(x)) for x in (g.values() if isinstance(g, dict) else [])]}- except Exception:- out[appid] = {"name": None, "type": None, "genres": []}- off = body + size- return out---@probe(id="steam.present", level="L1", family="gaming", tier="T0", collect="core")-def steam_present(h, facts):- """Steam client installed (HKCU SteamPath or Program Files); gates the Steam subtree."""- sp = h.reg(r"HKCU\Software\Valve\Steam", "SteamPath")- if sp and _ex(sp):- return {"present": True, "via": "registry"}- if _ex(os.path.join(_paths()["PF86"], "Steam")):- return {"present": True, "via": "path"}- return None---def _lib_volume(p):- """Volume holding a Steam library: drive letter ('D:') for a Windows path, else the POSIX mount point."""- if re.match(r"^[A-Za-z]:", p or ""):- return p[:2].upper()- q = os.path.realpath(p) if p else "/"- for _ in range(64):- if os.path.ismount(q) or os.path.dirname(q) == q:- return q- q = os.path.dirname(q)- return q---@probe(id="steam.installed", level="L2", family="gaming", tier="T1", collect="core", gate="steam.present")-def steam_installed(h, facts):- """Installed Steam titles and GB from libraryfolders.vdf + appmanifest_*.acf."""- st = _steam(h)- if not st or "error" in st:- return {"present": False, "error": (st or {}).get("error")}- inst = sorted(st["installed"], key=lambda x: -x["size_gb"])- games = [x for x in inst if not re.search(r"Redistributable|Dedicated Server|SDK|Proton|Steamworks", x["name"] or "", re.I)]- return {"present": True, "libraries": len(st["libs"]), "drives": sorted({_lib_volume(p) for p in st["libs"]}),- "apps": len(inst), "games": len(games), "total_gb": round(sum(x["size_gb"] for x in inst), 1),- "top": [[x["name"], x["size_gb"], _iso(x["last_played"])] for x in games[:12]]}---@probe(id="steam.playtime", level="L2", family="gaming", tier="T1", collect="core", gate="steam.present")-def steam_playtime(h, facts):- """Account-wide playtime per Steam userdata account from localconfig.vdf: hours, 2-week hours, top games."""- st = _steam(h)- if not st or not st.get("users"):- return {"present": False}- want = set()- for apps in st["users"].values():- want |= set(sorted(apps, key=lambda a: -apps[a]["min"])[:15])- info = _appinfo(h, want) if want else {}- names = {x["appid"]: x["name"] for x in st["installed"]}- accounts = []- for uid, apps in st["users"].items():- rows = []- for aid, v in apps.items():- t = (info.get(aid) or {}).get("type")- if t and t.lower() not in ("game", "demo", "mod", "beta"):- continue- rows.append((aid, v))- rows.sort(key=lambda kv: -kv[1]["min"])- lasts = [v["last"] for _, v in rows if v["last"]]- accounts.append({- "account": f"acct{len(accounts) + 1}", "games_with_record": len(rows),- "games_played": sum(1 for _, v in rows if v["min"] > 0),- "total_h": round(sum(v["min"] for _, v in rows) / 60, 1),- "h_last_2wk": round(sum(v["min2wk"] for _, v in rows) / 60, 1),- "played_7d": sum(1 for x in lasts if time.time() - x <= 7 * 86400),- "played_30d": sum(1 for x in lasts if time.time() - x <= 30 * 86400),- "last_played": _iso(max(lasts)) if lasts else None,- "top": [[(info.get(a) or {}).get("name") or names.get(a) or f"app{a}", round(v["min"] / 60, 1), _iso(v["last"])]- for a, v in rows[:10] if v["min"]]})- accounts.sort(key=lambda a: -a["total_h"])- return {"present": True, "accounts": len(accounts), "total_hours": round(sum(a["total_h"] for a in accounts), 1),- "played_last_30d": max((a["played_30d"] for a in accounts), default=0), "per_account": accounts}---@probe(id="steam.appinfo_genres", level="L2", family="gaming", tier="T0", collect="extended", gate="steam.present")-def steam_appinfo_genres(h, facts):- """Genre hours per account from binary appinfo.vdf (static genre-id map)."""- st = _steam(h)- if not st or not st.get("users"):- return {"present": False}- want = set()- for apps in st["users"].values():- want |= {a for a, v in apps.items() if v["min"] > 0}- info = _appinfo(h, want)- out = []- for i, apps in enumerate(st["users"].values()):- gh = collections.Counter()- for a, v in apps.items():- for g in (info.get(a) or {}).get("genres", []):- if g not in ("Free to Play", "Early Access"):- gh[g] += v["min"] / 60- out.append({"account": f"acct{i + 1}", "genre_h": [[g, round(x, 1)] for g, x in gh.most_common(8)]})- return {"present": True, "resolved": len(info), "unresolved": len(want - set(info)), "per_account": out}---@probe(id="steam.local_sessions", level="L2", family="gaming", tier="T1", collect="core", gate="steam.present")-def steam_local_sessions(h, facts):- """Per-machine play sessions from gameprocess_log: hours, last-30-day hours, start hour and weekday histograms."""- st = _steam(h)- if not st:- return {"present": False}- rx_add = re.compile(r"^\[(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)\] AppID (\d+) adding PID")- rx_end = re.compile(r"^\[(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)\] Remove (\d+) from running list")- active, sessions, first = {}, [], None- for fn in ("gameprocess_log.previous.txt", "gameprocess_log.txt"):- txt = _read(os.path.join(st["path"], "logs", fn), 20_000_000)- if not txt:- continue- last_ts = None- for line in txt.splitlines():- if not line.startswith("[20"):- continue- if first is None:- first = line[1:11]- if "] Client version:" in line and active and last_ts:- sessions += [(a, s0, last_ts) for a, s0 in active.items()]- active = {}- try:- last_ts = dt.datetime.strptime(line[1:20], "%Y-%m-%d %H:%M:%S")- except ValueError:- continue- m = rx_add.match(line)- if m:- active.setdefault(int(m.group(2)), last_ts)- continue- m = rx_end.match(line)- if m and int(m.group(2)) in active:- sessions.append((int(m.group(2)), active.pop(int(m.group(2))), last_ts))- dropped = sum(1 for _, s0, e0 in sessions if (e0 - s0).total_seconds() > 16 * 3600)- sessions = [x for x in sessions if (x[2] - x[1]).total_seconds() <= 16 * 3600]- if not sessions:- return {"present": False, "log_starts": first}- per = {}- hh, dh = [0] * 24, [0] * 7- now = dt.datetime.now()- for a, s0, e0 in sessions:- p = per.setdefault(a, [0, 0.0, ""])- p[0] += 1- p[1] += max(0, (e0 - s0).total_seconds()) / 3600- p[2] = max(p[2], e0.strftime("%Y-%m-%d"))- hh[s0.hour] += 1- dh[s0.weekday()] += 1- names = {x["appid"]: x["name"] for x in st["installed"]}- top_ids = sorted(per, key=lambda a: -per[a][1])[:10]- info = _appinfo(h, set(top_ids) - set(names))- return {"present": True, "log_starts": first, "sessions": len(sessions), "dropped_over_16h": dropped, "apps": len(per),- "total_hours": round(sum(p[1] for p in per.values()), 1),- "hours_30d": round(sum(max(0, (e - s).total_seconds()) / 3600 for _, s, e in sessions if (now - e).days <= 30), 1),- "start_hours": hh, "start_dow_hist_mon0": dh,- "top": [[names.get(a) or (info.get(a) or {}).get("name") or f"app{a}", per[a][0], round(per[a][1], 1), per[a][2]]- for a in top_ids]}---@probe(id="steam.non_steam_shortcuts", level="L2", family="gaming", tier="T0", collect="core", gate="steam.present")-def steam_non_steam_shortcuts(h, facts):- """Count of non-Steam game shortcuts (shortcuts.vdf entries) per account; count only."""- st = _steam(h)- if not st:- return {"present": False}- total, files = 0, 0- for uid in st["uids"]:- p = os.path.join(st["path"], "userdata", uid, "config", "shortcuts.vdf")- try:- with open(p, "rb") as f:- data = f.read(5_000_000)- except OSError:- continue- files += 1- total += len(re.findall(rb"\x01(?i:appname)\x00", data))- return {"present": files > 0, "files": files, "shortcuts": total}---@probe(id="steam.screenshots", level="L2", family="gaming", tier="T0", collect="core", gate="steam.present")-def steam_screenshots(h, facts):- """Steam screenshot counts per account (userdata\\*\\760\\remote, depth <= 3)."""- st = _steam(h)- if not st:- return {"present": False}- counts = []- for uid in st["uids"]:- rem = os.path.join(st["path"], "userdata", uid, "760", "remote")- n, seen = 0, 0- for root, dirs, files in os.walk(rem):- seen += 1- if seen > 2000 or root.count(os.sep) - rem.count(os.sep) >= 3:- dirs[:] = []- n += sum(1 for f in files if f.lower().endswith((".jpg", ".png")))- counts.append(n)- return {"present": True, "accounts": len(counts), "screenshots": sum(counts), "per_account": counts}---@probe(id="steam.login_users", level="L2", family="gaming", tier="T2", collect="extended", gate="steam.present")-def steam_login_users(h, facts):- """loginusers.vdf: account count, last-login dates, autologin; persona names (T2). Login AccountName never emitted."""- st = _steam(h)- if not st:- return {"present": False}- txt = _read(os.path.join(st["path"], "config", "loginusers.vdf"))- if not txt:- return {"present": False}- users = []- for _sid, v in (_ci(_vdf(txt), "users") or {}).items():- if isinstance(v, dict):- users.append({"persona_name": v.get("PersonaName"), "most_recent": v.get("MostRecent") == "1",- "auto_login": v.get("AutoLogin") == "1", "last_login": _iso(int(v.get("Timestamp", 0) or 0))})- return {"present": bool(users), "count": len(users), "users": users}---@probe(id="steam.remote_clients", level="L2", family="gaming", tier="T2", collect="deep", gate="steam.present")-def steam_remote_clients(h, facts):- """Steam Remote Play peers: peer count and hostnames of the user's other machines (T2)."""- st = _steam(h)- if not st:- return {"present": False}- txt = _read(os.path.join(st["path"], "config", "remoteclients.vdf"))- if not txt:- return {"present": False}- hn = re.findall(r'"hostname"\s+"([^"]*)"', txt)- return {"present": bool(hn), "count": len(hn), "hostnames": hn[:10]}---@probe(id="epic.present", level="L1", family="gaming", tier="T0", collect="core")-def epic_present(h, facts):- """Epic Games Launcher data dir present; gates Epic subtree."""- return {"present": True} if _ex(os.path.join(_paths()["PD"], "Epic", "EpicGamesLauncher")) else None---@probe(id="epic.installs", level="L2", family="gaming", tier="T0", collect="core", gate="epic.present")-def epic_installs(h, facts):- """Epic installs: LauncherInstalled.dat, manifests (incl. Pending), game dirs with .egstore."""- P = _paths()- items = []- t = _read(os.path.join(P["PD"], "Epic", "UnrealEngineLauncher", "LauncherInstalled.dat"))- if t:- try:- items = [e.get("AppName") for e in json.loads(t).get("InstallationList", [])]- except Exception:- pass- man = os.path.join(P["PD"], "Epic", "EpicGamesLauncher", "Data", "Manifests")- manifests = []- for sub in ("", "Pending"):- d = os.path.join(man, sub)- for n in h.list_dir(d, 500):- if n.endswith(".item"):- try:- j = json.loads(_read(os.path.join(d, n)) or "{}")- manifests.append([j.get("DisplayName"), round((j.get("InstallSize") or 0) / 1e9, 1), bool(sub)])- except Exception:- pass- dirs = []- for base in (os.path.join(P["PF"], "Epic Games"), os.path.join(P["PF86"], "Epic Games")):- for n in h.list_dir(base, 200):- if n not in ("Launcher", "DirectXRedist", "Epic Online Services") and _ex(os.path.join(base, n, ".egstore")):- dirs.append(n)- return {"present": True, "launcher": _unmatch(h, r"Epic Games Launcher")[:1], "installed_list": items[:30],- "manifests": manifests[:30], "pending": sum(1 for m in manifests if m[2]), "egstore_dirs": dirs[:30]}---@probe(id="xbox.present", level="L1", family="gaming", tier="T0", collect="core")-def xbox_present(h, facts):- """Xbox app package dir present (inbox app, weak alone)."""- pk = os.path.join(_paths()["LAD"], "Packages")- app = _ex(os.path.join(pk, "Microsoft.GamingApp_8wekyb3d8bbwe"))- bar = _ex(os.path.join(pk, "Microsoft.XboxGamingOverlay_8wekyb3d8bbwe"))- return {"present": True, "xbox_app": app, "game_bar": bar} if (app or bar) else None---@probe(id="xbox.gamepass", level="L2", family="gaming", tier="T0", collect="core", gate="xbox.present")-def xbox_gamepass(h, facts):- """Game Pass / Gaming Services installs: package repository, XboxGames dirs, ModifiableWindowsApps."""- repo = _reg_keys(h, r"HKLM\SOFTWARE\Microsoft\GamingServices\PackageRepository\Root", 500)- dirs = []- for d in (r"C:\XboxGames", r"D:\XboxGames", r"E:\XboxGames"):- dirs += [n for n in h.list_dir(d, 200) if n != "GameSave"]- mwa = h.count_dir(os.path.join(_paths()["PF"], "ModifiableWindowsApps"), 500)- return {"present": True, "gaming_services_repo": len(repo), "xboxgames_dirs": len(dirs),- "modifiable_windows_apps": max(mwa, 0),- "game_mode_auto": h.reg(r"HKCU\Software\Microsoft\GameBar", "AutoGameModeEnabled"),- "gamedvr_capture": h.reg(r"HKCU\Software\Microsoft\Windows\CurrentVersion\GameDVR", "AppCaptureEnabled")}---@probe(id="gcs.present", level="L1", family="gaming", tier="T0", collect="core")-def gcs_present(h, facts):- """GameConfigStore Children key present (Game Bar game classification); gates gcs.game_history."""- n = len(_reg_keys(h, r"HKCU\System\GameConfigStore\Children", 5000))- return {"present": True, "children": n} if n else None---@probe(id="gcs.game_history", level="L2", family="gaming", tier="T2", collect="core", gate="gcs.present")-def gcs_game_history(h, facts):- """Game exes ever run (incl. since uninstalled) from GameConfigStore; game names and launcher, paths stripped."""- base = r"HKCU\System\GameConfigStore\Children"- by = {}- for sk in _reg_keys(h, base, 2000):- v = _reg_values(base + "\\" + sk, 100)- exe = v.get("MatchedExeFullPath")- if not exe or _noise(exe):- continue- low = exe.lower()- launcher = ("steam" if "\\steamapps\\" in low else "epic" if "\\epic games\\" in low else- "riot" if "riot games" in low else "xbox" if ("xboxgames" in low or "windowsapps" in low) else- "ea" if ("\\ea games\\" in low or "electronic arts" in low) else "ubisoft" if "ubisoft" in low else- "rockstar" if "rockstar" in low else "gog" if "gog" in low else "other")- m = re.search(r"\\(?:steamapps\\common|Epic Games|Riot Games|Rockstar Games|Games|XboxGames)\\([^\\]+)", exe, re.I)- game = m.group(1) if m else (exe.split("\\")[1] if re.match(r"^[A-Z]:\\[^\\]+\\", exe) else _base(exe))- la = v.get("LastAccessed")- t = _ft(la) if isinstance(la, int) else None- ts = t.timestamp() if t else None- k = game.lower()- cur = by.get(k)- present = _ex(exe)- if cur is None or (ts or 0) > (cur["ts"] or 0):- by[k] = {"game": game, "launcher": launcher, "ts": ts, "present": present or (cur or {}).get("present", False)}- elif present:- cur["present"] = True- if not by:- return {"present": False}- games = sorted(by.values(), key=lambda g: -(g["ts"] or 0))- return {"present": True, "distinct_games": len(games),- "uninstalled_since": sum(1 for g in games if not g["present"]),- "last_30d": sum(1 for g in games if g["ts"] and time.time() - g["ts"] <= 30 * 86400),- "by_launcher": dict(collections.Counter(g["launcher"] for g in games)),- "games": [[g["game"], g["launcher"], _iso(g["ts"]), g["present"]] for g in games[:30]]}---@probe(id="launchers.other", level="L1", family="gaming", tier="T0", collect="core")-def launchers_other(h, facts):- """Presence of Battle.net, Riot, EA, Ubisoft, GOG, Rockstar, Amazon, Playnite, Heroic launchers."""- P = _paths()- cands = {- "battlenet": [os.path.join(P["PF86"], "Battle.net"), os.path.join(P["PD"], "Battle.net")],- "riot": [r"C:\Riot Games", os.path.join(P["LAD"], "Riot Games")],- "ea": [os.path.join(P["PD"], "EA Desktop"), os.path.join(P["RAD"], "Electronic Arts"), os.path.join(P["LAD"], "Electronic Arts")],- "ubisoft": [os.path.join(P["PF86"], "Ubisoft"), os.path.join(P["LAD"], "Ubisoft Game Launcher")],- "gog": [os.path.join(P["PF86"], "GOG Galaxy"), os.path.join(P["PD"], "GOG.com")],- "rockstar": [os.path.join(P["PF"], "Rockstar Games"), os.path.join(P["LAD"], "Rockstar Games")],- "amazon": [os.path.join(P["LAD"], "Amazon Games")],- "playnite": [os.path.join(P["RAD"], "Playnite"), os.path.join(P["LAD"], "Playnite")],- "heroic": [os.path.join(P["RAD"], "heroic")],- }- hits = sorted(k for k, ps in cands.items() if any(_ex(p) for p in ps))- return {"present": True, "launchers": hits} if hits else None---@probe(id="emulators", level="L1", family="gaming", tier="T0", collect="core")-def emulators(h, facts):- """Emulator config dirs (RetroArch, Ryujinx, yuzu, Dolphin, PCSX2, RPCS3, Cemu, ...)."""- P = _paths()- docs = os.path.join(P["HOME"], "Documents")- cands = {"RetroArch": [os.path.join(P["RAD"], "RetroArch"), r"C:\RetroArch-Win64"], "Ryujinx": [os.path.join(P["RAD"], "Ryujinx")],- "yuzu/suyu": [os.path.join(P["RAD"], "yuzu"), os.path.join(P["RAD"], "suyu")],- "Dolphin": [os.path.join(P["RAD"], "Dolphin Emulator"), os.path.join(docs, "Dolphin Emulator")],- "PCSX2": [os.path.join(P["RAD"], "PCSX2"), os.path.join(docs, "PCSX2")], "RPCS3": [os.path.join(P["RAD"], "rpcs3")],- "Cemu": [os.path.join(P["RAD"], "Cemu")], "DuckStation": [os.path.join(docs, "DuckStation")],- "PPSSPP": [os.path.join(docs, "PPSSPP")], "xemu": [os.path.join(P["RAD"], "xemu")],- "Xenia": [os.path.join(docs, "Xenia")], "melonDS": [os.path.join(P["RAD"], "melonDS")]}- hits = sorted(k for k, ps in cands.items() if any(_ex(p) for p in ps))- return {"present": True, "found": hits} if hits else None---@probe(id="gaming.anticheat", level="L1", family="gaming", tier="T0", collect="core")-def gaming_anticheat(h, facts):- """Anti-cheat drivers/dirs (BattlEye, EasyAntiCheat, Vanguard, FACEIT): competitive-shooter hint."""- P = _paths()- cands = {"BattlEye": [os.path.join(P["LAD"], "BattlEye"), os.path.join(P["PF86"], "Common Files", "BattlEye")],- "EasyAntiCheat": [os.path.join(P["PF86"], "EasyAntiCheat_EOS"), os.path.join(P["PF86"], "EasyAntiCheat")],- "Vanguard": [os.path.join(P["PF"], "Riot Vanguard")], "FACEIT": [os.path.join(P["PF"], "FACEIT AC")]}- hits = sorted(k for k, ps in cands.items() if any(_ex(p) for p in ps))- return {"present": True, "found": hits} if hits else None---@probe(id="gaming.secondary_drive", level="L1", family="gaming", tier="T0", collect="core")-def gaming_secondary_drive(h, facts):- """Game folders on D:/E: (Games, SteamLibrary, XboxGames, Epic Games, GOG Games) with entry counts."""- out = []- for drv in ("D:\\", "E:\\", "F:\\"):- if not _ex(drv):- continue- for n in ("Games", "SteamLibrary", "XboxGames", "Epic Games", "GOG Games"):- p = os.path.join(drv, n)- if _ex(p):- out.append([p, max(h.count_dir(p, 1000), 0)])- return {"present": True, "dirs": out} if out else None---@probe(id="gaming.save_roots", level="L1", family="gaming", tier="T0", collect="core")-def gaming_save_roots(h, facts):- """My Games / Saved Games / LocalLow roots exist; gates gaming.save_dirs."""- home = os.path.expanduser("~")- roots = [p for p in (os.path.join(home, "Documents", "My Games"), os.path.join(home, "Saved Games"),- os.path.join(home, "AppData", "LocalLow")) if _ex(p)]- return {"present": True, "roots": len(roots)} if roots else None---@probe(id="gaming.save_dirs", level="L2", family="gaming", tier="T2", collect="extended", gate="gaming.save_roots")-def gaming_save_dirs(h, facts):- """Game titles/publishers from My Games, Saved Games and LocalLow dir names (bounded listdir)."""- home = os.path.expanduser("~")- skip = {"microsoft", "nvidia", "intel", "adobe", "com.adobe.crashreporter", "temp", "desktop.ini", "sun", "oracle",- "unity", "google", "mozilla", "igdump"}- out = {}- for key, p in (("my_games", os.path.join(home, "Documents", "My Games")), ("saved_games", os.path.join(home, "Saved Games")),- ("locallow", os.path.join(home, "AppData", "LocalLow"))):- names = [n for n in h.list_dir(p, 300) if n.lower() not in skip and not n.endswith(".ini")- and not re.fullmatch(r"[0-9a-fA-F-]{32,}", n) and not _noise("\\" + n + "\\")]- out[key] = sorted(names)[:40]- return {"present": any(out.values()), **out}---# ================================================================= MEDIA--@probe(id="nvidia.app", level="L1", family="hardware", tier="T0", collect="core")-def nvidia_app(h, facts):- """NVIDIA App backend dir present; gates the NVIDIA subtree."""- return {"present": True} if _ex(os.path.join(_paths()["LAD"], "NVIDIA Corporation", "NVIDIA App", "NvBackend")) else None---@probe(id="nvidia.library", level="L2", family="gaming", tier="T0", collect="core", gate="nvidia.app")-def nvidia_library(h, facts):- """Apps and games detected by NVIDIA App (ApplicationStorage.json)."""- p = os.path.join(_paths()["LAD"], "NVIDIA Corporation", "NVIDIA App", "NvBackend", "ApplicationStorage.json")- t = _read(p)- if not t:- return {"present": False}- try:- j = json.loads(t)- except Exception:- return {"present": False, "error": "json"}- names = []- for a in j.get("Applications", [])[:500]:- ap = a.get("Application", a) if isinstance(a, dict) else {}- if ap.get("DisplayName"):- names.append(ap["DisplayName"])- return {"present": bool(names), "count": len(names), "apps": names[:40], "mtime": _mtime(p),- "app_version": (_unmatch(h, r"^NVIDIA App \d") or [{}])[0].get("version")}---@probe(id="nvidia.recommendations", level="L2", family="gaming", tier="T2", collect="core", gate="nvidia.app")-def nvidia_recommendations(h, facts):- """Per-game optimisation dirs in NvBackend\\Recommendations; persist after uninstall (game history)."""- d = os.path.join(_paths()["LAD"], "NVIDIA Corporation", "NVIDIA App", "NvBackend", "Recommendations")- names = sorted(n for n in h.list_dir(d, 500) if os.path.isdir(os.path.join(d, n)))- return {"present": bool(names), "count": len(names), "games": names[:60]}---@probe(id="captures.nvidia", level="L2", family="media", tier="T2", collect="core", gate="nvidia.app")-def captures_nvidia(h, facts):- """NVIDIA overlay captures: file count and size; per-game folder counts (folder names are game titles)."""- P = _paths()- capdir = None- t = _read(os.path.join(P["LAD"], "NVIDIA Corporation", "NVIDIA Overlay", "GallerySettings.json"))- if t:- try:- capdir = json.loads(t).get("settings", {}).get("currentDirectoryV2")- except Exception:- pass- capdir = capdir or os.path.join(P["HOME"], "Videos", "NVIDIA")- if not _ex(capdir):- return {"present": False}- n = b = seen = 0- per = {}- for root, dirs, files in os.walk(capdir):- seen += 1- if seen > 500 or root.count(os.sep) - capdir.count(os.sep) >= 2:- dirs[:] = []- for f in files[:5000]:- n += 1- try:- b += os.path.getsize(os.path.join(root, f))- except OSError:- pass- if root != capdir and files:- per[os.path.basename(root)] = len(files)- return {"present": True, "dir_is_default": capdir.lower().endswith("videos\\nvidia"), "files": n,- "mb": round(b / 1e6), "game_folders": dict(sorted(per.items(), key=lambda kv: -kv[1])[:20])}---@probe(id="captures.gamebar", level="L2", family="media", tier="T0", collect="core", gate="xbox.present")-def captures_gamebar(h, facts):- """Game Bar captures dir (Videos\\Captures): file count and size."""- cap = os.path.join(os.path.expanduser("~"), "Videos", "Captures")- n = b = 0- try:- with os.scandir(cap) as it:- for e in it:- if n >= 5000:- break- if e.is_file():- n += 1- b += e.stat().st_size- except OSError:- return {"present": False}- return {"present": True, "files": n, "mb": round(b / 1e6)}---@probe(id="nvidia.shadowplay", level="L1", family="media", tier="T0", collect="core")-def nvidia_shadowplay(h, facts):- """NVIDIA overlay/instant replay/highlights/mic flags (NVSPCAPS REG_BINARY dwords)."""- sp = r"HKCU\Software\NVIDIA Corporation\Global\ShadowPlay\NVSPCAPS"- out = {}- for k, name in (("overlay_enabled", "IsShadowPlayEnabledUser"), ("instant_replay_or_rec", "RecEnabled"),- ("highlights", "HLEnabled"), ("mic", "EnableMicrophone")):- v = h.reg(sp, name)- if isinstance(v, (bytes, bytearray)) and len(v) >= 4:- v = int.from_bytes(v[:4], "little")- if v is not None:- out[k] = v- return {"present": True, **out} if out else None---@probe(id="nvidia.broadcast", level="L1", family="media", tier="T0", collect="core")-def nvidia_broadcast(h, facts):- """NVIDIA Broadcast / G-Assist presence."""- P = _paths()- b = any(_ex(p) for p in (os.path.join(P["PD"], "NVIDIA Corporation", "NVIDIA Broadcast"),- os.path.join(P["PF"], "NVIDIA Corporation", "NVIDIA Broadcast")))- g = _ex(os.path.join(P["PD"], "NVIDIA Corporation", "nvtopps", "rise")) or _ex(os.path.join(P["PF"], "NVIDIA Corporation", "NVIDIA G-Assist"))- return {"present": True, "broadcast": b, "g_assist": g} if (b or g) else None---@probe(id="media.obs", level="L1", family="media", tier="T0", collect="core")-def media_obs(h, facts):- """OBS/Streamlabs presence and whether a config dir exists (launched at least once); agent-container copies flagged."""- P = _paths()- installs, configs = [], []- if _ex(os.path.join(P["PF"], "obs-studio")):- installs.append("program_files")- wg = os.path.join(P["LAD"], "Microsoft", "WinGet", "Packages")- for n in h.list_dir(wg, 1000):- if n.lower().startswith("obsproject.obsstudio"):- installs.append("winget_portable")- if _ex(os.path.join(wg, n, "config", "obs-studio")):- configs.append("winget_portable")- if _ex(os.path.join(P["RAD"], "obs-studio")):- configs.append("roaming")- agent_cfg = 0- for n in h.list_dir(os.path.join(P["LAD"], "Packages"), 2000):- if n.lower().startswith(("openai.codex", "anthropic.claude")):- if _ex(os.path.join(P["LAD"], "Packages", n, "LocalCache", "Roaming", "obs-studio")):- agent_cfg += 1- sl = _ex(os.path.join(P["PF"], "Streamlabs OBS"))- sl_cfg = _ex(os.path.join(P["RAD"], "slobs-client"))- if not (installs or configs or sl or agent_cfg):- return None- return {"present": True, "obs_installs": installs, "obs_configs": configs, "config_dir": bool(configs), "obs_config_in_agent_container": agent_cfg,- "streamlabs": sl, "streamlabs_config": sl_cfg}---@probe(id="media.players", level="L1", family="media", tier="T0", collect="core")-def media_players(h, facts):- """Music/video players and streaming apps (Spotify, Apple Music, Store players, mpv, Plex, ...)."""- P = _paths()- pkgs = [n.lower() for n in h.list_dir(os.path.join(P["LAD"], "Packages"), 3000)]-- def pkg(prefix):- return any(n.startswith(prefix.lower()) for n in pkgs)- found = {"spotify": _ex(os.path.join(P["RAD"], "Spotify")) or pkg("SpotifyAB.SpotifyMusic"),- "apple_music": pkg("AppleInc.AppleMusic"), "media_player_uwp": pkg("Microsoft.ZuneMusic"),- "netflix": pkg("4DF9E0F8.Netflix"), "prime_video": pkg("AmazonVideo.PrimeVideo"), "disney": pkg("Disney."),- "mpv": _ex(os.path.join(P["RAD"], "mpv")), "mpc_hc": _ex(os.path.join(P["PF"], "MPC-HC")),- "potplayer": _ex(os.path.join(P["PF"], "DAUM", "PotPlayer")), "foobar2000": _ex(os.path.join(P["RAD"], "foobar2000")),- "musicbee": _ex(os.path.join(P["RAD"], "MusicBee")), "plex": _ex(os.path.join(P["LAD"], "Plex")),- "kodi": _ex(os.path.join(P["RAD"], "Kodi")), "tidal": _ex(os.path.join(P["LAD"], "TIDAL"))}- hits = sorted(k for k, v in found.items() if v)- return {"present": True, "players": hits} if hits else None---@probe(id="media.vlc", level="L1", family="media", tier="T0", collect="core")-def media_vlc(h, facts):- """VLC installed and whether a user config exists."""- P = _paths()- inst = _ex(os.path.join(P["PF"], "VideoLAN", "VLC")) or _ex(os.path.join(P["PF86"], "VideoLAN", "VLC"))- cfg = _ex(os.path.join(P["RAD"], "vlc"))- return {"present": True, "installed": inst, "user_config": cfg} if (inst or cfg) else None---@probe(id="media.vlc_recents", level="L2", family="media", tier="T2", collect="extended", gate="media.vlc")-def media_vlc_recents(h, facts):- """VLC recent-media count, local vs stream split and extension histogram; the MRL list itself is not emitted."""- qi = os.path.join(_paths()["RAD"], "vlc", "vlc-qt-interface.ini")- t = _read(qi, 2_000_000)- if not t:- return {"present": False}- m = re.search(r"^\[RecentsMRL\][^\[]*?^list=(.*)$", t, re.M | re.S)- items = [x.strip() for x in m.group(1).split(",") if x.strip()] if m else []- kinds = collections.Counter("local" if x.startswith("file:") else "stream" for x in items)- exts = collections.Counter()- for x in items:- if x.startswith("file:"):- m2 = re.search(r"\.([A-Za-z0-9]{1,5})$", x.split("?")[0])- exts["." + m2.group(1).lower() if m2 else ""] += 1- own = sum(1 for x in items if "/Videos/Captures/" in x or "/Videos/NVIDIA/" in x)- return {"present": bool(items), "count": len(items), "kinds": dict(kinds), "ext": dict(exts),- "from_own_capture_dirs": own, "ini_mtime": _mtime(qi)}---_MEDIA_EXT = {"video": {".mp4", ".mkv", ".avi", ".mov", ".webm", ".wmv", ".m4v", ".flv", ".ts"},- "audio": {".mp3", ".flac", ".m4a", ".wav", ".ogg", ".opus", ".aac", ".wma"},- "image": {".jpg", ".jpeg", ".png", ".gif", ".webp", ".heic", ".bmp", ".tif", ".tiff", ".raw", ".dng", ".jxr"}}---def _walk_media(root, max_depth=4, max_files=20000, budget_s=1.5):- t0 = time.perf_counter()- st = {"files": 0, "bytes": 0, "video": 0, "audio": 0, "image": 0, "cloud_only": 0, "truncated": False}- stack = [(root, 0)]- while stack:- p, dep = stack.pop()- if _noise(p + "\\"):- continue- try:- it = os.scandir(p)- except OSError:- continue- with it:- for e in it:- if time.perf_counter() - t0 > budget_s or st["files"] >= max_files:- st["truncated"] = True- return st- try:- if e.is_dir(follow_symlinks=False):- if dep < max_depth:- stack.append((e.path, dep + 1))- continue- s = e.stat(follow_symlinks=False)- except OSError:- continue- st["files"] += 1- if getattr(s, "st_file_attributes", 0) & (0x400000 | 0x1000):- st["cloud_only"] += 1- else:- st["bytes"] += s.st_size- ext = os.path.splitext(e.name)[1].lower()- for k, exts in _MEDIA_EXT.items():- if ext in exts:- st[k] += 1- break- return st---@probe(id="media.libraries", level="L1", family="media", tier="T1", collect="core")-def media_libraries(h, facts):- """Music/Videos/Pictures known-folder file counts by type and size (bounded walk), plus Screenshots count."""- home = os.path.expanduser("~")- usf = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"- out = {}- for short, regname in (("Music", "My Music"), ("Videos", "My Video"), ("Pictures", "My Pictures")):- p = os.path.expandvars(h.reg(usf, regname) or os.path.join(home, short))- s = _walk_media(p)- s["gb"] = round(s.pop("bytes") / 1e9, 2)- s["onedrive"] = "onedrive" in p.lower()- out[short] = s- out["screenshots"] = max(h.count_dir(os.path.join(home, "Pictures", "Screenshots"), 20000), 0)- return {"present": True, **out}---# ================================================================= HARDWARE--@probe(id="hw.system", level="L1", family="hardware", tier="T0", collect="core")-def hw_system(h, facts):- """SMBIOS system/board/BIOS from registry, visible RAM (GlobalMemoryStatusEx), fixed-drive free space."""- import ctypes- b = _reg_values(r"HKLM\HARDWARE\DESCRIPTION\System\BIOS", 100)-- class MEMSTAT(ctypes.Structure):- _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong)] + [- (n, ctypes.c_ulonglong) for n in ("total", "avail", "tpf", "apf", "tv", "av", "aev")]- ms = MEMSTAT()- ms.dwLength = ctypes.sizeof(ms)- ram = None- if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(ms)):- ram = round(ms.total / 2 ** 30, 1)- drives = []- k32 = ctypes.windll.kernel32- mask = k32.GetLogicalDrives()- for i in range(26):- if not mask & (1 << i):- continue- root = chr(65 + i) + ":\\"- if k32.GetDriveTypeW(ctypes.c_wchar_p(root)) != 3:- continue- free, total = ctypes.c_ulonglong(0), ctypes.c_ulonglong(0)- if k32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(root), None, ctypes.byref(total), ctypes.byref(free)) and total.value:- drives.append([root[:2], round(total.value / 1e9, 1), round(free.value / 1e9, 1),- round(100 * free.value / total.value, 1)])- return {"present": True, "manufacturer": b.get("SystemManufacturer"), "product": b.get("SystemProductName"),- "family": b.get("SystemFamily"), "board_vendor": b.get("BaseBoardManufacturer"),- "board": b.get("BaseBoardProduct"), "bios_vendor": b.get("BIOSVendor"), "bios_version": b.get("BIOSVersion"),- "bios_date": b.get("BIOSReleaseDate"), "visible_ram_gb": ram, "memory_load_pct": ms.dwMemoryLoad if ram else None,- "fixed_drives_total_free_gb_pct": drives}---@probe(id="hw.cpu", level="L2", family="hardware", tier="T0", collect="core", gate="hw.system")-def hw_cpu(h, facts):- """CPU name, vendor, MHz and logical processor count from HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor."""- base = r"HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor"- cores = _reg_keys(h, base, 1024)- v = _reg_values(base + "\\0", 50)- if not v:- return {"present": False}- return {"present": True, "name": (v.get("ProcessorNameString") or "").strip(), "vendor": v.get("VendorIdentifier"),- "mhz": v.get("~MHz"), "logical_processors": len(cores), "native_arch": h.l0.get("native_arch")}---@probe(id="hw.gpu", level="L1", family="hardware", tier="T0", collect="core")-def hw_gpu(h, facts):- """Display adapters from the Display class registry key: name, driver version, VRAM (qwMemorySize)."""- base = r"HKLM\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"- out = []- for sk in _reg_keys(h, base, 50):- if not sk.isdigit():- continue- v = _reg_values(base + "\\" + sk, 400)- name = v.get("DriverDesc")- if not name:- continue- mem = v.get("HardwareInformation.qwMemorySize")- if mem is None:- m2 = v.get("HardwareInformation.MemorySize")- mem = int.from_bytes(m2[:8], "little") if isinstance(m2, (bytes, bytearray)) else m2- out.append({"name": name, "driver": v.get("DriverVersion"), "driver_date": v.get("DriverDate"),- "vram_gb": round(mem / 2 ** 30, 1) if isinstance(mem, int) and mem > 0 else None,- "vendor": v.get("ProviderName")})- real = [g for g in out if not re.search(r"Microsoft Basic|Remote Display|Virtual|Parsec|Meta Virtual", g["name"], re.I)]- vr = [g["vram_gb"] for g in real if g["vram_gb"]]- return {"present": True, "max_vram_gb": max(vr) if vr else None, "adapters": real, "other": len(out) - len(real)} if out else None---@probe(id="hw.power_plan", level="L2", family="hardware", tier="T0", collect="core", gate="hw.system")-def hw_power_plan(h, facts):- """Active power scheme GUID and friendly name from registry; Modern Standby flag."""- known = {"381b4222-f694-41f0-9685-ff5bb260df2e": "Balanced", "8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c": "High performance",- "a1841308-3541-4fab-bc81-f71556f20b4a": "Power saver", "e9a42b02-d5df-448d-aa00-03f14749eb61": "Ultimate Performance"}- base = r"HKLM\SYSTEM\CurrentControlSet\Control\Power\User\PowerSchemes"- g = h.reg(base, "ActivePowerScheme")- if not g:- return {"present": False}- fname = h.reg(base + "\\" + g, "FriendlyName")- if fname and fname.startswith("@"):- fname = None- ov = {"ded574b5-45a0-4f42-8737-46345c09c238": "Best performance", "961cc777-2547-4f9d-8174-7d86181b8a7a": "Best power efficiency",- "00000000-0000-0000-0000-000000000000": "Balanced"}- ac = h.reg(base, "ActiveOverlayAcPowerScheme")- cs = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\Power", "CsEnabled")- return {"present": True, "guid": g, "name": known.get(g.lower()) or fname or "custom",- "overlay_ac": ov.get((ac or "").lower(), ac), "modern_standby": cs}---@probe(id="hw.battery", level="L1", family="hardware", tier="T0", collect="core")-def hw_battery(h, facts):- """Battery present (GetSystemPowerStatus + ACPI PNP0C0A); laptop vs desktop."""- import ctypes-- class SPS(ctypes.Structure):- _fields_ = [("ac", ctypes.c_ubyte), ("flag", ctypes.c_ubyte), ("pct", ctypes.c_ubyte), ("saver", ctypes.c_ubyte),- ("life", ctypes.c_ulong), ("full", ctypes.c_ulong)]- s = SPS()- ok = ctypes.windll.kernel32.GetSystemPowerStatus(ctypes.byref(s))- acpi = bool(_reg_keys(h, r"HKLM\SYSTEM\CurrentControlSet\Enum\ACPI\PNP0C0A", 10))- has = acpi or (ok and s.flag not in (128, 255))- if not has:- return None- return {"present": True, "on_ac": s.ac == 1 if ok else None, "charge_pct": s.pct if ok and s.pct <= 100 else None,- "battery_saver": bool(s.saver) if ok else None}---@probe(id="boot.fastboot", level="L1", family="hardware", tier="T0", collect="core")-def boot_fastboot(h, facts):- """Fast Startup (HiberbootEnabled): needed to read 'shutdown' events correctly."""- v = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power", "HiberbootEnabled")- hib = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\Power", "HibernateEnabled")- if v is None and hib is None:- return None- return {"present": True, "fast_startup": v, "hibernate_enabled": hib}---@probe(id="tuning.afterburner", level="L1", family="hardware", tier="T0", collect="core")-def tuning_afterburner(h, facts):- """MSI Afterburner: autostart, fan curve, logging, per-GPU profiles (power limit, offsets, VF curve)."""- ab = os.path.join(_paths()["PF86"], "MSI Afterburner")- if not _ex(ab):- return None- out = {"present": True}- t = _read(os.path.join(ab, "Profiles", "MSIAfterburner.cfg"), 500_000)- if t:- def k(n):- m = re.search(rf"^{n}=(.*)$", t, re.M)- return m.group(1).strip() if m else None- out.update(start_with_windows=k("StartWithWindows"), sw_fan_curve=k("SwAutoFanControl"),- hw_log=k("EnableHwMonitoringLog") or k("EnableLog"))- gpus = []- for f in h.list_dir(os.path.join(ab, "Profiles"), 100):- if f.startswith("VEN_") and not f.startswith("VEN_0000"):- tt = _read(os.path.join(ab, "Profiles", f), 500_000) or ""-- def g(n):- m = re.search(rf"^{n}=(\S+)", tt, re.M)- return m.group(1) if m else None- gpus.append({"vendor": {"10DE": "NVIDIA", "8086": "Intel", "1002": "AMD"}.get(f[4:8], f[4:8]), "dev": f[13:17],- "power_limit": g("PowerLimit"), "core_offset": g("CoreClkBoost"), "fan_mode": g("FanMode"),- "vf_curve": bool(g("VFCurve"))})- out["gpu_profiles"] = gpus- out["version"] = (_unmatch(h, r"MSI Afterburner") or [{}])[0].get("version")- return out---@probe(id="tuning.rtss", level="L1", family="hardware", tier="T0", collect="core")-def tuning_rtss(h, facts):- """RivaTuner Statistics Server presence and per-game profile count."""- rt = os.path.join(_paths()["PF86"], "RivaTuner Statistics Server")- if not _ex(rt):- return None- prof = [f for f in h.list_dir(os.path.join(rt, "Profiles"), 2000) if f.endswith(".cfg") and f.lower() != "global"]- return {"present": True, "profiles": len(prof)}---@probe(id="periph.rgb_suites", level="L2", family="hardware", tier="T0", collect="core", gate="hw.system")-def periph_rgb_suites(h, facts):- """RGB / peripheral vendor suites from the uninstall index (Razer, Logi, Corsair, ASUS Aura, OpenRGB, ...)."""- hits = _unmatch(h, r"Razer|Logi|G HUB|SteelSeries|Corsair|iCUE|HyperX|NGENUITY|Patriot Viper|Armoury|\bAura\b|OpenRGB|"- r"SignalRGB|Wallpaper Engine|DS4Windows|8BitDo|Xbox Accessories|Stream Deck|Elgato|Wooting|NZXT")- names = sorted({re.sub(r"\s+[\d.]+$", "", x["name"]) for x in hits})- return {"present": bool(names), "count": len(hits), "suites": names[:25]}---@probe(id="hw.audio", level="L2", family="hardware", tier="T1", collect="extended", gate="hw.system")-def hw_audio(h, facts):- """Audio endpoints from MMDevices registry: active render/capture counts and adapter interface names."""- base = r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio"- out = {"present": False}- for kind in ("Render", "Capture"):- keys = _reg_keys(h, base + "\\" + kind, 300)- active = []- for k in keys:- st = h.reg(base + "\\" + kind + "\\" + k, "DeviceState")- if st == 1:- iface = h.reg(base + "\\" + kind + "\\" + k + "\\Properties", "{b3f8fa53-0004-438e-9003-51a46e139bfc},6")- active.append(re.sub(r"(?i)\b[A-Z][a-z]+'s\b", "<name>'s", iface or "?"))- out[kind.lower()] = {"total": len(keys), "active": len(active), "active_ifaces": sorted(set(active))[:12]}- out["present"] = out["present"] or bool(keys)- return out---@probe(id="hw.bluetooth", level="L2", family="hardware", tier="T1", collect="extended", gate="hw.system")-def hw_bluetooth(h, facts):- """Paired Bluetooth devices by class (gamepad/audio/HID) from BTHPORT registry; device names not emitted."""- base = r"HKLM\SYSTEM\CurrentControlSet\Services\BTHPORT\Parameters\Devices"- keys = _reg_keys(h, base, 500)- major = {0: "Misc", 1: "Computer", 2: "Phone", 3: "LAN", 4: "Audio/Video", 5: "Peripheral", 6: "Imaging",- 7: "Wearable", 8: "Toy", 9: "Health", 31: "Uncategorized"}- cls = collections.Counter()- for k in keys:- cod = h.reg(base + "\\" + k, "COD") or 0- if isinstance(cod, bytes):- cod = int.from_bytes(cod[:4], "little")- maj, mn = (cod >> 8) & 0x1F, (cod >> 2) & 0x3F- sub = None- if maj == 5:- sub = {0x10: "Keyboard", 0x20: "Mouse", 0x30: "Keyboard+Mouse", 0x01: "Joystick", 0x02: "Gamepad"}.get(mn & 0x33)- elif maj == 4:- sub = {1: "Headset", 2: "Handsfree", 4: "Microphone", 5: "Loudspeaker", 6: "Headphones"}.get(mn)- if not sub:- raw = h.reg(base + "\\" + k, "Name")- nm = raw.decode("utf-8", "replace").strip("\0") if isinstance(raw, bytes) else ""- for rx, lbl in ((r"(?i)controller|gamepad|dualsense|dualshock|joy-?con", "Gamepad"),- (r"(?i)mouse|mx master|deathadder|mx anywhere", "Mouse"), (r"(?i)keyboard|keys\b", "Keyboard"),- (r"(?i)WH-|WF-|buds|airpods|headphone|headset", "Headphones"), (r"(?i)speaker|soundbar|kanto", "Speaker")):- if re.search(rx, nm):- sub = lbl + "(name)"- break- cls[major.get(maj, str(maj)) + ("/" + sub if sub else "")] += 1- le = sum(len(_reg_keys(h, r"HKLM\SYSTEM\CurrentControlSet\Enum\BTHLE\\" + d, 50))- for d in _reg_keys(h, r"HKLM\SYSTEM\CurrentControlSet\Enum\BTHLE", 300))- if not keys and not le:- return {"present": False}- return {"present": True, "classic_paired": len(keys), "ble_instances": le, "by_class": dict(cls)}---@probe(id="hw.usb_history", level="L2", family="hardware", tier="T1", collect="extended", gate="hw.system")-def hw_usb_history(h, facts):- """USB device ids/instances ever seen and USB storage count (Enum\\USB, USBSTOR); top vendor ids only."""- base = r"HKLM\SYSTEM\CurrentControlSet\Enum\USB"- ids = _reg_keys(h, base, 2000)- inst = 0- vids = collections.Counter()- for i in ids:- inst += len(_reg_keys(h, base + "\\" + i, 200))- m = re.search(r"VID_([0-9A-Fa-f]{4})", i)- if m:- vids[m.group(1).upper()] += 1- stor = sum(len(_reg_keys(h, r"HKLM\SYSTEM\CurrentControlSet\Enum\USBSTOR\\" + d, 100))- for d in _reg_keys(h, r"HKLM\SYSTEM\CurrentControlSet\Enum\USBSTOR", 500))- vend = {"046D": "Logitech", "1532": "Razer", "1B1C": "Corsair", "1038": "SteelSeries", "0B05": "ASUS", "045E": "Microsoft",- "054C": "Sony", "057E": "Nintendo", "28DE": "Valve", "3434": "Keychron", "0951": "Kingston/HyperX", "03F0": "HP/HyperX",- "8087": "Intel", "0BDA": "Realtek", "0955": "NVIDIA", "1462": "MSI", "05AC": "Apple", "04E8": "Samsung", "0781": "SanDisk"}- if not ids:- return {"present": False}- return {"present": True, "device_ids_ever": len(ids), "instances_ever": inst, "usbstor_instances": stor,- "top_vendors": [[v, vend.get(v), n] for v, n in vids.most_common(12)]}---@probe(id="hw.monitor_mode", level="L2", family="hardware", tier="T0", collect="extended", gate="hw.system")-def hw_monitor_mode(h, facts):- """Current resolution/refresh per display (EnumDisplaySettings); falls back to GraphicsDrivers\\Configuration."""- import ctypes- from ctypes import wintypes as W-- class DEVMODEW(ctypes.Structure):- _fields_ = [("dmDeviceName", ctypes.c_wchar * 32), ("dmSpecVersion", W.WORD), ("dmDriverVersion", W.WORD),- ("dmSize", W.WORD), ("dmDriverExtra", W.WORD), ("dmFields", W.DWORD), ("dmPositionX", W.LONG),- ("dmPositionY", W.LONG), ("dmDisplayOrientation", W.DWORD), ("dmDisplayFixedOutput", W.DWORD),- ("dmColor", ctypes.c_short), ("dmDuplex", ctypes.c_short), ("dmYResolution", ctypes.c_short),- ("dmTTOption", ctypes.c_short), ("dmCollate", ctypes.c_short), ("dmFormName", ctypes.c_wchar * 32),- ("dmLogPixels", W.WORD), ("dmBitsPerPel", W.DWORD), ("dmPelsWidth", W.DWORD), ("dmPelsHeight", W.DWORD),- ("dmDisplayFlags", W.DWORD), ("dmDisplayFrequency", W.DWORD), ("dmICMMethod", W.DWORD),- ("dmICMIntent", W.DWORD), ("dmMediaType", W.DWORD), ("dmDitherType", W.DWORD), ("dmReserved1", W.DWORD),- ("dmReserved2", W.DWORD), ("dmPanningWidth", W.DWORD), ("dmPanningHeight", W.DWORD)]-- class DISPLAY_DEVICEW(ctypes.Structure):- _fields_ = [("cb", W.DWORD), ("DeviceName", ctypes.c_wchar * 32), ("DeviceString", ctypes.c_wchar * 128),- ("StateFlags", W.DWORD), ("DeviceID", ctypes.c_wchar * 128), ("DeviceKey", ctypes.c_wchar * 128)]- u32 = ctypes.windll.user32- modes = []- i = 0- while i < 16:- dd = DISPLAY_DEVICEW()- dd.cb = ctypes.sizeof(dd)- if not u32.EnumDisplayDevicesW(None, i, ctypes.byref(dd), 0):- break- i += 1- if not dd.StateFlags & 1:- continue- dm = DEVMODEW()- dm.dmSize = ctypes.sizeof(dm)- if u32.EnumDisplaySettingsW(dd.DeviceName, -1, ctypes.byref(dm)):- modes.append({"w": dm.dmPelsWidth, "h": dm.dmPelsHeight, "hz": dm.dmDisplayFrequency, "adapter": dd.DeviceString})- if modes:- return {"present": True, "via": "EnumDisplaySettings", "displays": modes}- base = r"HKLM\SYSTEM\CurrentControlSet\Control\GraphicsDrivers\Configuration"- best, best_ts = None, -1- for cfg in _reg_keys(h, base, 200):- ts = h.reg(base + "\\" + cfg, "Timestamp") or 0- if isinstance(ts, int) and ts > best_ts:- best, best_ts = cfg, ts- if not best:- return {"present": False}- out = []- for t in _reg_keys(h, base + "\\" + best, 20):- for m in _reg_keys(h, base + "\\" + best + "\\" + t, 20):- v = _reg_values(base + "\\" + best + "\\" + t + "\\" + m, 100)- if v.get("PrimSurfSize.cx"):- num, den = v.get("VSyncFreq.Numerator"), v.get("VSyncFreq.Denominator")- out.append({"w": v["PrimSurfSize.cx"], "h": v.get("PrimSurfSize.cy"),- "hz": round(num / den, 1) if num and den else None})- return {"present": bool(out), "via": "GraphicsDrivers\\Configuration", "committed": _iso(_ft(best_ts)), "displays": out}---@probe(id="hw.nvidia_smi", level="L2", family="hardware", tier="T0", collect="extended", gate="hw.gpu")-def hw_nvidia_smi(h, facts):- """nvidia-smi query: VRAM, power draw/limit, temperature, pstate, driver."""- P = _paths()- exe = next((p for p in (os.path.join(P["WIN"], "System32", "nvidia-smi.exe"),- os.path.join(P["PF"], "NVIDIA Corporation", "NVSMI", "nvidia-smi.exe")) if _ex(p)), None)- if not exe:- return {"present": False}- fields = "name,memory.total,power.draw,power.limit,power.default_limit,power.max_limit,temperature.gpu,pstate,driver_version,fan.speed"- out = h.run([exe, "--query-gpu=" + fields, "--format=csv,noheader,nounits"], timeout_ms=5000, text=False)- if not out:- return {"present": False, "exe": True}- gpus = []- for line in out.strip().splitlines()[:8]:- vals = [x.strip() for x in line.split(",")]- gpus.append({k: (None if v in ("[N/A]", "N/A", "[Not Supported]") else v) for k, v in zip(fields.split(","), vals)})- vram = None- try:- vram = round(max(float(g["memory.total"]) for g in gpus if g.get("memory.total")) / 1024, 1)- except ValueError:- pass- return {"present": bool(gpus), "vram_gb": vram, "gpus": gpus}---ps_probe("hw.monitors", r"""-try {- function U($a) { if ($a) { (($a | Where-Object { $_ -ne 0 } | ForEach-Object { [char]$_ }) -join '').Trim() } }- $ids = @(Get-CimInstance -Namespace root\wmi -ClassName WmiMonitorID -ErrorAction SilentlyContinue | ForEach-Object {- [ordered]@{ mfr = (U $_.ManufacturerName); product = (U $_.ProductCodeID); name = (U $_.UserFriendlyName); year = $_.YearOfManufacture; active = $_.Active } })- $size = @(Get-CimInstance -Namespace root\wmi -ClassName WmiMonitorBasicDisplayParams -ErrorAction SilentlyContinue | ForEach-Object {- if ($_.MaxHorizontalImageSize) { [math]::Round([math]::Sqrt([math]::Pow($_.MaxHorizontalImageSize,2)+[math]::Pow($_.MaxVerticalImageSize,2))/2.54,1) } })- $tech = @(Get-CimInstance -Namespace root\wmi -ClassName WmiMonitorConnectionParams -ErrorAction SilentlyContinue | ForEach-Object {- switch ([int64]$_.VideoOutputTechnology) { 0 {'VGA'} 4 {'DVI'} 5 {'HDMI'} 10 {'DP'} 11 {'DP-embedded'} 2147483648 {'Internal'} default { [string]$_.VideoOutputTechnology } } })- [ordered]@{ present = ($ids.Count -gt 0); count = $ids.Count; monitors = $ids; diag_in = $size; outputs = $tech }-} catch { [ordered]@{ present = $false; error = $_.Exception.Message } }-""", family="hardware", tier="T0", collect="extended", gate="hw.system", timeout_ms=6000,- doc="Connected monitors from EDID (WmiMonitorID): maker, model, year, size, connection; no serials.")--ps_probe("hw.ram", r"""-try {- $m = @(Get-CimInstance Win32_PhysicalMemory -ErrorAction SilentlyContinue)- $a = @(Get-CimInstance Win32_PhysicalMemoryArray -ErrorAction SilentlyContinue)- [ordered]@{ present = ($m.Count -gt 0); modules = $m.Count- total_gb = [math]::Round((($m | Measure-Object Capacity -Sum).Sum) / 1GB, 1)- slots = ($a | Measure-Object MemoryDevices -Sum).Sum- speed = @($m | ForEach-Object { $_.Speed } | Select-Object -Unique)- configured = @($m | ForEach-Object { $_.ConfiguredClockSpeed } | Select-Object -Unique)- rated_mhz = ($m | Measure-Object Speed -Minimum).Minimum; configured_mhz = ($m | Measure-Object ConfiguredClockSpeed -Minimum).Minimum- smbios_type = @($m | ForEach-Object { $_.SMBIOSMemoryType } | Select-Object -Unique)- mfr = @($m | ForEach-Object { ([string]$_.Manufacturer).Trim() } | Select-Object -Unique)- part = @($m | ForEach-Object { ([string]$_.PartNumber).Trim() } | Select-Object -Unique) }-} catch { [ordered]@{ present = $false; error = $_.Exception.Message } }-""", family="hardware", tier="T0", collect="extended", gate="hw.system", timeout_ms=6000,- doc="Installed RAM modules, slots, rated vs configured speed (Win32_PhysicalMemory).")--ps_probe("hw.disks", r"""-try {- $pd = @(Get-PhysicalDisk -ErrorAction SilentlyContinue | ForEach-Object {- $rc = $_ | Get-StorageReliabilityCounter -ErrorAction SilentlyContinue- [ordered]@{ name = $_.FriendlyName; media = [string]$_.MediaType; bus = [string]$_.BusType; size_gb = [math]::Round($_.Size/1GB)- health = [string]$_.HealthStatus; wear_pct = $rc.Wear; temp_c = $rc.Temperature; temp_max_c = $rc.TemperatureMax- power_on_h = $rc.PowerOnHours; read_err_uncorrected = $rc.ReadErrorsUncorrected; write_err_uncorrected = $rc.WriteErrorsUncorrected } })- $vol = @(Get-Volume -ErrorAction SilentlyContinue | Where-Object { $_.DriveLetter -and $_.DriveType -eq 'Fixed' -and $_.Size } | ForEach-Object {- [ordered]@{ letter = [string]$_.DriveLetter; size_gb = [math]::Round($_.Size/1GB,1); free_gb = [math]::Round($_.SizeRemaining/1GB,1)- free_pct = [math]::Round(100*$_.SizeRemaining/$_.Size,1) } })- [ordered]@{ present = ($pd.Count -gt 0); count = $pd.Count; disks = $pd; volumes = $vol }-} catch { [ordered]@{ present = $false; error = $_.Exception.Message } }-""", family="hardware", tier="T0", collect="deep", gate="hw.system", timeout_ms=15000,- doc="Physical disks with health, wear, temperature and error counters (Get-PhysicalDisk).")--ps_probe("hw.gpu_history", r"""-try {- $g = @(Get-PnpDevice -Class Display -ErrorAction SilentlyContinue | ForEach-Object {- $fi = (Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName DEVPKEY_Device_FirstInstallDate -ErrorAction SilentlyContinue).Data- $la = (Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName DEVPKEY_Device_LastArrivalDate -ErrorAction SilentlyContinue).Data- [ordered]@{ name = $_.FriendlyName; pci = (($_.InstanceId -split '\\')[1] -replace '&REV.*$',''); present = $_.Present- first = $(if ($fi) { ([datetime]$fi).ToString('s') }); last = $(if ($la) { ([datetime]$la).ToString('s') }) } })- [ordered]@{ present = ($g.Count -gt 0); ever = $g.Count; now = @($g | Where-Object { $_.present }).Count- swaps = @($g | Where-Object { -not $_.present -and $_.name -notmatch 'Basic|Remote|Virtual' }).Count; adapters = $g }-} catch { [ordered]@{ present = $false; error = $_.Exception.Message } }-""", family="hardware", tier="T0", collect="deep", gate="hw.gpu", timeout_ms=15000,- doc="Every display adapter ever installed with first-install/last-arrival dates (GPU swaps).")--ps_probe("hw.monitor_history", r"""-try {- $h = @(Get-PnpDevice -ErrorAction SilentlyContinue | Where-Object { $_.InstanceId -match '^DISPLAY\\' -and $_.InstanceId -notmatch 'DEFAULT_MONITOR' } | ForEach-Object {- $fi = (Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName DEVPKEY_Device_FirstInstallDate -ErrorAction SilentlyContinue).Data- $la = (Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName DEVPKEY_Device_LastArrivalDate -ErrorAction SilentlyContinue).Data- [pscustomobject]@{ pnp = ($_.InstanceId -split '\\')[1]; present = [bool]$_.Present; first = $fi; last = $la } } |- Group-Object pnp | ForEach-Object { $f = @($_.Group | Where-Object first | Sort-Object first); $l = @($_.Group | Where-Object last | Sort-Object last -Descending)- [ordered]@{ pnp = $_.Name; present = [bool]($_.Group | Where-Object present)- first = $(if ($f) { ([datetime]$f[0].first).ToString('s') }); last = $(if ($l) { ([datetime]$l[0].last).ToString('s') }) } })- [ordered]@{ present = ($h.Count -gt 0); distinct_monitors_ever = $h.Count; changes = @($h | Where-Object { -not $_.present }).Count; monitors = $h }-} catch { [ordered]@{ present = $false; error = $_.Exception.Message } }-""", family="hardware", tier="T0", collect="deep", gate="hw.system", timeout_ms=15000,- doc="Every monitor model (PnP id) ever connected with first/last dates.")--ps_probe("hw.peripherals", r"""-try {- $cls = 'Keyboard','Mouse','HIDClass','Camera','Image','Biometric','XnaComposite','Printer','MEDIA','SmartCardReader'- $pp = @(Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | Where-Object { $cls -contains $_.Class })- $by = @{}; foreach ($d in $pp) { $by[[string]$d.Class] = 1 + [int]$by[[string]$d.Class] }- $vids = @{}; foreach ($d in $pp) { if ($d.InstanceId -match 'VID_([0-9A-F]{4})') { $vids[$matches[1]] = 1 + [int]$vids[$matches[1]] } }- $pads = @($pp | Where-Object { $_.Class -eq 'XnaComposite' -or $_.FriendlyName -match 'game ?controller|gamepad|xbox|dualsense|dualshock' }).Count- $cams = @($pp | Where-Object { $_.Class -in 'Camera','Image' }).Count- [ordered]@{ present = ($pp.Count -gt 0); by_class = $by; hid_vids = $vids; game_controllers = $pads; cameras = $cams }-} catch { [ordered]@{ present = $false; error = $_.Exception.Message } }-""", family="hardware", tier="T1", collect="deep", gate="hw.system", timeout_ms=15000,- doc="Present peripherals by PnP class, USB vendor ids, controller and camera counts.")---def _xml_local(path):- import xml.etree.ElementTree as ET- try:- return ET.parse(path).getroot()- except Exception:- return None---def _ln(el):- return el.tag.rsplit("}", 1)[-1]---@probe(id="hw.battery_report", level="L2", family="hardware", tier="T1", collect="deep", gate="hw.battery", timeout_ms=15000)-def hw_battery_report(h, facts):- """powercfg /batteryreport (XML into scratch): design vs full capacity, cycle count, recent AC/DC usage."""- out = os.path.join(h.scratch(), "battery.xml")- h.run(["powercfg", "/batteryreport", "/xml", "/output", out], timeout_ms=15000, text=False)- root = _xml_local(out)- if root is None:- return {"present": False}- bat = next((e for e in root.iter() if _ln(e) == "Battery"), None)- if bat is None:- return {"present": False}- kv = {_ln(c): (c.text or "").strip() for c in bat}- design, full = int(kv.get("DesignCapacity") or 0), int(kv.get("FullChargeCapacity") or 0)- usage = [e for e in root.iter() if _ln(e) == "UsageEntry"]- ac = sum(1 for e in usage if e.get("Ac") == "1")- try:- os.remove(out)- except OSError:- pass- return {"present": True, "design_mwh": design, "full_mwh": full, "health_pct": round(100 * full / design, 1) if design else None,- "cycles": kv.get("CycleCount"), "chemistry": kv.get("Chemistry"), "recent_usage_entries": len(usage),- "recent_ac": ac, "recent_dc": len(usage) - ac}---@probe(id="hw.sleep_study", level="L2", family="hardware", tier="T1", collect="deep", gate="hw.battery", timeout_ms=20000)-def hw_sleep_study(h, facts):- """powercfg /sleepstudy (XML into scratch): Modern Standby sessions, low-power share, drain."""- out = os.path.join(h.scratch(), "sleepstudy.xml")- h.run(["powercfg", "/sleepstudy", "/xml", "/output", out], timeout_ms=20000, text=False)- root = _xml_local(out)- if root is None:- return {"present": False}- inst = [e for e in root.iter() if _ln(e) == "ScenarioInstance"]- types = collections.Counter(e.get("Type") or "?" for e in inst)- lp = []- for e in inst:- d, l = int(e.get("Duration") or 0), int(e.get("LowPowerStateTime") or 0)- if d:- lp.append(100 * l / d)- try:- os.remove(out)- except OSError:- pass- return {"present": bool(inst), "sessions": len(inst), "types": dict(types),- "lowpower_pct_median": round(sorted(lp)[len(lp) // 2], 1) if lp else None,- "lowpower_pct_min": round(min(lp), 1) if lp else None}---# ================================================================= HEALTH--@probe(id="health.dumps", level="L1", family="health", tier="T1", collect="core")-def health_dumps(h, facts):- """Crash dump config (CrashControl) and dump files: Minidump count/newest, MEMORY.DMP, LiveKernelReports."""- P = _paths()- cc = _reg_values(r"HKLM\SYSTEM\CurrentControlSet\Control\CrashControl", 100)- mini, newest, mini30 = 0, None, 0- try:- with os.scandir(os.path.join(P["WIN"], "Minidump")) as it:- for e in it:- if mini >= 1000:- break- if e.is_file():- mini += 1- m = e.stat().st_mtime- newest = m if newest is None or m > newest else newest- mini30 += time.time() - m <= 30 * 86400- except OSError:- pass- lkr = {}- lroot = os.path.join(P["WIN"], "LiveKernelReports")- for d in h.list_dir(lroot, 50):- p = os.path.join(lroot, d)- if os.path.isdir(p):- n = sum(1 for f in h.list_dir(p, 500) if f.lower().endswith(".dmp"))- if n:- lkr[d] = n- elif d.lower().endswith(".dmp"):- lkr["root"] = lkr.get("root", 0) + 1- md = h.meta(os.path.join(P["WIN"], "MEMORY.DMP"))- if not cc and not mini and not lkr:- return None- return {"present": True, "crash_dump_enabled": cc.get("CrashDumpEnabled"), "auto_reboot": cc.get("AutoReboot"),- "minidumps": mini, "count_30d": mini30, "minidump_newest": _iso(newest), "memory_dmp_bytes": md.get("bytes"),- "live_kernel_reports": lkr}---_WER_NOISE = re.compile(r"(?i)^(svchost\.exe|TrustedInstaller\.exe|TiWorker\.exe|MoUsoCoreWorker\.exe|WinStore\.App\.exe|"- r"Microsoft\.WindowsStore.*|MicrosoftEdgeUpdate.*|MicrosoftEdge_X64_.*|setup\.exe|MsiExec\.exe|"- r"wermgr\.exe|StoreDesktopExtension.*|backgroundTaskHost\.exe|RuntimeBroker\.exe|SearchHost\.exe|"- r"MpSigStub\.exe|MsMpEng\.exe|WindowsPackageManagerServer\.exe)$")---@probe(id="health.wer", level="L2", family="health", tier="T1", collect="extended", gate="health.dumps")-def health_wer(h, facts):- """WER report dirs: crashes/hangs per app (Report.wer AppName), kernel reports; svchost/Store noise split out."""- roots = [os.path.join(_paths()["PD"], "Microsoft", "Windows", "WER", r) for r in ("ReportArchive", "ReportQueue")]- types = collections.Counter()- apps = collections.Counter()- last = {}- kernel = collections.Counter()- noise = total = 0- oldest = newest = None- for rt in roots:- for n in h.list_dir(rt, 1000):- p = os.path.join(rt, n)- total += 1- typ = n.split("_", 1)[0]- types[typ] += 1- m = _mtime(p)- if m:- oldest = m if oldest is None or m < oldest else oldest- newest = m if newest is None or m > newest else newest- app, evt = None, None- try:- with open(os.path.join(p, "Report.wer"), "rb") as f:- txt = f.read(200_000).decode("utf-16", "replace")- ma = re.search(r"^AppPath=([^\r\n]+)", txt, re.M) or re.search(r"^AppName=([^\r\n]+)", txt, re.M)- me = re.search(r"^EventType=([^\r\n]+)", txt, re.M)- app, evt = (_base(ma.group(1).strip()) if ma else None), (me.group(1).strip() if me else None)- except OSError:- pass- if re.search(r"Kernel|BlueScreen", typ, re.I) or (evt and re.search(r"LiveKernel|BlueScreen", evt, re.I)):- kernel[evt or typ] += 1- continue- if re.search(r"AppCrash|AppHang|BEX|Critical", typ, re.I):- m2 = re.match(r"^[^_]+_([^_]+?\.exe)_", n, re.I)- if m2:- app = m2.group(1)- app = app or "?"- if _WER_NOISE.match(app):- noise += 1- continue- apps[app] += 1- last[app] = max(last.get(app) or 0, m or 0)- if not total:- return {"present": False}- types = collections.Counter({k: v for k, v in types.items() if not re.fullmatch(r"[0-9a-fA-F-]{36}", k)})- return {"present": True, "reports": total, "by_type": dict(types.most_common(8)), "system_noise_crashes": noise,- "max_repeat": apps.most_common(1)[0][1] if apps else 0,- "crashes_by_app": [[a, c, _iso(last.get(a))] for a, c in apps.most_common(12)], "kernel_reports": dict(kernel),- "oldest": _iso(oldest), "newest": _iso(newest)}---@probe(id="health.whea_gpu", level="L2", family="health", tier="T1", collect="extended", gate="hw.system", timeout_ms=20000)-def health_whea_gpu(h, facts):- """Hardware error events: WHEA, nvlddmkm, display TDR 4101, bugcheck 1001 codes, storage warnings (wevtutil)."""- provs = ("Microsoft-Windows-WHEA-Logger", "nvlddmkm", "Display", "Microsoft-Windows-WER-SystemErrorReporting",- "disk", "Ntfs", "stornvme")- xp = "*[System[Provider[" + " or ".join(f"@Name='{p}'" for p in provs) + "]]]"- evs = _wevt(h, "System", xp, 3000, newest_first=True)- if evs is None:- return {"present": False, "error": "wevtutil failed"}- grp = {k: {"count": 0, "by_id": collections.Counter(), "newest": None} for k in ("whea", "nvlddmkm", "tdr_4101", "storage_warn_err")}- bug = []- now = dt.datetime.now().astimezone()- c30 = 0- for ev in evs:- try:- prov, eid, t, data = _evt_fields(ev)- lvl = int(ev.find(_EVT_NS + "System").find(_EVT_NS + "Level").text or 4)- except (AttributeError, ValueError, TypeError):- continue- key = None- if prov == "Microsoft-Windows-WHEA-Logger":- key = "whea"- elif prov == "nvlddmkm":- key = "nvlddmkm"- elif prov == "Display" and eid == 4101:- key = "tdr_4101"- elif prov in ("disk", "Ntfs", "stornvme") and 1 <= lvl <= 3:- key = "storage_warn_err"- elif prov == "Microsoft-Windows-WER-SystemErrorReporting" and eid == 1001:- m = re.search(r"0x[0-9a-fA-F]+", " ".join(v or "" for v in data.values()))- bug.append({"t": _iso(t), "code": m.group(0) if m else None})- c30 += bool(t and (now - t).days < 30)- continue- if not key:- continue- g = grp[key]- g["count"] += 1- g["by_id"][str(eid)] += 1- if t and (g["newest"] is None or _iso(t) > g["newest"]):- g["newest"] = _iso(t)- if key != "storage_warn_err" and t and (now - t).days < 30:- c30 += 1- for g in grp.values():- g["by_id"] = dict(g["by_id"])- return {"present": True, "count_30d": c30, **grp, "bugchecks": bug[:20]}---ps_probe("health.reliability", r"""-try {- $r = @(Get-CimInstance Win32_ReliabilityRecords -ErrorAction SilentlyContinue)- $m = @(Get-CimInstance Win32_ReliabilityStabilityMetrics -ErrorAction SilentlyContinue | Sort-Object TimeGenerated)- $s = @($r | Sort-Object TimeGenerated)- function T($grp) { $o = [ordered]@{}; foreach ($x in @($grp | Sort-Object Count -Descending | Select-Object -First 8)) { $o[[string]$x.Name] = $x.Count }; $o }- [ordered]@{ present = ($r.Count -gt 0); records = $r.Count- oldest = $(if ($s) { $s[0].TimeGenerated.ToString('s') }); newest = $(if ($s) { $s[-1].TimeGenerated.ToString('s') })- by_source = (T ($r | Group-Object SourceName)); top_products = (T ($r | Where-Object ProductName | Group-Object ProductName))- stability_latest = $(if ($m) { [math]::Round($m[-1].SystemStabilityIndex, 2) })- stability_min = $(if ($m) { [math]::Round(($m | Measure-Object SystemStabilityIndex -Minimum).Minimum, 2) }) }-} catch { [ordered]@{ present = $false; error = $_.Exception.Message } }-""", family="health", tier="T1", collect="deep", gate="hw.system", timeout_ms=20000,- doc="Reliability Monitor records by source/product and the stability index (latest, min).")diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/usage_gaming_games.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/usage_gaming_games.pynew file mode 100644index 00000000000..cd52f5ac232--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/usage_gaming_games.py@@ -0,0 +1,849 @@+"""Gaming and media probes (Windows).++Registration only at import time. Shared helpers live in usage_gaming.+"""+from __future__ import annotations++import collections+import datetime as dt+import json+import os+import re+import struct+import time++from ..registry import probe+from .usage_gaming import (_base, _cached, _ex, _ft, _iso, _mtime, _noise, _paths, _read,+ _reg_keys, _reg_values, _unmatch)++# ================================================================= GAMING++def _steam(h):+ """Shared Steam state: path, libraries, manifests, userdata ids, localconfig apps, appinfo buffer."""+ def load():+ sp = h.reg(r"HKCU\Software\Valve\Steam", "SteamPath")+ if not sp:+ cand = os.path.join(_paths()["PF86"], "Steam")+ sp = cand if _ex(cand) else None+ if not sp:+ return None+ sp = os.path.normpath(sp)+ libs = []+ txt = _read(os.path.join(sp, "steamapps", "libraryfolders.vdf"))+ if txt:+ for _k, v in (_ci(_vdf(txt), "libraryfolders") or {}).items():+ if isinstance(v, dict) and v.get("path"):+ libs.append(os.path.normpath(v["path"]))+ libs = libs or [sp]+ installed = []+ for lib in libs[:20]:+ sa = os.path.join(lib, "steamapps")+ for n in h.list_dir(sa, 2000):+ if n.startswith("appmanifest_") and n.endswith(".acf"):+ st = _ci(_vdf(_read(os.path.join(sa, n)) or ""), "AppState") or {}+ installed.append({"appid": int(st.get("appid", 0) or 0), "name": st.get("name"),+ "size_gb": round(int(st.get("SizeOnDisk", 0) or 0) / 1e9, 1), "drive": lib[:2].upper(),+ "last_played": int(st.get("LastPlayed", 0) or 0)})+ ud = os.path.join(sp, "userdata")+ uids = [u for u in h.list_dir(ud, 50) if u.isdigit()]+ users = {}+ for uid in uids:+ lc = os.path.join(ud, uid, "config", "localconfig.vdf")+ apps = {}+ t = _read(lc)+ if t:+ d = _vdf(t)+ node = _ci(d, "UserLocalConfigStore", "Software", "Valve", "Steam", "apps") or {}+ for aid, v in node.items():+ if isinstance(v, dict) and aid.isdigit() and ("Playtime" in v or "LastPlayed" in v):+ apps[int(aid)] = {"min": int(v.get("Playtime", 0) or 0), "min2wk": int(v.get("Playtime2wks", 0) or 0),+ "last": int(v.get("LastPlayed", 0) or 0)}+ users[uid] = apps+ return {"path": sp, "libs": libs, "installed": installed, "uids": uids, "users": users,+ "appinfo_path": os.path.join(sp, "appcache", "appinfo.vdf")}+ return _cached(("steam", h.l0.get("run_id")), load)+++_TOK = re.compile(r'"((?:[^"\\]|\\.)*)"|(\{)|(\})', re.S)+++def _vdf(text):+ stack, key = [{}], None+ for m in _TOK.finditer(text):+ s, ob, cb = m.groups()+ if ob:+ d = {}+ stack[-1][key] = d+ stack.append(d)+ key = None+ elif cb:+ if len(stack) > 1:+ stack.pop()+ else:+ s = s.replace("\\\\", "\\")+ if key is None:+ key = s+ else:+ stack[-1][key] = s+ key = None+ return stack[0]+++def _ci(d, *keys):+ for k in keys:+ if not isinstance(d, dict):+ return None+ lk = {kk.lower(): kk for kk in d}+ if k.lower() not in lk:+ return None+ d = d[lk[k.lower()]]+ return d+++_GENRES = {"1": "Action", "2": "Strategy", "3": "RPG", "4": "Casual", "9": "Racing", "18": "Sports", "23": "Indie",+ "25": "Adventure", "28": "Simulation", "29": "Massively Multiplayer", "37": "Free to Play", "70": "Early Access",+ "51": "Animation & Modeling", "52": "Audio Production", "53": "Design & Illustration", "54": "Education",+ "55": "Photo Editing", "56": "Software Training", "57": "Utilities", "58": "Video Production",+ "59": "Web Publishing", "60": "Game Development"}+++def _cstr(buf, i):+ j = buf.index(b"\x00", i)+ return buf[i:j].decode("utf-8", "replace"), j + 1+++def _bkv(buf, i, strtab, depth=0):+ d = {}+ while True:+ t = buf[i]+ i += 1+ if t in (8, 11):+ return d, i+ if strtab is not None:+ (idx,) = struct.unpack_from("<I", buf, i)+ i += 4+ key = strtab[idx] if idx < len(strtab) else str(idx)+ else:+ key, i = _cstr(buf, i)+ if t == 0:+ if depth > 30:+ raise ValueError("bkv too deep")+ v, i = _bkv(buf, i, strtab, depth + 1)+ elif t == 1:+ v, i = _cstr(buf, i)+ elif t in (2, 4, 6):+ (v,) = struct.unpack_from("<i", buf, i)+ i += 4+ elif t == 3:+ (v,) = struct.unpack_from("<f", buf, i)+ i += 4+ elif t == 7:+ (v,) = struct.unpack_from("<Q", buf, i)+ i += 8+ elif t == 10:+ (v,) = struct.unpack_from("<q", buf, i)+ i += 8+ elif t == 5:+ j = i+ while buf[j:j + 2] != b"\x00\x00":+ j += 2+ v = buf[i:j].decode("utf-16-le", "replace")+ i = j + 2+ else:+ raise ValueError(f"bkv type {t}")+ d[key] = v+++def _appinfo(h, want):+ """{appid: {name, type, genres}} for wanted appids, reading appinfo.vdf once per run."""+ st = _steam(h) or {}+ path = st.get("appinfo_path")++ def load():+ with open(path, "rb") as f:+ return f.read(200_000_000)+ buf = _cached(("appinfo_buf", h.l0.get("run_id")), load) if path and _ex(path) else None+ if not isinstance(buf, (bytes, bytearray)):+ return {}+ magic, _u = struct.unpack_from("<II", buf, 0)+ ver = magic & 0xFF+ off, strtab, end = 8, None, len(buf)+ if ver >= 0x29:+ (st_off,) = struct.unpack_from("<q", buf, 8)+ off, end = 16, st_off+ (n,) = struct.unpack_from("<I", buf, st_off)+ strtab, j = [], st_off + 4+ for _ in range(min(n, 500000)):+ s, j = _cstr(buf, j)+ strtab.append(s)+ out = {}+ while off < end - 8:+ appid, size = struct.unpack_from("<II", buf, off)+ if appid == 0:+ break+ body = off + 8+ if appid in want:+ kv_start = body + 4 + 4 + 8 + 20 + 4 + (20 if ver >= 0x28 else 0)+ try:+ kv, _ = _bkv(buf, kv_start, strtab)+ common = _ci(kv, "appinfo", "common") or {}+ g = common.get("genres") or {}+ out[appid] = {"name": common.get("name"), "type": common.get("type"),+ "genres": [_GENRES.get(str(x), str(x)) for x in (g.values() if isinstance(g, dict) else [])]}+ except Exception:+ out[appid] = {"name": None, "type": None, "genres": []}+ off = body + size+ return out+++@probe(id="steam.present", level="L1", family="gaming", tier="T0", collect="core")+def steam_present(h, facts):+ """Steam client installed (HKCU SteamPath or Program Files); gates the Steam subtree."""+ sp = h.reg(r"HKCU\Software\Valve\Steam", "SteamPath")+ if sp and _ex(sp):+ return {"present": True, "via": "registry"}+ if _ex(os.path.join(_paths()["PF86"], "Steam")):+ return {"present": True, "via": "path"}+ return None+++def _lib_volume(p):+ """Volume holding a Steam library: drive letter ('D:') for a Windows path, else the POSIX mount point."""+ if re.match(r"^[A-Za-z]:", p or ""):+ return p[:2].upper()+ q = os.path.realpath(p) if p else "/"+ for _ in range(64):+ if os.path.ismount(q) or os.path.dirname(q) == q:+ return q+ q = os.path.dirname(q)+ return q+++@probe(id="steam.installed", level="L2", family="gaming", tier="T1", collect="core", gate="steam.present")+def steam_installed(h, facts):+ """Installed Steam titles and GB from libraryfolders.vdf + appmanifest_*.acf."""+ st = _steam(h)+ if not st or "error" in st:+ return {"present": False, "error": (st or {}).get("error")}+ inst = sorted(st["installed"], key=lambda x: -x["size_gb"])+ games = [x for x in inst if not re.search(r"Redistributable|Dedicated Server|SDK|Proton|Steamworks", x["name"] or "", re.I)]+ return {"present": True, "libraries": len(st["libs"]), "drives": sorted({_lib_volume(p) for p in st["libs"]}),+ "apps": len(inst), "games": len(games), "total_gb": round(sum(x["size_gb"] for x in inst), 1),+ "top": [[x["name"], x["size_gb"], _iso(x["last_played"])] for x in games[:12]]}+++@probe(id="steam.playtime", level="L2", family="gaming", tier="T1", collect="core", gate="steam.present")+def steam_playtime(h, facts):+ """Account-wide playtime per Steam userdata account from localconfig.vdf: hours, 2-week hours, top games."""+ st = _steam(h)+ if not st or not st.get("users"):+ return {"present": False}+ want = set()+ for apps in st["users"].values():+ want |= set(sorted(apps, key=lambda a: -apps[a]["min"])[:15])+ info = _appinfo(h, want) if want else {}+ names = {x["appid"]: x["name"] for x in st["installed"]}+ accounts = []+ for uid, apps in st["users"].items():+ rows = []+ for aid, v in apps.items():+ t = (info.get(aid) or {}).get("type")+ if t and t.lower() not in ("game", "demo", "mod", "beta"):+ continue+ rows.append((aid, v))+ rows.sort(key=lambda kv: -kv[1]["min"])+ lasts = [v["last"] for _, v in rows if v["last"]]+ accounts.append({+ "account": f"acct{len(accounts) + 1}", "games_with_record": len(rows),+ "games_played": sum(1 for _, v in rows if v["min"] > 0),+ "total_h": round(sum(v["min"] for _, v in rows) / 60, 1),+ "h_last_2wk": round(sum(v["min2wk"] for _, v in rows) / 60, 1),+ "played_7d": sum(1 for x in lasts if time.time() - x <= 7 * 86400),+ "played_30d": sum(1 for x in lasts if time.time() - x <= 30 * 86400),+ "last_played": _iso(max(lasts)) if lasts else None,+ "top": [[(info.get(a) or {}).get("name") or names.get(a) or f"app{a}", round(v["min"] / 60, 1), _iso(v["last"])]+ for a, v in rows[:10] if v["min"]]})+ accounts.sort(key=lambda a: -a["total_h"])+ return {"present": True, "accounts": len(accounts), "total_hours": round(sum(a["total_h"] for a in accounts), 1),+ "played_last_30d": max((a["played_30d"] for a in accounts), default=0), "per_account": accounts}+++@probe(id="steam.appinfo_genres", level="L2", family="gaming", tier="T0", collect="extended", gate="steam.present")+def steam_appinfo_genres(h, facts):+ """Genre hours per account from binary appinfo.vdf (static genre-id map)."""+ st = _steam(h)+ if not st or not st.get("users"):+ return {"present": False}+ want = set()+ for apps in st["users"].values():+ want |= {a for a, v in apps.items() if v["min"] > 0}+ info = _appinfo(h, want)+ out = []+ for i, apps in enumerate(st["users"].values()):+ gh = collections.Counter()+ for a, v in apps.items():+ for g in (info.get(a) or {}).get("genres", []):+ if g not in ("Free to Play", "Early Access"):+ gh[g] += v["min"] / 60+ out.append({"account": f"acct{i + 1}", "genre_h": [[g, round(x, 1)] for g, x in gh.most_common(8)]})+ return {"present": True, "resolved": len(info), "unresolved": len(want - set(info)), "per_account": out}+++@probe(id="steam.local_sessions", level="L2", family="gaming", tier="T1", collect="core", gate="steam.present")+def steam_local_sessions(h, facts):+ """Per-machine play sessions from gameprocess_log: hours, last-30-day hours, start hour and weekday histograms."""+ st = _steam(h)+ if not st:+ return {"present": False}+ rx_add = re.compile(r"^\[(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)\] AppID (\d+) adding PID")+ rx_end = re.compile(r"^\[(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)\] Remove (\d+) from running list")+ active, sessions, first = {}, [], None+ for fn in ("gameprocess_log.previous.txt", "gameprocess_log.txt"):+ txt = _read(os.path.join(st["path"], "logs", fn), 20_000_000)+ if not txt:+ continue+ last_ts = None+ for line in txt.splitlines():+ if not line.startswith("[20"):+ continue+ if first is None:+ first = line[1:11]+ if "] Client version:" in line and active and last_ts:+ sessions += [(a, s0, last_ts) for a, s0 in active.items()]+ active = {}+ try:+ last_ts = dt.datetime.strptime(line[1:20], "%Y-%m-%d %H:%M:%S")+ except ValueError:+ continue+ m = rx_add.match(line)+ if m:+ active.setdefault(int(m.group(2)), last_ts)+ continue+ m = rx_end.match(line)+ if m and int(m.group(2)) in active:+ sessions.append((int(m.group(2)), active.pop(int(m.group(2))), last_ts))+ dropped = sum(1 for _, s0, e0 in sessions if (e0 - s0).total_seconds() > 16 * 3600)+ sessions = [x for x in sessions if (x[2] - x[1]).total_seconds() <= 16 * 3600]+ if not sessions:+ return {"present": False, "log_starts": first}+ per = {}+ hh, dh = [0] * 24, [0] * 7+ now = dt.datetime.now()+ for a, s0, e0 in sessions:+ p = per.setdefault(a, [0, 0.0, ""])+ p[0] += 1+ p[1] += max(0, (e0 - s0).total_seconds()) / 3600+ p[2] = max(p[2], e0.strftime("%Y-%m-%d"))+ hh[s0.hour] += 1+ dh[s0.weekday()] += 1+ names = {x["appid"]: x["name"] for x in st["installed"]}+ top_ids = sorted(per, key=lambda a: -per[a][1])[:10]+ info = _appinfo(h, set(top_ids) - set(names))+ return {"present": True, "log_starts": first, "sessions": len(sessions), "dropped_over_16h": dropped, "apps": len(per),+ "total_hours": round(sum(p[1] for p in per.values()), 1),+ "hours_30d": round(sum(max(0, (e - s).total_seconds()) / 3600 for _, s, e in sessions if (now - e).days <= 30), 1),+ "start_hours": hh, "start_dow_hist_mon0": dh,+ "top": [[names.get(a) or (info.get(a) or {}).get("name") or f"app{a}", per[a][0], round(per[a][1], 1), per[a][2]]+ for a in top_ids]}+++@probe(id="steam.non_steam_shortcuts", level="L2", family="gaming", tier="T0", collect="core", gate="steam.present")+def steam_non_steam_shortcuts(h, facts):+ """Count of non-Steam game shortcuts (shortcuts.vdf entries) per account; count only."""+ st = _steam(h)+ if not st:+ return {"present": False}+ total, files = 0, 0+ for uid in st["uids"]:+ p = os.path.join(st["path"], "userdata", uid, "config", "shortcuts.vdf")+ try:+ with open(p, "rb") as f:+ data = f.read(5_000_000)+ except OSError:+ continue+ files += 1+ total += len(re.findall(rb"\x01(?i:appname)\x00", data))+ return {"present": files > 0, "files": files, "shortcuts": total}+++@probe(id="steam.screenshots", level="L2", family="gaming", tier="T0", collect="core", gate="steam.present")+def steam_screenshots(h, facts):+ """Steam screenshot counts per account (userdata\\*\\760\\remote, depth <= 3)."""+ st = _steam(h)+ if not st:+ return {"present": False}+ counts = []+ for uid in st["uids"]:+ rem = os.path.join(st["path"], "userdata", uid, "760", "remote")+ n, seen = 0, 0+ for root, dirs, files in os.walk(rem):+ seen += 1+ if seen > 2000 or root.count(os.sep) - rem.count(os.sep) >= 3:+ dirs[:] = []+ n += sum(1 for f in files if f.lower().endswith((".jpg", ".png")))+ counts.append(n)+ return {"present": True, "accounts": len(counts), "screenshots": sum(counts), "per_account": counts}+++@probe(id="steam.login_users", level="L2", family="gaming", tier="T2", collect="extended", gate="steam.present")+def steam_login_users(h, facts):+ """loginusers.vdf: account count, last-login dates, autologin; persona names (T2). Login AccountName never emitted."""+ st = _steam(h)+ if not st:+ return {"present": False}+ txt = _read(os.path.join(st["path"], "config", "loginusers.vdf"))+ if not txt:+ return {"present": False}+ users = []+ for _sid, v in (_ci(_vdf(txt), "users") or {}).items():+ if isinstance(v, dict):+ users.append({"persona_name": v.get("PersonaName"), "most_recent": v.get("MostRecent") == "1",+ "auto_login": v.get("AutoLogin") == "1", "last_login": _iso(int(v.get("Timestamp", 0) or 0))})+ return {"present": bool(users), "count": len(users), "users": users}+++@probe(id="steam.remote_clients", level="L2", family="gaming", tier="T2", collect="deep", gate="steam.present")+def steam_remote_clients(h, facts):+ """Steam Remote Play peers: peer count and hostnames of the user's other machines (T2)."""+ st = _steam(h)+ if not st:+ return {"present": False}+ txt = _read(os.path.join(st["path"], "config", "remoteclients.vdf"))+ if not txt:+ return {"present": False}+ hn = re.findall(r'"hostname"\s+"([^"]*)"', txt)+ return {"present": bool(hn), "count": len(hn), "hostnames": hn[:10]}+++@probe(id="epic.present", level="L1", family="gaming", tier="T0", collect="core")+def epic_present(h, facts):+ """Epic Games Launcher data dir present; gates Epic subtree."""+ return {"present": True} if _ex(os.path.join(_paths()["PD"], "Epic", "EpicGamesLauncher")) else None+++@probe(id="epic.installs", level="L2", family="gaming", tier="T0", collect="core", gate="epic.present")+def epic_installs(h, facts):+ """Epic installs: LauncherInstalled.dat, manifests (incl. Pending), game dirs with .egstore."""+ P = _paths()+ items = []+ t = _read(os.path.join(P["PD"], "Epic", "UnrealEngineLauncher", "LauncherInstalled.dat"))+ if t:+ try:+ items = [e.get("AppName") for e in json.loads(t).get("InstallationList", [])]+ except Exception:+ pass+ man = os.path.join(P["PD"], "Epic", "EpicGamesLauncher", "Data", "Manifests")+ manifests = []+ for sub in ("", "Pending"):+ d = os.path.join(man, sub)+ for n in h.list_dir(d, 500):+ if n.endswith(".item"):+ try:+ j = json.loads(_read(os.path.join(d, n)) or "{}")+ manifests.append([j.get("DisplayName"), round((j.get("InstallSize") or 0) / 1e9, 1), bool(sub)])+ except Exception:+ pass+ dirs = []+ for base in (os.path.join(P["PF"], "Epic Games"), os.path.join(P["PF86"], "Epic Games")):+ for n in h.list_dir(base, 200):+ if n not in ("Launcher", "DirectXRedist", "Epic Online Services") and _ex(os.path.join(base, n, ".egstore")):+ dirs.append(n)+ return {"present": True, "launcher": _unmatch(h, r"Epic Games Launcher")[:1], "installed_list": items[:30],+ "manifests": manifests[:30], "pending": sum(1 for m in manifests if m[2]), "egstore_dirs": dirs[:30]}+++@probe(id="xbox.present", level="L1", family="gaming", tier="T0", collect="core")+def xbox_present(h, facts):+ """Xbox app package dir present (inbox app, weak alone)."""+ pk = os.path.join(_paths()["LAD"], "Packages")+ app = _ex(os.path.join(pk, "Microsoft.GamingApp_8wekyb3d8bbwe"))+ bar = _ex(os.path.join(pk, "Microsoft.XboxGamingOverlay_8wekyb3d8bbwe"))+ return {"present": True, "xbox_app": app, "game_bar": bar} if (app or bar) else None+++@probe(id="xbox.gamepass", level="L2", family="gaming", tier="T0", collect="core", gate="xbox.present")+def xbox_gamepass(h, facts):+ """Game Pass / Gaming Services installs: package repository, XboxGames dirs, ModifiableWindowsApps."""+ repo = _reg_keys(h, r"HKLM\SOFTWARE\Microsoft\GamingServices\PackageRepository\Root", 500)+ dirs = []+ for d in (r"C:\XboxGames", r"D:\XboxGames", r"E:\XboxGames"):+ dirs += [n for n in h.list_dir(d, 200) if n != "GameSave"]+ mwa = h.count_dir(os.path.join(_paths()["PF"], "ModifiableWindowsApps"), 500)+ return {"present": True, "gaming_services_repo": len(repo), "xboxgames_dirs": len(dirs),+ "modifiable_windows_apps": max(mwa, 0),+ "game_mode_auto": h.reg(r"HKCU\Software\Microsoft\GameBar", "AutoGameModeEnabled"),+ "gamedvr_capture": h.reg(r"HKCU\Software\Microsoft\Windows\CurrentVersion\GameDVR", "AppCaptureEnabled")}+++@probe(id="gcs.present", level="L1", family="gaming", tier="T0", collect="core")+def gcs_present(h, facts):+ """GameConfigStore Children key present (Game Bar game classification); gates gcs.game_history."""+ n = len(_reg_keys(h, r"HKCU\System\GameConfigStore\Children", 5000))+ return {"present": True, "children": n} if n else None+++@probe(id="gcs.game_history", level="L2", family="gaming", tier="T2", collect="core", gate="gcs.present")+def gcs_game_history(h, facts):+ """Game exes ever run (incl. since uninstalled) from GameConfigStore; game names and launcher, paths stripped."""+ base = r"HKCU\System\GameConfigStore\Children"+ by = {}+ for sk in _reg_keys(h, base, 2000):+ v = _reg_values(base + "\\" + sk, 100)+ exe = v.get("MatchedExeFullPath")+ if not exe or _noise(exe):+ continue+ low = exe.lower()+ launcher = ("steam" if "\\steamapps\\" in low else "epic" if "\\epic games\\" in low else+ "riot" if "riot games" in low else "xbox" if ("xboxgames" in low or "windowsapps" in low) else+ "ea" if ("\\ea games\\" in low or "electronic arts" in low) else "ubisoft" if "ubisoft" in low else+ "rockstar" if "rockstar" in low else "gog" if "gog" in low else "other")+ m = re.search(r"\\(?:steamapps\\common|Epic Games|Riot Games|Rockstar Games|Games|XboxGames)\\([^\\]+)", exe, re.I)+ game = m.group(1) if m else (exe.split("\\")[1] if re.match(r"^[A-Z]:\\[^\\]+\\", exe) else _base(exe))+ la = v.get("LastAccessed")+ t = _ft(la) if isinstance(la, int) else None+ ts = t.timestamp() if t else None+ k = game.lower()+ cur = by.get(k)+ present = _ex(exe)+ if cur is None or (ts or 0) > (cur["ts"] or 0):+ by[k] = {"game": game, "launcher": launcher, "ts": ts, "present": present or (cur or {}).get("present", False)}+ elif present:+ cur["present"] = True+ if not by:+ return {"present": False}+ games = sorted(by.values(), key=lambda g: -(g["ts"] or 0))+ return {"present": True, "distinct_games": len(games),+ "uninstalled_since": sum(1 for g in games if not g["present"]),+ "last_30d": sum(1 for g in games if g["ts"] and time.time() - g["ts"] <= 30 * 86400),+ "by_launcher": dict(collections.Counter(g["launcher"] for g in games)),+ "games": [[g["game"], g["launcher"], _iso(g["ts"]), g["present"]] for g in games[:30]]}+++@probe(id="launchers.other", level="L1", family="gaming", tier="T0", collect="core")+def launchers_other(h, facts):+ """Presence of Battle.net, Riot, EA, Ubisoft, GOG, Rockstar, Amazon, Playnite, Heroic launchers."""+ P = _paths()+ cands = {+ "battlenet": [os.path.join(P["PF86"], "Battle.net"), os.path.join(P["PD"], "Battle.net")],+ "riot": [r"C:\Riot Games", os.path.join(P["LAD"], "Riot Games")],+ "ea": [os.path.join(P["PD"], "EA Desktop"), os.path.join(P["RAD"], "Electronic Arts"), os.path.join(P["LAD"], "Electronic Arts")],+ "ubisoft": [os.path.join(P["PF86"], "Ubisoft"), os.path.join(P["LAD"], "Ubisoft Game Launcher")],+ "gog": [os.path.join(P["PF86"], "GOG Galaxy"), os.path.join(P["PD"], "GOG.com")],+ "rockstar": [os.path.join(P["PF"], "Rockstar Games"), os.path.join(P["LAD"], "Rockstar Games")],+ "amazon": [os.path.join(P["LAD"], "Amazon Games")],+ "playnite": [os.path.join(P["RAD"], "Playnite"), os.path.join(P["LAD"], "Playnite")],+ "heroic": [os.path.join(P["RAD"], "heroic")],+ }+ hits = sorted(k for k, ps in cands.items() if any(_ex(p) for p in ps))+ return {"present": True, "launchers": hits} if hits else None+++@probe(id="emulators", level="L1", family="gaming", tier="T0", collect="core")+def emulators(h, facts):+ """Emulator config dirs (RetroArch, Ryujinx, yuzu, Dolphin, PCSX2, RPCS3, Cemu, ...)."""+ P = _paths()+ docs = os.path.join(P["HOME"], "Documents")+ cands = {"RetroArch": [os.path.join(P["RAD"], "RetroArch"), r"C:\RetroArch-Win64"], "Ryujinx": [os.path.join(P["RAD"], "Ryujinx")],+ "yuzu/suyu": [os.path.join(P["RAD"], "yuzu"), os.path.join(P["RAD"], "suyu")],+ "Dolphin": [os.path.join(P["RAD"], "Dolphin Emulator"), os.path.join(docs, "Dolphin Emulator")],+ "PCSX2": [os.path.join(P["RAD"], "PCSX2"), os.path.join(docs, "PCSX2")], "RPCS3": [os.path.join(P["RAD"], "rpcs3")],+ "Cemu": [os.path.join(P["RAD"], "Cemu")], "DuckStation": [os.path.join(docs, "DuckStation")],+ "PPSSPP": [os.path.join(docs, "PPSSPP")], "xemu": [os.path.join(P["RAD"], "xemu")],+ "Xenia": [os.path.join(docs, "Xenia")], "melonDS": [os.path.join(P["RAD"], "melonDS")]}+ hits = sorted(k for k, ps in cands.items() if any(_ex(p) for p in ps))+ return {"present": True, "found": hits} if hits else None+++@probe(id="gaming.anticheat", level="L1", family="gaming", tier="T0", collect="core")+def gaming_anticheat(h, facts):+ """Anti-cheat drivers/dirs (BattlEye, EasyAntiCheat, Vanguard, FACEIT): competitive-shooter hint."""+ P = _paths()+ cands = {"BattlEye": [os.path.join(P["LAD"], "BattlEye"), os.path.join(P["PF86"], "Common Files", "BattlEye")],+ "EasyAntiCheat": [os.path.join(P["PF86"], "EasyAntiCheat_EOS"), os.path.join(P["PF86"], "EasyAntiCheat")],+ "Vanguard": [os.path.join(P["PF"], "Riot Vanguard")], "FACEIT": [os.path.join(P["PF"], "FACEIT AC")]}+ hits = sorted(k for k, ps in cands.items() if any(_ex(p) for p in ps))+ return {"present": True, "found": hits} if hits else None+++@probe(id="gaming.secondary_drive", level="L1", family="gaming", tier="T0", collect="core")+def gaming_secondary_drive(h, facts):+ """Game folders on D:/E: (Games, SteamLibrary, XboxGames, Epic Games, GOG Games) with entry counts."""+ out = []+ for drv in ("D:\\", "E:\\", "F:\\"):+ if not _ex(drv):+ continue+ for n in ("Games", "SteamLibrary", "XboxGames", "Epic Games", "GOG Games"):+ p = os.path.join(drv, n)+ if _ex(p):+ out.append([p, max(h.count_dir(p, 1000), 0)])+ return {"present": True, "dirs": out} if out else None+++@probe(id="gaming.save_roots", level="L1", family="gaming", tier="T0", collect="core")+def gaming_save_roots(h, facts):+ """My Games / Saved Games / LocalLow roots exist; gates gaming.save_dirs."""+ home = os.path.expanduser("~")+ roots = [p for p in (os.path.join(home, "Documents", "My Games"), os.path.join(home, "Saved Games"),+ os.path.join(home, "AppData", "LocalLow")) if _ex(p)]+ return {"present": True, "roots": len(roots)} if roots else None+++@probe(id="gaming.save_dirs", level="L2", family="gaming", tier="T2", collect="extended", gate="gaming.save_roots")+def gaming_save_dirs(h, facts):+ """Game titles/publishers from My Games, Saved Games and LocalLow dir names (bounded listdir)."""+ home = os.path.expanduser("~")+ skip = {"microsoft", "nvidia", "intel", "adobe", "com.adobe.crashreporter", "temp", "desktop.ini", "sun", "oracle",+ "unity", "google", "mozilla", "igdump"}+ out = {}+ for key, p in (("my_games", os.path.join(home, "Documents", "My Games")), ("saved_games", os.path.join(home, "Saved Games")),+ ("locallow", os.path.join(home, "AppData", "LocalLow"))):+ names = [n for n in h.list_dir(p, 300) if n.lower() not in skip and not n.endswith(".ini")+ and not re.fullmatch(r"[0-9a-fA-F-]{32,}", n) and not _noise("\\" + n + "\\")]+ out[key] = sorted(names)[:40]+ return {"present": any(out.values()), **out}+++# ================================================================= MEDIA++@probe(id="nvidia.app", level="L1", family="hardware", tier="T0", collect="core")+def nvidia_app(h, facts):+ """NVIDIA App backend dir present; gates the NVIDIA subtree."""+ return {"present": True} if _ex(os.path.join(_paths()["LAD"], "NVIDIA Corporation", "NVIDIA App", "NvBackend")) else None+++@probe(id="nvidia.library", level="L2", family="gaming", tier="T0", collect="core", gate="nvidia.app")+def nvidia_library(h, facts):+ """Apps and games detected by NVIDIA App (ApplicationStorage.json)."""+ p = os.path.join(_paths()["LAD"], "NVIDIA Corporation", "NVIDIA App", "NvBackend", "ApplicationStorage.json")+ t = _read(p)+ if not t:+ return {"present": False}+ try:+ j = json.loads(t)+ except Exception:+ return {"present": False, "error": "json"}+ names = []+ for a in j.get("Applications", [])[:500]:+ ap = a.get("Application", a) if isinstance(a, dict) else {}+ if ap.get("DisplayName"):+ names.append(ap["DisplayName"])+ return {"present": bool(names), "count": len(names), "apps": names[:40], "mtime": _mtime(p),+ "app_version": (_unmatch(h, r"^NVIDIA App \d") or [{}])[0].get("version")}+++@probe(id="nvidia.recommendations", level="L2", family="gaming", tier="T2", collect="core", gate="nvidia.app")+def nvidia_recommendations(h, facts):+ """Per-game optimisation dirs in NvBackend\\Recommendations; persist after uninstall (game history)."""+ d = os.path.join(_paths()["LAD"], "NVIDIA Corporation", "NVIDIA App", "NvBackend", "Recommendations")+ names = sorted(n for n in h.list_dir(d, 500) if os.path.isdir(os.path.join(d, n)))+ return {"present": bool(names), "count": len(names), "games": names[:60]}+++@probe(id="captures.nvidia", level="L2", family="media", tier="T2", collect="core", gate="nvidia.app")+def captures_nvidia(h, facts):+ """NVIDIA overlay captures: file count and size; per-game folder counts (folder names are game titles)."""+ P = _paths()+ capdir = None+ t = _read(os.path.join(P["LAD"], "NVIDIA Corporation", "NVIDIA Overlay", "GallerySettings.json"))+ if t:+ try:+ capdir = json.loads(t).get("settings", {}).get("currentDirectoryV2")+ except Exception:+ pass+ capdir = capdir or os.path.join(P["HOME"], "Videos", "NVIDIA")+ if not _ex(capdir):+ return {"present": False}+ n = b = seen = 0+ per = {}+ for root, dirs, files in os.walk(capdir):+ seen += 1+ if seen > 500 or root.count(os.sep) - capdir.count(os.sep) >= 2:+ dirs[:] = []+ for f in files[:5000]:+ n += 1+ try:+ b += os.path.getsize(os.path.join(root, f))+ except OSError:+ pass+ if root != capdir and files:+ per[os.path.basename(root)] = len(files)+ return {"present": True, "dir_is_default": capdir.lower().endswith("videos\\nvidia"), "files": n,+ "mb": round(b / 1e6), "game_folders": dict(sorted(per.items(), key=lambda kv: -kv[1])[:20])}+++@probe(id="captures.gamebar", level="L2", family="media", tier="T0", collect="core", gate="xbox.present")+def captures_gamebar(h, facts):+ """Game Bar captures dir (Videos\\Captures): file count and size."""+ cap = os.path.join(os.path.expanduser("~"), "Videos", "Captures")+ n = b = 0+ try:+ with os.scandir(cap) as it:+ for e in it:+ if n >= 5000:+ break+ if e.is_file():+ n += 1+ b += e.stat().st_size+ except OSError:+ return {"present": False}+ return {"present": True, "files": n, "mb": round(b / 1e6)}+++@probe(id="nvidia.shadowplay", level="L1", family="media", tier="T0", collect="core")+def nvidia_shadowplay(h, facts):+ """NVIDIA overlay/instant replay/highlights/mic flags (NVSPCAPS REG_BINARY dwords)."""+ sp = r"HKCU\Software\NVIDIA Corporation\Global\ShadowPlay\NVSPCAPS"+ out = {}+ for k, name in (("overlay_enabled", "IsShadowPlayEnabledUser"), ("instant_replay_or_rec", "RecEnabled"),+ ("highlights", "HLEnabled"), ("mic", "EnableMicrophone")):+ v = h.reg(sp, name)+ if isinstance(v, (bytes, bytearray)) and len(v) >= 4:+ v = int.from_bytes(v[:4], "little")+ if v is not None:+ out[k] = v+ return {"present": True, **out} if out else None+++@probe(id="nvidia.broadcast", level="L1", family="media", tier="T0", collect="core")+def nvidia_broadcast(h, facts):+ """NVIDIA Broadcast / G-Assist presence."""+ P = _paths()+ b = any(_ex(p) for p in (os.path.join(P["PD"], "NVIDIA Corporation", "NVIDIA Broadcast"),+ os.path.join(P["PF"], "NVIDIA Corporation", "NVIDIA Broadcast")))+ g = _ex(os.path.join(P["PD"], "NVIDIA Corporation", "nvtopps", "rise")) or _ex(os.path.join(P["PF"], "NVIDIA Corporation", "NVIDIA G-Assist"))+ return {"present": True, "broadcast": b, "g_assist": g} if (b or g) else None+++@probe(id="media.obs", level="L1", family="media", tier="T0", collect="core")+def media_obs(h, facts):+ """OBS/Streamlabs presence and whether a config dir exists (launched at least once); agent-container copies flagged."""+ P = _paths()+ installs, configs = [], []+ if _ex(os.path.join(P["PF"], "obs-studio")):+ installs.append("program_files")+ wg = os.path.join(P["LAD"], "Microsoft", "WinGet", "Packages")+ for n in h.list_dir(wg, 1000):+ if n.lower().startswith("obsproject.obsstudio"):+ installs.append("winget_portable")+ if _ex(os.path.join(wg, n, "config", "obs-studio")):+ configs.append("winget_portable")+ if _ex(os.path.join(P["RAD"], "obs-studio")):+ configs.append("roaming")+ agent_cfg = 0+ for n in h.list_dir(os.path.join(P["LAD"], "Packages"), 2000):+ if n.lower().startswith(("openai.codex", "anthropic.claude")):+ if _ex(os.path.join(P["LAD"], "Packages", n, "LocalCache", "Roaming", "obs-studio")):+ agent_cfg += 1+ sl = _ex(os.path.join(P["PF"], "Streamlabs OBS"))+ sl_cfg = _ex(os.path.join(P["RAD"], "slobs-client"))+ if not (installs or configs or sl or agent_cfg):+ return None+ return {"present": True, "obs_installs": installs, "obs_configs": configs, "config_dir": bool(configs), "obs_config_in_agent_container": agent_cfg,+ "streamlabs": sl, "streamlabs_config": sl_cfg}+++@probe(id="media.players", level="L1", family="media", tier="T0", collect="core")+def media_players(h, facts):+ """Music/video players and streaming apps (Spotify, Apple Music, Store players, mpv, Plex, ...)."""+ P = _paths()+ pkgs = [n.lower() for n in h.list_dir(os.path.join(P["LAD"], "Packages"), 3000)]++ def pkg(prefix):+ return any(n.startswith(prefix.lower()) for n in pkgs)+ found = {"spotify": _ex(os.path.join(P["RAD"], "Spotify")) or pkg("SpotifyAB.SpotifyMusic"),+ "apple_music": pkg("AppleInc.AppleMusic"), "media_player_uwp": pkg("Microsoft.ZuneMusic"),+ "netflix": pkg("4DF9E0F8.Netflix"), "prime_video": pkg("AmazonVideo.PrimeVideo"), "disney": pkg("Disney."),+ "mpv": _ex(os.path.join(P["RAD"], "mpv")), "mpc_hc": _ex(os.path.join(P["PF"], "MPC-HC")),+ "potplayer": _ex(os.path.join(P["PF"], "DAUM", "PotPlayer")), "foobar2000": _ex(os.path.join(P["RAD"], "foobar2000")),+ "musicbee": _ex(os.path.join(P["RAD"], "MusicBee")), "plex": _ex(os.path.join(P["LAD"], "Plex")),+ "kodi": _ex(os.path.join(P["RAD"], "Kodi")), "tidal": _ex(os.path.join(P["LAD"], "TIDAL"))}+ hits = sorted(k for k, v in found.items() if v)+ return {"present": True, "players": hits} if hits else None+++@probe(id="media.vlc", level="L1", family="media", tier="T0", collect="core")+def media_vlc(h, facts):+ """VLC installed and whether a user config exists."""+ P = _paths()+ inst = _ex(os.path.join(P["PF"], "VideoLAN", "VLC")) or _ex(os.path.join(P["PF86"], "VideoLAN", "VLC"))+ cfg = _ex(os.path.join(P["RAD"], "vlc"))+ return {"present": True, "installed": inst, "user_config": cfg} if (inst or cfg) else None+++@probe(id="media.vlc_recents", level="L2", family="media", tier="T2", collect="extended", gate="media.vlc")+def media_vlc_recents(h, facts):+ """VLC recent-media count, local vs stream split and extension histogram; the MRL list itself is not emitted."""+ qi = os.path.join(_paths()["RAD"], "vlc", "vlc-qt-interface.ini")+ t = _read(qi, 2_000_000)+ if not t:+ return {"present": False}+ m = re.search(r"^\[RecentsMRL\][^\[]*?^list=(.*)$", t, re.M | re.S)+ items = [x.strip() for x in m.group(1).split(",") if x.strip()] if m else []+ kinds = collections.Counter("local" if x.startswith("file:") else "stream" for x in items)+ exts = collections.Counter()+ for x in items:+ if x.startswith("file:"):+ m2 = re.search(r"\.([A-Za-z0-9]{1,5})$", x.split("?")[0])+ exts["." + m2.group(1).lower() if m2 else ""] += 1+ own = sum(1 for x in items if "/Videos/Captures/" in x or "/Videos/NVIDIA/" in x)+ return {"present": bool(items), "count": len(items), "kinds": dict(kinds), "ext": dict(exts),+ "from_own_capture_dirs": own, "ini_mtime": _mtime(qi)}+++_MEDIA_EXT = {"video": {".mp4", ".mkv", ".avi", ".mov", ".webm", ".wmv", ".m4v", ".flv", ".ts"},+ "audio": {".mp3", ".flac", ".m4a", ".wav", ".ogg", ".opus", ".aac", ".wma"},+ "image": {".jpg", ".jpeg", ".png", ".gif", ".webp", ".heic", ".bmp", ".tif", ".tiff", ".raw", ".dng", ".jxr"}}+++def _walk_media(root, max_depth=4, max_files=20000, budget_s=1.5):+ t0 = time.perf_counter()+ st = {"files": 0, "bytes": 0, "video": 0, "audio": 0, "image": 0, "cloud_only": 0, "truncated": False}+ stack = [(root, 0)]+ while stack:+ p, dep = stack.pop()+ if _noise(p + "\\"):+ continue+ try:+ it = os.scandir(p)+ except OSError:+ continue+ with it:+ for e in it:+ if time.perf_counter() - t0 > budget_s or st["files"] >= max_files:+ st["truncated"] = True+ return st+ try:+ if e.is_dir(follow_symlinks=False):+ if dep < max_depth:+ stack.append((e.path, dep + 1))+ continue+ s = e.stat(follow_symlinks=False)+ except OSError:+ continue+ st["files"] += 1+ if getattr(s, "st_file_attributes", 0) & (0x400000 | 0x1000):+ st["cloud_only"] += 1+ else:+ st["bytes"] += s.st_size+ ext = os.path.splitext(e.name)[1].lower()+ for k, exts in _MEDIA_EXT.items():+ if ext in exts:+ st[k] += 1+ break+ return st+++@probe(id="media.libraries", level="L1", family="media", tier="T1", collect="core")+def media_libraries(h, facts):+ """Music/Videos/Pictures known-folder file counts by type and size (bounded walk), plus Screenshots count."""+ home = os.path.expanduser("~")+ usf = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"+ out = {}+ for short, regname in (("Music", "My Music"), ("Videos", "My Video"), ("Pictures", "My Pictures")):+ p = os.path.expandvars(h.reg(usf, regname) or os.path.join(home, short))+ s = _walk_media(p)+ s["gb"] = round(s.pop("bytes") / 1e9, 2)+ s["onedrive"] = "onedrive" in p.lower()+ out[short] = s+ out["screenshots"] = max(h.count_dir(os.path.join(home, "Pictures", "Screenshots"), 20000), 0)+ return {"present": True, **out}diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/usage_gaming_hardware.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/usage_gaming_hardware.pynew file mode 100644index 00000000000..b79a44af07e--- /dev/null+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/usage_gaming_hardware.py@@ -0,0 +1,644 @@+"""Hardware and health probes (Windows).++Registration only at import time. Shared helpers live in usage_gaming.+"""+from __future__ import annotations++import collections+import datetime as dt+import os+import re+import time++from ..registry import probe, ps_probe+from .usage_gaming import (_EVT_NS, _base, _evt_fields, _ex, _ft, _iso, _mtime, _paths, _read,+ _reg_keys, _reg_values, _unmatch, _wevt)++# ================================================================= HARDWARE++@probe(id="hw.system", level="L1", family="hardware", tier="T0", collect="core")+def hw_system(h, facts):+ """SMBIOS system/board/BIOS from registry, visible RAM (GlobalMemoryStatusEx), fixed-drive free space."""+ import ctypes+ b = _reg_values(r"HKLM\HARDWARE\DESCRIPTION\System\BIOS", 100)++ class MEMSTAT(ctypes.Structure):+ _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong)] + [+ (n, ctypes.c_ulonglong) for n in ("total", "avail", "tpf", "apf", "tv", "av", "aev")]+ ms = MEMSTAT()+ ms.dwLength = ctypes.sizeof(ms)+ ram = None+ if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(ms)):+ ram = round(ms.total / 2 ** 30, 1)+ drives = []+ k32 = ctypes.windll.kernel32+ mask = k32.GetLogicalDrives()+ for i in range(26):+ if not mask & (1 << i):+ continue+ root = chr(65 + i) + ":\\"+ if k32.GetDriveTypeW(ctypes.c_wchar_p(root)) != 3:+ continue+ free, total = ctypes.c_ulonglong(0), ctypes.c_ulonglong(0)+ if k32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(root), None, ctypes.byref(total), ctypes.byref(free)) and total.value:+ drives.append([root[:2], round(total.value / 1e9, 1), round(free.value / 1e9, 1),+ round(100 * free.value / total.value, 1)])+ return {"present": True, "manufacturer": b.get("SystemManufacturer"), "product": b.get("SystemProductName"),+ "family": b.get("SystemFamily"), "board_vendor": b.get("BaseBoardManufacturer"),+ "board": b.get("BaseBoardProduct"), "bios_vendor": b.get("BIOSVendor"), "bios_version": b.get("BIOSVersion"),+ "bios_date": b.get("BIOSReleaseDate"), "visible_ram_gb": ram, "memory_load_pct": ms.dwMemoryLoad if ram else None,+ "fixed_drives_total_free_gb_pct": drives}+++@probe(id="hw.cpu", level="L2", family="hardware", tier="T0", collect="core", gate="hw.system")+def hw_cpu(h, facts):+ """CPU name, vendor, MHz and logical processor count from HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor."""+ base = r"HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor"+ cores = _reg_keys(h, base, 1024)+ v = _reg_values(base + "\\0", 50)+ if not v:+ return {"present": False}+ return {"present": True, "name": (v.get("ProcessorNameString") or "").strip(), "vendor": v.get("VendorIdentifier"),+ "mhz": v.get("~MHz"), "logical_processors": len(cores), "native_arch": h.l0.get("native_arch")}+++@probe(id="hw.gpu", level="L1", family="hardware", tier="T0", collect="core")+def hw_gpu(h, facts):+ """Display adapters from the Display class registry key: name, driver version, VRAM (qwMemorySize)."""+ base = r"HKLM\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"+ out = []+ for sk in _reg_keys(h, base, 50):+ if not sk.isdigit():+ continue+ v = _reg_values(base + "\\" + sk, 400)+ name = v.get("DriverDesc")+ if not name:+ continue+ mem = v.get("HardwareInformation.qwMemorySize")+ if mem is None:+ m2 = v.get("HardwareInformation.MemorySize")+ mem = int.from_bytes(m2[:8], "little") if isinstance(m2, (bytes, bytearray)) else m2+ out.append({"name": name, "driver": v.get("DriverVersion"), "driver_date": v.get("DriverDate"),+ "vram_gb": round(mem / 2 ** 30, 1) if isinstance(mem, int) and mem > 0 else None,+ "vendor": v.get("ProviderName")})+ real = [g for g in out if not re.search(r"Microsoft Basic|Remote Display|Virtual|Parsec|Meta Virtual", g["name"], re.I)]+ vr = [g["vram_gb"] for g in real if g["vram_gb"]]+ return {"present": True, "max_vram_gb": max(vr) if vr else None, "adapters": real, "other": len(out) - len(real)} if out else None+++@probe(id="hw.power_plan", level="L2", family="hardware", tier="T0", collect="core", gate="hw.system")+def hw_power_plan(h, facts):+ """Active power scheme GUID and friendly name from registry; Modern Standby flag."""+ known = {"381b4222-f694-41f0-9685-ff5bb260df2e": "Balanced", "8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c": "High performance",+ "a1841308-3541-4fab-bc81-f71556f20b4a": "Power saver", "e9a42b02-d5df-448d-aa00-03f14749eb61": "Ultimate Performance"}+ base = r"HKLM\SYSTEM\CurrentControlSet\Control\Power\User\PowerSchemes"+ g = h.reg(base, "ActivePowerScheme")+ if not g:+ return {"present": False}+ fname = h.reg(base + "\\" + g, "FriendlyName")+ if fname and fname.startswith("@"):+ fname = None+ ov = {"ded574b5-45a0-4f42-8737-46345c09c238": "Best performance", "961cc777-2547-4f9d-8174-7d86181b8a7a": "Best power efficiency",+ "00000000-0000-0000-0000-000000000000": "Balanced"}+ ac = h.reg(base, "ActiveOverlayAcPowerScheme")+ cs = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\Power", "CsEnabled")+ return {"present": True, "guid": g, "name": known.get(g.lower()) or fname or "custom",+ "overlay_ac": ov.get((ac or "").lower(), ac), "modern_standby": cs}+++@probe(id="hw.battery", level="L1", family="hardware", tier="T0", collect="core")+def hw_battery(h, facts):+ """Battery present (GetSystemPowerStatus + ACPI PNP0C0A); laptop vs desktop."""+ import ctypes++ class SPS(ctypes.Structure):+ _fields_ = [("ac", ctypes.c_ubyte), ("flag", ctypes.c_ubyte), ("pct", ctypes.c_ubyte), ("saver", ctypes.c_ubyte),+ ("life", ctypes.c_ulong), ("full", ctypes.c_ulong)]+ s = SPS()+ ok = ctypes.windll.kernel32.GetSystemPowerStatus(ctypes.byref(s))+ acpi = bool(_reg_keys(h, r"HKLM\SYSTEM\CurrentControlSet\Enum\ACPI\PNP0C0A", 10))+ has = acpi or (ok and s.flag not in (128, 255))+ if not has:+ return None+ return {"present": True, "on_ac": s.ac == 1 if ok else None, "charge_pct": s.pct if ok and s.pct <= 100 else None,+ "battery_saver": bool(s.saver) if ok else None}+++@probe(id="boot.fastboot", level="L1", family="hardware", tier="T0", collect="core")+def boot_fastboot(h, facts):+ """Fast Startup (HiberbootEnabled): needed to read 'shutdown' events correctly."""+ v = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power", "HiberbootEnabled")+ hib = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\Power", "HibernateEnabled")+ if v is None and hib is None:+ return None+ return {"present": True, "fast_startup": v, "hibernate_enabled": hib}+++@probe(id="tuning.afterburner", level="L1", family="hardware", tier="T0", collect="core")+def tuning_afterburner(h, facts):+ """MSI Afterburner: autostart, fan curve, logging, per-GPU profiles (power limit, offsets, VF curve)."""+ ab = os.path.join(_paths()["PF86"], "MSI Afterburner")+ if not _ex(ab):+ return None+ out = {"present": True}+ t = _read(os.path.join(ab, "Profiles", "MSIAfterburner.cfg"), 500_000)+ if t:+ def k(n):+ m = re.search(rf"^{n}=(.*)$", t, re.M)+ return m.group(1).strip() if m else None+ out.update(start_with_windows=k("StartWithWindows"), sw_fan_curve=k("SwAutoFanControl"),+ hw_log=k("EnableHwMonitoringLog") or k("EnableLog"))+ gpus = []+ for f in h.list_dir(os.path.join(ab, "Profiles"), 100):+ if f.startswith("VEN_") and not f.startswith("VEN_0000"):+ tt = _read(os.path.join(ab, "Profiles", f), 500_000) or ""++ def g(n):+ m = re.search(rf"^{n}=(\S+)", tt, re.M)+ return m.group(1) if m else None+ gpus.append({"vendor": {"10DE": "NVIDIA", "8086": "Intel", "1002": "AMD"}.get(f[4:8], f[4:8]), "dev": f[13:17],+ "power_limit": g("PowerLimit"), "core_offset": g("CoreClkBoost"), "fan_mode": g("FanMode"),+ "vf_curve": bool(g("VFCurve"))})+ out["gpu_profiles"] = gpus+ out["version"] = (_unmatch(h, r"MSI Afterburner") or [{}])[0].get("version")+ return out+++@probe(id="tuning.rtss", level="L1", family="hardware", tier="T0", collect="core")+def tuning_rtss(h, facts):+ """RivaTuner Statistics Server presence and per-game profile count."""+ rt = os.path.join(_paths()["PF86"], "RivaTuner Statistics Server")+ if not _ex(rt):+ return None+ prof = [f for f in h.list_dir(os.path.join(rt, "Profiles"), 2000) if f.endswith(".cfg") and f.lower() != "global"]+ return {"present": True, "profiles": len(prof)}+++@probe(id="periph.rgb_suites", level="L2", family="hardware", tier="T0", collect="core", gate="hw.system")+def periph_rgb_suites(h, facts):+ """RGB / peripheral vendor suites from the uninstall index (Razer, Logi, Corsair, ASUS Aura, OpenRGB, ...)."""+ hits = _unmatch(h, r"Razer|Logi|G HUB|SteelSeries|Corsair|iCUE|HyperX|NGENUITY|Patriot Viper|Armoury|\bAura\b|OpenRGB|"+ r"SignalRGB|Wallpaper Engine|DS4Windows|8BitDo|Xbox Accessories|Stream Deck|Elgato|Wooting|NZXT")+ names = sorted({re.sub(r"\s+[\d.]+$", "", x["name"]) for x in hits})+ return {"present": bool(names), "count": len(hits), "suites": names[:25]}+++@probe(id="hw.audio", level="L2", family="hardware", tier="T1", collect="extended", gate="hw.system")+def hw_audio(h, facts):+ """Audio endpoints from MMDevices registry: active render/capture counts and adapter interface names."""+ base = r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio"+ out = {"present": False}+ for kind in ("Render", "Capture"):+ keys = _reg_keys(h, base + "\\" + kind, 300)+ active = []+ for k in keys:+ st = h.reg(base + "\\" + kind + "\\" + k, "DeviceState")+ if st == 1:+ iface = h.reg(base + "\\" + kind + "\\" + k + "\\Properties", "{b3f8fa53-0004-438e-9003-51a46e139bfc},6")+ active.append(re.sub(r"(?i)\b[A-Z][a-z]+'s\b", "<name>'s", iface or "?"))+ out[kind.lower()] = {"total": len(keys), "active": len(active), "active_ifaces": sorted(set(active))[:12]}+ out["present"] = out["present"] or bool(keys)+ return out+++@probe(id="hw.bluetooth", level="L2", family="hardware", tier="T1", collect="extended", gate="hw.system")+def hw_bluetooth(h, facts):+ """Paired Bluetooth devices by class (gamepad/audio/HID) from BTHPORT registry; device names not emitted."""+ base = r"HKLM\SYSTEM\CurrentControlSet\Services\BTHPORT\Parameters\Devices"+ keys = _reg_keys(h, base, 500)+ major = {0: "Misc", 1: "Computer", 2: "Phone", 3: "LAN", 4: "Audio/Video", 5: "Peripheral", 6: "Imaging",+ 7: "Wearable", 8: "Toy", 9: "Health", 31: "Uncategorized"}+ cls = collections.Counter()+ for k in keys:+ cod = h.reg(base + "\\" + k, "COD") or 0+ if isinstance(cod, bytes):+ cod = int.from_bytes(cod[:4], "little")+ maj, mn = (cod >> 8) & 0x1F, (cod >> 2) & 0x3F+ sub = None+ if maj == 5:+ sub = {0x10: "Keyboard", 0x20: "Mouse", 0x30: "Keyboard+Mouse", 0x01: "Joystick", 0x02: "Gamepad"}.get(mn & 0x33)+ elif maj == 4:+ sub = {1: "Headset", 2: "Handsfree", 4: "Microphone", 5: "Loudspeaker", 6: "Headphones"}.get(mn)+ if not sub:+ raw = h.reg(base + "\\" + k, "Name")+ nm = raw.decode("utf-8", "replace").strip("\0") if isinstance(raw, bytes) else ""+ for rx, lbl in ((r"(?i)controller|gamepad|dualsense|dualshock|joy-?con", "Gamepad"),+ (r"(?i)mouse|mx master|deathadder|mx anywhere", "Mouse"), (r"(?i)keyboard|keys\b", "Keyboard"),+ (r"(?i)WH-|WF-|buds|airpods|headphone|headset", "Headphones"), (r"(?i)speaker|soundbar|kanto", "Speaker")):+ if re.search(rx, nm):+ sub = lbl + "(name)"+ break+ cls[major.get(maj, str(maj)) + ("/" + sub if sub else "")] += 1+ le = sum(len(_reg_keys(h, r"HKLM\SYSTEM\CurrentControlSet\Enum\BTHLE\\" + d, 50))+ for d in _reg_keys(h, r"HKLM\SYSTEM\CurrentControlSet\Enum\BTHLE", 300))+ if not keys and not le:+ return {"present": False}+ return {"present": True, "classic_paired": len(keys), "ble_instances": le, "by_class": dict(cls)}+++@probe(id="hw.usb_history", level="L2", family="hardware", tier="T1", collect="extended", gate="hw.system")+def hw_usb_history(h, facts):+ """USB device ids/instances ever seen and USB storage count (Enum\\USB, USBSTOR); top vendor ids only."""+ base = r"HKLM\SYSTEM\CurrentControlSet\Enum\USB"+ ids = _reg_keys(h, base, 2000)+ inst = 0+ vids = collections.Counter()+ for i in ids:+ inst += len(_reg_keys(h, base + "\\" + i, 200))+ m = re.search(r"VID_([0-9A-Fa-f]{4})", i)+ if m:+ vids[m.group(1).upper()] += 1+ stor = sum(len(_reg_keys(h, r"HKLM\SYSTEM\CurrentControlSet\Enum\USBSTOR\\" + d, 100))+ for d in _reg_keys(h, r"HKLM\SYSTEM\CurrentControlSet\Enum\USBSTOR", 500))+ vend = {"046D": "Logitech", "1532": "Razer", "1B1C": "Corsair", "1038": "SteelSeries", "0B05": "ASUS", "045E": "Microsoft",+ "054C": "Sony", "057E": "Nintendo", "28DE": "Valve", "3434": "Keychron", "0951": "Kingston/HyperX", "03F0": "HP/HyperX",+ "8087": "Intel", "0BDA": "Realtek", "0955": "NVIDIA", "1462": "MSI", "05AC": "Apple", "04E8": "Samsung", "0781": "SanDisk"}+ if not ids:+ return {"present": False}+ return {"present": True, "device_ids_ever": len(ids), "instances_ever": inst, "usbstor_instances": stor,+ "top_vendors": [[v, vend.get(v), n] for v, n in vids.most_common(12)]}+++@probe(id="hw.monitor_mode", level="L2", family="hardware", tier="T0", collect="extended", gate="hw.system")+def hw_monitor_mode(h, facts):+ """Current resolution/refresh per display (EnumDisplaySettings); falls back to GraphicsDrivers\\Configuration."""+ import ctypes+ from ctypes import wintypes as W++ class DEVMODEW(ctypes.Structure):+ _fields_ = [("dmDeviceName", ctypes.c_wchar * 32), ("dmSpecVersion", W.WORD), ("dmDriverVersion", W.WORD),+ ("dmSize", W.WORD), ("dmDriverExtra", W.WORD), ("dmFields", W.DWORD), ("dmPositionX", W.LONG),+ ("dmPositionY", W.LONG), ("dmDisplayOrientation", W.DWORD), ("dmDisplayFixedOutput", W.DWORD),+ ("dmColor", ctypes.c_short), ("dmDuplex", ctypes.c_short), ("dmYResolution", ctypes.c_short),+ ("dmTTOption", ctypes.c_short), ("dmCollate", ctypes.c_short), ("dmFormName", ctypes.c_wchar * 32),+ ("dmLogPixels", W.WORD), ("dmBitsPerPel", W.DWORD), ("dmPelsWidth", W.DWORD), ("dmPelsHeight", W.DWORD),+ ("dmDisplayFlags", W.DWORD), ("dmDisplayFrequency", W.DWORD), ("dmICMMethod", W.DWORD),+ ("dmICMIntent", W.DWORD), ("dmMediaType", W.DWORD), ("dmDitherType", W.DWORD), ("dmReserved1", W.DWORD),+ ("dmReserved2", W.DWORD), ("dmPanningWidth", W.DWORD), ("dmPanningHeight", W.DWORD)]++ class DISPLAY_DEVICEW(ctypes.Structure):+ _fields_ = [("cb", W.DWORD), ("DeviceName", ctypes.c_wchar * 32), ("DeviceString", ctypes.c_wchar * 128),+ ("StateFlags", W.DWORD), ("DeviceID", ctypes.c_wchar * 128), ("DeviceKey", ctypes.c_wchar * 128)]+ u32 = ctypes.windll.user32+ modes = []+ i = 0+ while i < 16:+ dd = DISPLAY_DEVICEW()+ dd.cb = ctypes.sizeof(dd)+ if not u32.EnumDisplayDevicesW(None, i, ctypes.byref(dd), 0):+ break+ i += 1+ if not dd.StateFlags & 1:+ continue+ dm = DEVMODEW()+ dm.dmSize = ctypes.sizeof(dm)+ if u32.EnumDisplaySettingsW(dd.DeviceName, -1, ctypes.byref(dm)):+ modes.append({"w": dm.dmPelsWidth, "h": dm.dmPelsHeight, "hz": dm.dmDisplayFrequency, "adapter": dd.DeviceString})+ if modes:+ return {"present": True, "via": "EnumDisplaySettings", "displays": modes}+ base = r"HKLM\SYSTEM\CurrentControlSet\Control\GraphicsDrivers\Configuration"+ best, best_ts = None, -1+ for cfg in _reg_keys(h, base, 200):+ ts = h.reg(base + "\\" + cfg, "Timestamp") or 0+ if isinstance(ts, int) and ts > best_ts:+ best, best_ts = cfg, ts+ if not best:+ return {"present": False}+ out = []+ for t in _reg_keys(h, base + "\\" + best, 20):+ for m in _reg_keys(h, base + "\\" + best + "\\" + t, 20):+ v = _reg_values(base + "\\" + best + "\\" + t + "\\" + m, 100)+ if v.get("PrimSurfSize.cx"):+ num, den = v.get("VSyncFreq.Numerator"), v.get("VSyncFreq.Denominator")+ out.append({"w": v["PrimSurfSize.cx"], "h": v.get("PrimSurfSize.cy"),+ "hz": round(num / den, 1) if num and den else None})+ return {"present": bool(out), "via": "GraphicsDrivers\\Configuration", "committed": _iso(_ft(best_ts)), "displays": out}+++@probe(id="hw.nvidia_smi", level="L2", family="hardware", tier="T0", collect="extended", gate="hw.gpu")+def hw_nvidia_smi(h, facts):+ """nvidia-smi query: VRAM, power draw/limit, temperature, pstate, driver."""+ P = _paths()+ exe = next((p for p in (os.path.join(P["WIN"], "System32", "nvidia-smi.exe"),+ os.path.join(P["PF"], "NVIDIA Corporation", "NVSMI", "nvidia-smi.exe")) if _ex(p)), None)+ if not exe:+ return {"present": False}+ fields = "name,memory.total,power.draw,power.limit,power.default_limit,power.max_limit,temperature.gpu,pstate,driver_version,fan.speed"+ out = h.run([exe, "--query-gpu=" + fields, "--format=csv,noheader,nounits"], timeout_ms=5000, text=False)+ if not out:+ return {"present": False, "exe": True}+ gpus = []+ for line in out.strip().splitlines()[:8]:+ vals = [x.strip() for x in line.split(",")]+ gpus.append({k: (None if v in ("[N/A]", "N/A", "[Not Supported]") else v) for k, v in zip(fields.split(","), vals)})+ vram = None+ try:+ vram = round(max(float(g["memory.total"]) for g in gpus if g.get("memory.total")) / 1024, 1)+ except ValueError:+ pass+ return {"present": bool(gpus), "vram_gb": vram, "gpus": gpus}+++ps_probe("hw.monitors", r"""+try {+ function U($a) { if ($a) { (($a | Where-Object { $_ -ne 0 } | ForEach-Object { [char]$_ }) -join '').Trim() } }+ $ids = @(Get-CimInstance -Namespace root\wmi -ClassName WmiMonitorID -ErrorAction SilentlyContinue | ForEach-Object {+ [ordered]@{ mfr = (U $_.ManufacturerName); product = (U $_.ProductCodeID); name = (U $_.UserFriendlyName); year = $_.YearOfManufacture; active = $_.Active } })+ $size = @(Get-CimInstance -Namespace root\wmi -ClassName WmiMonitorBasicDisplayParams -ErrorAction SilentlyContinue | ForEach-Object {+ if ($_.MaxHorizontalImageSize) { [math]::Round([math]::Sqrt([math]::Pow($_.MaxHorizontalImageSize,2)+[math]::Pow($_.MaxVerticalImageSize,2))/2.54,1) } })+ $tech = @(Get-CimInstance -Namespace root\wmi -ClassName WmiMonitorConnectionParams -ErrorAction SilentlyContinue | ForEach-Object {+ switch ([int64]$_.VideoOutputTechnology) { 0 {'VGA'} 4 {'DVI'} 5 {'HDMI'} 10 {'DP'} 11 {'DP-embedded'} 2147483648 {'Internal'} default { [string]$_.VideoOutputTechnology } } })+ [ordered]@{ present = ($ids.Count -gt 0); count = $ids.Count; monitors = $ids; diag_in = $size; outputs = $tech }+} catch { [ordered]@{ present = $false; error = $_.Exception.Message } }+""", family="hardware", tier="T0", collect="extended", gate="hw.system", timeout_ms=6000,+ doc="Connected monitors from EDID (WmiMonitorID): maker, model, year, size, connection; no serials.")++ps_probe("hw.ram", r"""+try {+ $m = @(Get-CimInstance Win32_PhysicalMemory -ErrorAction SilentlyContinue)+ $a = @(Get-CimInstance Win32_PhysicalMemoryArray -ErrorAction SilentlyContinue)+ [ordered]@{ present = ($m.Count -gt 0); modules = $m.Count+ total_gb = [math]::Round((($m | Measure-Object Capacity -Sum).Sum) / 1GB, 1)+ slots = ($a | Measure-Object MemoryDevices -Sum).Sum+ speed = @($m | ForEach-Object { $_.Speed } | Select-Object -Unique)+ configured = @($m | ForEach-Object { $_.ConfiguredClockSpeed } | Select-Object -Unique)+ rated_mhz = ($m | Measure-Object Speed -Minimum).Minimum; configured_mhz = ($m | Measure-Object ConfiguredClockSpeed -Minimum).Minimum+ smbios_type = @($m | ForEach-Object { $_.SMBIOSMemoryType } | Select-Object -Unique)+ mfr = @($m | ForEach-Object { ([string]$_.Manufacturer).Trim() } | Select-Object -Unique)+ part = @($m | ForEach-Object { ([string]$_.PartNumber).Trim() } | Select-Object -Unique) }+} catch { [ordered]@{ present = $false; error = $_.Exception.Message } }+""", family="hardware", tier="T0", collect="extended", gate="hw.system", timeout_ms=6000,+ doc="Installed RAM modules, slots, rated vs configured speed (Win32_PhysicalMemory).")++ps_probe("hw.disks", r"""+try {+ $pd = @(Get-PhysicalDisk -ErrorAction SilentlyContinue | ForEach-Object {+ $rc = $_ | Get-StorageReliabilityCounter -ErrorAction SilentlyContinue+ [ordered]@{ name = $_.FriendlyName; media = [string]$_.MediaType; bus = [string]$_.BusType; size_gb = [math]::Round($_.Size/1GB)+ health = [string]$_.HealthStatus; wear_pct = $rc.Wear; temp_c = $rc.Temperature; temp_max_c = $rc.TemperatureMax+ power_on_h = $rc.PowerOnHours; read_err_uncorrected = $rc.ReadErrorsUncorrected; write_err_uncorrected = $rc.WriteErrorsUncorrected } })+ $vol = @(Get-Volume -ErrorAction SilentlyContinue | Where-Object { $_.DriveLetter -and $_.DriveType -eq 'Fixed' -and $_.Size } | ForEach-Object {+ [ordered]@{ letter = [string]$_.DriveLetter; size_gb = [math]::Round($_.Size/1GB,1); free_gb = [math]::Round($_.SizeRemaining/1GB,1)+ free_pct = [math]::Round(100*$_.SizeRemaining/$_.Size,1) } })+ [ordered]@{ present = ($pd.Count -gt 0); count = $pd.Count; disks = $pd; volumes = $vol }+} catch { [ordered]@{ present = $false; error = $_.Exception.Message } }+""", family="hardware", tier="T0", collect="deep", gate="hw.system", timeout_ms=15000,+ doc="Physical disks with health, wear, temperature and error counters (Get-PhysicalDisk).")++ps_probe("hw.gpu_history", r"""+try {+ $g = @(Get-PnpDevice -Class Display -ErrorAction SilentlyContinue | ForEach-Object {+ $fi = (Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName DEVPKEY_Device_FirstInstallDate -ErrorAction SilentlyContinue).Data+ $la = (Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName DEVPKEY_Device_LastArrivalDate -ErrorAction SilentlyContinue).Data+ [ordered]@{ name = $_.FriendlyName; pci = (($_.InstanceId -split '\\')[1] -replace '&REV.*$',''); present = $_.Present+ first = $(if ($fi) { ([datetime]$fi).ToString('s') }); last = $(if ($la) { ([datetime]$la).ToString('s') }) } })+ [ordered]@{ present = ($g.Count -gt 0); ever = $g.Count; now = @($g | Where-Object { $_.present }).Count+ swaps = @($g | Where-Object { -not $_.present -and $_.name -notmatch 'Basic|Remote|Virtual' }).Count; adapters = $g }+} catch { [ordered]@{ present = $false; error = $_.Exception.Message } }+""", family="hardware", tier="T0", collect="deep", gate="hw.gpu", timeout_ms=15000,+ doc="Every display adapter ever installed with first-install/last-arrival dates (GPU swaps).")++ps_probe("hw.monitor_history", r"""+try {+ $h = @(Get-PnpDevice -ErrorAction SilentlyContinue | Where-Object { $_.InstanceId -match '^DISPLAY\\' -and $_.InstanceId -notmatch 'DEFAULT_MONITOR' } | ForEach-Object {+ $fi = (Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName DEVPKEY_Device_FirstInstallDate -ErrorAction SilentlyContinue).Data+ $la = (Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName DEVPKEY_Device_LastArrivalDate -ErrorAction SilentlyContinue).Data+ [pscustomobject]@{ pnp = ($_.InstanceId -split '\\')[1]; present = [bool]$_.Present; first = $fi; last = $la } } |+ Group-Object pnp | ForEach-Object { $f = @($_.Group | Where-Object first | Sort-Object first); $l = @($_.Group | Where-Object last | Sort-Object last -Descending)+ [ordered]@{ pnp = $_.Name; present = [bool]($_.Group | Where-Object present)+ first = $(if ($f) { ([datetime]$f[0].first).ToString('s') }); last = $(if ($l) { ([datetime]$l[0].last).ToString('s') }) } })+ [ordered]@{ present = ($h.Count -gt 0); distinct_monitors_ever = $h.Count; changes = @($h | Where-Object { -not $_.present }).Count; monitors = $h }+} catch { [ordered]@{ present = $false; error = $_.Exception.Message } }+""", family="hardware", tier="T0", collect="deep", gate="hw.system", timeout_ms=15000,+ doc="Every monitor model (PnP id) ever connected with first/last dates.")++ps_probe("hw.peripherals", r"""+try {+ $cls = 'Keyboard','Mouse','HIDClass','Camera','Image','Biometric','XnaComposite','Printer','MEDIA','SmartCardReader'+ $pp = @(Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | Where-Object { $cls -contains $_.Class })+ $by = @{}; foreach ($d in $pp) { $by[[string]$d.Class] = 1 + [int]$by[[string]$d.Class] }+ $vids = @{}; foreach ($d in $pp) { if ($d.InstanceId -match 'VID_([0-9A-F]{4})') { $vids[$matches[1]] = 1 + [int]$vids[$matches[1]] } }+ $pads = @($pp | Where-Object { $_.Class -eq 'XnaComposite' -or $_.FriendlyName -match 'game ?controller|gamepad|xbox|dualsense|dualshock' }).Count+ $cams = @($pp | Where-Object { $_.Class -in 'Camera','Image' }).Count+ [ordered]@{ present = ($pp.Count -gt 0); by_class = $by; hid_vids = $vids; game_controllers = $pads; cameras = $cams }+} catch { [ordered]@{ present = $false; error = $_.Exception.Message } }+""", family="hardware", tier="T1", collect="deep", gate="hw.system", timeout_ms=15000,+ doc="Present peripherals by PnP class, USB vendor ids, controller and camera counts.")+++def _xml_local(path):+ import xml.etree.ElementTree as ET+ try:+ return ET.parse(path).getroot()+ except Exception:+ return None+++def _ln(el):+ return el.tag.rsplit("}", 1)[-1]+++@probe(id="hw.battery_report", level="L2", family="hardware", tier="T1", collect="deep", gate="hw.battery", timeout_ms=15000)+def hw_battery_report(h, facts):+ """powercfg /batteryreport (XML into scratch): design vs full capacity, cycle count, recent AC/DC usage."""+ out = os.path.join(h.scratch(), "battery.xml")+ h.run(["powercfg", "/batteryreport", "/xml", "/output", out], timeout_ms=15000, text=False)+ root = _xml_local(out)+ if root is None:+ return {"present": False}+ bat = next((e for e in root.iter() if _ln(e) == "Battery"), None)+ if bat is None:+ return {"present": False}+ kv = {_ln(c): (c.text or "").strip() for c in bat}+ design, full = int(kv.get("DesignCapacity") or 0), int(kv.get("FullChargeCapacity") or 0)+ usage = [e for e in root.iter() if _ln(e) == "UsageEntry"]+ ac = sum(1 for e in usage if e.get("Ac") == "1")+ try:+ os.remove(out)+ except OSError:+ pass+ return {"present": True, "design_mwh": design, "full_mwh": full, "health_pct": round(100 * full / design, 1) if design else None,+ "cycles": kv.get("CycleCount"), "chemistry": kv.get("Chemistry"), "recent_usage_entries": len(usage),+ "recent_ac": ac, "recent_dc": len(usage) - ac}+++@probe(id="hw.sleep_study", level="L2", family="hardware", tier="T1", collect="deep", gate="hw.battery", timeout_ms=20000)+def hw_sleep_study(h, facts):+ """powercfg /sleepstudy (XML into scratch): Modern Standby sessions, low-power share, drain."""+ out = os.path.join(h.scratch(), "sleepstudy.xml")+ h.run(["powercfg", "/sleepstudy", "/xml", "/output", out], timeout_ms=20000, text=False)+ root = _xml_local(out)+ if root is None:+ return {"present": False}+ inst = [e for e in root.iter() if _ln(e) == "ScenarioInstance"]+ types = collections.Counter(e.get("Type") or "?" for e in inst)+ lp = []+ for e in inst:+ d, l = int(e.get("Duration") or 0), int(e.get("LowPowerStateTime") or 0)+ if d:+ lp.append(100 * l / d)+ try:+ os.remove(out)+ except OSError:+ pass+ return {"present": bool(inst), "sessions": len(inst), "types": dict(types),+ "lowpower_pct_median": round(sorted(lp)[len(lp) // 2], 1) if lp else None,+ "lowpower_pct_min": round(min(lp), 1) if lp else None}+++# ================================================================= HEALTH++@probe(id="health.dumps", level="L1", family="health", tier="T1", collect="core")+def health_dumps(h, facts):+ """Crash dump config (CrashControl) and dump files: Minidump count/newest, MEMORY.DMP, LiveKernelReports."""+ P = _paths()+ cc = _reg_values(r"HKLM\SYSTEM\CurrentControlSet\Control\CrashControl", 100)+ mini, newest, mini30 = 0, None, 0+ try:+ with os.scandir(os.path.join(P["WIN"], "Minidump")) as it:+ for e in it:+ if mini >= 1000:+ break+ if e.is_file():+ mini += 1+ m = e.stat().st_mtime+ newest = m if newest is None or m > newest else newest+ mini30 += time.time() - m <= 30 * 86400+ except OSError:+ pass+ lkr = {}+ lroot = os.path.join(P["WIN"], "LiveKernelReports")+ for d in h.list_dir(lroot, 50):+ p = os.path.join(lroot, d)+ if os.path.isdir(p):+ n = sum(1 for f in h.list_dir(p, 500) if f.lower().endswith(".dmp"))+ if n:+ lkr[d] = n+ elif d.lower().endswith(".dmp"):+ lkr["root"] = lkr.get("root", 0) + 1+ md = h.meta(os.path.join(P["WIN"], "MEMORY.DMP"))+ if not cc and not mini and not lkr:+ return None+ return {"present": True, "crash_dump_enabled": cc.get("CrashDumpEnabled"), "auto_reboot": cc.get("AutoReboot"),+ "minidumps": mini, "count_30d": mini30, "minidump_newest": _iso(newest), "memory_dmp_bytes": md.get("bytes"),+ "live_kernel_reports": lkr}+++_WER_NOISE = re.compile(r"(?i)^(svchost\.exe|TrustedInstaller\.exe|TiWorker\.exe|MoUsoCoreWorker\.exe|WinStore\.App\.exe|"+ r"Microsoft\.WindowsStore.*|MicrosoftEdgeUpdate.*|MicrosoftEdge_X64_.*|setup\.exe|MsiExec\.exe|"+ r"wermgr\.exe|StoreDesktopExtension.*|backgroundTaskHost\.exe|RuntimeBroker\.exe|SearchHost\.exe|"+ r"MpSigStub\.exe|MsMpEng\.exe|WindowsPackageManagerServer\.exe)$")+++@probe(id="health.wer", level="L2", family="health", tier="T1", collect="extended", gate="health.dumps")+def health_wer(h, facts):+ """WER report dirs: crashes/hangs per app (Report.wer AppName), kernel reports; svchost/Store noise split out."""+ roots = [os.path.join(_paths()["PD"], "Microsoft", "Windows", "WER", r) for r in ("ReportArchive", "ReportQueue")]+ types = collections.Counter()+ apps = collections.Counter()+ last = {}+ kernel = collections.Counter()+ noise = total = 0+ oldest = newest = None+ for rt in roots:+ for n in h.list_dir(rt, 1000):+ p = os.path.join(rt, n)+ total += 1+ typ = n.split("_", 1)[0]+ types[typ] += 1+ m = _mtime(p)+ if m:+ oldest = m if oldest is None or m < oldest else oldest+ newest = m if newest is None or m > newest else newest+ app, evt = None, None+ try:+ with open(os.path.join(p, "Report.wer"), "rb") as f:+ txt = f.read(200_000).decode("utf-16", "replace")+ ma = re.search(r"^AppPath=([^\r\n]+)", txt, re.M) or re.search(r"^AppName=([^\r\n]+)", txt, re.M)+ me = re.search(r"^EventType=([^\r\n]+)", txt, re.M)+ app, evt = (_base(ma.group(1).strip()) if ma else None), (me.group(1).strip() if me else None)+ except OSError:+ pass+ if re.search(r"Kernel|BlueScreen", typ, re.I) or (evt and re.search(r"LiveKernel|BlueScreen", evt, re.I)):+ kernel[evt or typ] += 1+ continue+ if re.search(r"AppCrash|AppHang|BEX|Critical", typ, re.I):+ m2 = re.match(r"^[^_]+_([^_]+?\.exe)_", n, re.I)+ if m2:+ app = m2.group(1)+ app = app or "?"+ if _WER_NOISE.match(app):+ noise += 1+ continue+ apps[app] += 1+ last[app] = max(last.get(app) or 0, m or 0)+ if not total:+ return {"present": False}+ types = collections.Counter({k: v for k, v in types.items() if not re.fullmatch(r"[0-9a-fA-F-]{36}", k)})+ return {"present": True, "reports": total, "by_type": dict(types.most_common(8)), "system_noise_crashes": noise,+ "max_repeat": apps.most_common(1)[0][1] if apps else 0,+ "crashes_by_app": [[a, c, _iso(last.get(a))] for a, c in apps.most_common(12)], "kernel_reports": dict(kernel),+ "oldest": _iso(oldest), "newest": _iso(newest)}+++@probe(id="health.whea_gpu", level="L2", family="health", tier="T1", collect="extended", gate="hw.system", timeout_ms=20000)+def health_whea_gpu(h, facts):+ """Hardware error events: WHEA, nvlddmkm, display TDR 4101, bugcheck 1001 codes, storage warnings (wevtutil)."""+ provs = ("Microsoft-Windows-WHEA-Logger", "nvlddmkm", "Display", "Microsoft-Windows-WER-SystemErrorReporting",+ "disk", "Ntfs", "stornvme")+ xp = "*[System[Provider[" + " or ".join(f"@Name='{p}'" for p in provs) + "]]]"+ evs = _wevt(h, "System", xp, 3000, newest_first=True)+ if evs is None:+ return {"present": False, "error": "wevtutil failed"}+ grp = {k: {"count": 0, "by_id": collections.Counter(), "newest": None} for k in ("whea", "nvlddmkm", "tdr_4101", "storage_warn_err")}+ bug = []+ now = dt.datetime.now().astimezone()+ c30 = 0+ for ev in evs:+ try:+ prov, eid, t, data = _evt_fields(ev)+ lvl = int(ev.find(_EVT_NS + "System").find(_EVT_NS + "Level").text or 4)+ except (AttributeError, ValueError, TypeError):+ continue+ key = None+ if prov == "Microsoft-Windows-WHEA-Logger":+ key = "whea"+ elif prov == "nvlddmkm":+ key = "nvlddmkm"+ elif prov == "Display" and eid == 4101:+ key = "tdr_4101"+ elif prov in ("disk", "Ntfs", "stornvme") and 1 <= lvl <= 3:+ key = "storage_warn_err"+ elif prov == "Microsoft-Windows-WER-SystemErrorReporting" and eid == 1001:+ m = re.search(r"0x[0-9a-fA-F]+", " ".join(v or "" for v in data.values()))+ bug.append({"t": _iso(t), "code": m.group(0) if m else None})+ c30 += bool(t and (now - t).days < 30)+ continue+ if not key:+ continue+ g = grp[key]+ g["count"] += 1+ g["by_id"][str(eid)] += 1+ if t and (g["newest"] is None or _iso(t) > g["newest"]):+ g["newest"] = _iso(t)+ if key != "storage_warn_err" and t and (now - t).days < 30:+ c30 += 1+ for g in grp.values():+ g["by_id"] = dict(g["by_id"])+ return {"present": True, "count_30d": c30, **grp, "bugchecks": bug[:20]}+++ps_probe("health.reliability", r"""+try {+ $r = @(Get-CimInstance Win32_ReliabilityRecords -ErrorAction SilentlyContinue)+ $m = @(Get-CimInstance Win32_ReliabilityStabilityMetrics -ErrorAction SilentlyContinue | Sort-Object TimeGenerated)+ $s = @($r | Sort-Object TimeGenerated)+ function T($grp) { $o = [ordered]@{}; foreach ($x in @($grp | Sort-Object Count -Descending | Select-Object -First 8)) { $o[[string]$x.Name] = $x.Count }; $o }+ [ordered]@{ present = ($r.Count -gt 0); records = $r.Count+ oldest = $(if ($s) { $s[0].TimeGenerated.ToString('s') }); newest = $(if ($s) { $s[-1].TimeGenerated.ToString('s') })+ by_source = (T ($r | Group-Object SourceName)); top_products = (T ($r | Where-Object ProductName | Group-Object ProductName))+ stability_latest = $(if ($m) { [math]::Round($m[-1].SystemStabilityIndex, 2) })+ stability_min = $(if ($m) { [math]::Round(($m | Measure-Object SystemStabilityIndex -Minimum).Minimum, 2) }) }+} catch { [ordered]@{ present = $false; error = $_.Exception.Message } }+""", family="health", tier="T1", collect="deep", gate="hw.system", timeout_ms=20000,+ doc="Reliability Monitor records by source/product and the stability index (latest, min).")diff --git a/optional-skills/security/unbroker/scripts/crypto.py b/optional-skills/security/unbroker/scripts/crypto.pyindex 98594f5e840..c205ac3ff54 100644--- a/optional-skills/security/unbroker/scripts/crypto.py+++ b/optional-skills/security/unbroker/scripts/crypto.py@@ -53,7 +53,7 @@ def ensure_identity() -> Path:p.parent.chmod(0o700)except OSError:pass- subprocess.run(["age-keygen", "-o", str(p)], check=True, capture_output=True)+ subprocess.run(["age-keygen", "-o", str(p)], check=True, capture_output=True, stdin=subprocess.DEVNULL)try:p.chmod(0o600)except OSError:diff --git a/optional-skills/software-development/ast-grep/scripts/ast_grep_helper.py b/optional-skills/software-development/ast-grep/scripts/ast_grep_helper.pyindex 053c0501582..c4c707fe5d8 100755--- a/optional-skills/software-development/ast-grep/scripts/ast_grep_helper.py+++ b/optional-skills/software-development/ast-grep/scripts/ast_grep_helper.py@@ -605,7 +605,7 @@ def cmd_install(_args: argparse.Namespace) -> int:err(f"installer not found: {installer}")return 1trace(f"running installer: {' '.join(cmd)}")- return subprocess.run(cmd).returncode+ return subprocess.run(cmd, stdin=subprocess.DEVNULL).returncodedef cmd_validate(args: argparse.Namespace) -> int:diff --git a/scripts/check_subprocess_stdin.py b/scripts/check_subprocess_stdin.pyindex e471b7c5ba6..c5a6beac39e 100644--- a/scripts/check_subprocess_stdin.py+++ b/scripts/check_subprocess_stdin.py@@ -7,7 +7,7 @@ inherit this fd can cause the gateway to exit with stdin EOF during toolexecution (issue #14036, PR #39257).This script checks that all subprocess.run() and subprocess.Popen() calls-in TUI-context files (agent/, tools/, plugins/, tui_gateway/) explicitly+in TUI-context files (agent/, tools/, plugins/, tui_gateway/, optional-skills/) explicitlyset stdin= to prevent fd inheritance.Exit codes:@@ -36,6 +36,10 @@ TUI_CONTEXT_DIRS = ["tools/","plugins/","tui_gateway/",+ # The backend loads some optional-skill scripts in-process: the /initiate-setup+ # builder runs initiate-setup's host_facts.py and its userscan package on a+ # backend thread, so their children would inherit the JSON-RPC stdin too.+ "optional-skills/",]# User plugin roots — scanned at runtime if they exist. Plugins load from@@ -73,16 +77,9 @@ KNOWN_SAFE = {# file:line entry).EXEMPT_MARKER = "noqa: subprocess-stdin"-# Directories to skip entirely.-SKIP_DIRS = {- "tests/",- "scripts/",- "skills/",- "optional-skills/",- "hermes_cli/",- "gateway/",- "cron/",-}+# Directory names skipped at any depth below a context dir. Matching against the+# path relative to that dir keeps a skill's own ``scripts/`` folder in scope.+SKIP_DIRS = {"tests"}_SPLAT_RE = re.compile(r"\*\*\s*([A-Za-z_][A-Za-z0-9_]*)")@@ -228,8 +225,7 @@ def main() -> int:continue# Skip test files inside tools/ etc.- parts = py_file.parts- if any(skip.rstrip("/") in parts for skip in SKIP_DIRS):+ if SKIP_DIRS & set(py_file.relative_to(dirpath).parts):continuecontent = py_file.read_text(encoding="utf-8-sig")diff --git a/tui_gateway/methods_onboarding.py b/tui_gateway/methods_onboarding.pyindex 1c0eac0c78b..d93bd06697c 100644--- a/tui_gateway/methods_onboarding.py+++ b/tui_gateway/methods_onboarding.py@@ -1,16 +1,23 @@+import threading+from .method_ctx import HandlerRegistry, bind_module_registry = HandlerRegistry()method = _registry.method+# These handlers run on the RPC pool. Two overlapping kickoffs must not both find no setup+# profile and create a second one, or both find an empty setup chat and seed it twice.+_setup_profile_lock = threading.Lock()+@method("onboarding.ensure_setup_profile")def _(rid, params: dict) -> dict:from hermes_cli.setup_profile import ensure_setup_profiletry:- setup = ensure_setup_profile()- if setup.created:- _mirror_launch_credentials(setup.path, {"share_auth": True})+ with _setup_profile_lock:+ setup = ensure_setup_profile()+ if setup.created:+ _mirror_launch_credentials(setup.path, {"share_auth": True})except Exception as e:return _err(rid, 5073, str(e))_start_setup_scan(setup.path)@@ -22,19 +29,20 @@ def _(rid, params: dict) -> dict:from hermes_cli.setup_profile import SETUP_CHAT_TITLE, ensure_setup_profilefrom hermes_state_registry import acquire, release_or_closetry:- setup = ensure_setup_profile()- if setup.created:- _mirror_launch_credentials(setup.path, {"share_auth": True})- db = acquire(setup.path / "state.db")- try:- row = db.get_session_by_title(SETUP_CHAT_TITLE)- if row is None:- row = {"id": db.create_session(new_session_id(), "desktop"), "message_count": 0}- db.set_session_title(row["id"], SETUP_CHAT_TITLE)- if not row["message_count"]:- row["message_count"] = db.append_messages_batch(row["id"], _coerce_seed_history(params.get("messages")))- finally:- release_or_close(db)+ with _setup_profile_lock:+ setup = ensure_setup_profile()+ if setup.created:+ _mirror_launch_credentials(setup.path, {"share_auth": True})+ db = acquire(setup.path / "state.db")+ try:+ row = db.get_session_by_title(SETUP_CHAT_TITLE)+ if row is None:+ row = {"id": db.create_session(new_session_id(), "desktop"), "message_count": 0}+ db.set_session_title(row["id"], SETUP_CHAT_TITLE)+ if not row["message_count"]:+ row["message_count"] = db.append_messages_batch(row["id"], _coerce_seed_history(params.get("messages")))+ finally:+ release_or_close(db)except Exception as e:return _err(rid, 5075, str(e))_start_setup_scan(setup.path)@@ -55,21 +63,22 @@ def _(rid, params: dict) -> dict:@method("onboarding.mark_seen")def _(rid, params: dict) -> dict:- from hermes_cli.setup_profile import mark_seen- return _onboarding_state_result(rid, mark_seen)+ from hermes_cli.setup_profile import mark_intro_seen+ return _onboarding_state_result(rid, mark_intro_seen)@method("onboarding.reset_setup_profile")def _(rid, params: dict) -> dict:from hermes_cli.setup_profile import find_setup_profile, reset_setup_profile- found = find_setup_profile()- if found is None:- return _err(rid, 4072, "no setup profile to reset")- _clear_setup_sessions(found[1])- try:- setup = reset_setup_profile()- except Exception as e:- return _err(rid, 5074, str(e))+ with _setup_profile_lock:+ found = find_setup_profile()+ if found is None:+ return _err(rid, 4072, "no setup profile to reset")+ _clear_setup_sessions(found[1])+ try:+ setup = reset_setup_profile()+ except Exception as e:+ return _err(rid, 5074, str(e))return _ok(rid, {"name": setup.name, "path": str(setup.path), "reset": True})diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 5554c19b019..94ce83882a1 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -164,7 +164,9 @@ _DETAIL_MODES = frozenset({"hidden", "collapsed", "expanded"})# open; bot_relay.* = a FULL one-turn agent conversation (600s); setup.* / session.active_list =# Desktop-polled and under GIL pressure block the WS read loop (false "needs setup", stalled# interrupts); voice.*/wake.* = SYNCHRONOUS faster-whisper install (300s); session.workspace.move =-# git subprocess probes on an arbitrary (maybe slow) mount.+# git subprocess probes on an arbitrary (maybe slow) mount; onboarding.* setup profile = create_profile+# skill copy + state.db writes + the first import of the setup scanner; session.start_chat = session+# creation + a prompt.submit._LONG_HANDLERS = frozenset({"session.foreign.list", "session.foreign.preview", "session.foreign.import","billing.state", "subscription.state", "subscription.preview", "subscription.change",@@ -179,6 +181,8 @@ _LONG_HANDLERS = frozenset({"setup.runtime_check", "setup.status", "free_tier.provision", "voice.toggle", "voice.record", "voice.tts", "wake.start","wake.status", "session.active_list", "session.branch", "session.compress", "session.list","session.resume", "session.workspace.move", "shell.exec", "skills.manage", "slash.exec",+ "onboarding.ensure_setup_profile", "onboarding.ensure_setup_session", "onboarding.reset_setup_profile",+ "session.start_chat","command.dispatch", # /goal draft invokes the auxiliary model; never block the RPC reader"shared_metrics.set", # consent reconcile waits on the metrics store's write lock})diff --git a/website/docs/reference/slash-commands.md b/website/docs/reference/slash-commands.mdindex 87fc55e36b9..0ca613855b5 100644--- a/website/docs/reference/slash-commands.md+++ b/website/docs/reference/slash-commands.md@@ -110,7 +110,7 @@ Type `/` in the CLI to open the autocomplete menu. Built-in commands are case-in| `/bundles` | List configured skill bundles — `/<name>` slash aliases that preload several skills at once. Configure under `bundles:` in `~/.hermes/config.yaml`. See [Skill Bundles](../user-guide/features/skills.md#skill-bundles). || `/learn <what to learn from>` | Distill a reusable skill from anything you describe — a directory, a URL, the workflow you just walked the agent through, or pasted notes. Open-ended: the agent gathers the sources with its own tools and authors a `SKILL.md` following the house authoring standards. Works in the CLI, the messaging gateway, the TUI, and the dashboard Skills page. || `/plan [task]` | Write a markdown implementation plan to `.hermes/plans/` in the active workspace — planning only, no execution. Empty argument infers the task from the conversation. (Formerly the bundled `plan` skill; now built-in so it survives the Telegram/Discord command-menu caps.) |-| `/initiate-setup` (alias: `/initiate_setup`) | Run the first-run setup: the agent learns about you and sets Hermes up around you. Sends the `initiate-setup` skill plus facts about this session and machine (surface, tools present, OS, RAM, GPU) as one normal turn. The first message ever ends with a one-line offer to run it (see [Onboarding](../user-guide/configuration.md#onboarding)). Works in the CLI, the messaging gateway, the TUI, and the desktop app. |+| `/initiate-setup` (alias: `/initiate_setup`) | Run the first-run setup: the agent learns about you and sets Hermes up around you. Sends the `initiate-setup` skill plus facts about this session and machine (surface, tools present, OS, RAM, GPU), plus a derived summary of an automatic machine scan (see [The setup chat's machine scan](../user-guide/desktop.md#the-setup-chats-machine-scan)), as one normal turn. The first message ever ends with a one-line offer to run it (see [Onboarding](../user-guide/configuration.md#onboarding)). Works in the CLI, the messaging gateway, the TUI, and the desktop app. || `/init [notes]` | Generate or update `AGENTS.md` project instructions from a repo scan (port of Codex `/init`). The agent inspects manifests, layout, and toolchain configs with its read-only tools, then writes a concise `AGENTS.md` — or, if one exists, merge-updates it preserving your content. Optional notes steer the emphasis. Works in the CLI, the messaging gateway, and the TUI. || `/cron` | Manage scheduled tasks (list, add/create, edit, pause, resume, run, remove) || `/suggestions [accept\|dismiss N\|catalog\|clear]` (alias: `/suggest`) | Review suggested automations. Use `/suggestions` to list pending suggestions, `/suggestions accept <id>` to create the proposed automation, `/suggestions dismiss <id>` to reject one, `/suggestions catalog` to add curated starter automations, and `/suggestions clear` to clear resolved suggestion records. Accepted jobs preserve the current surface as the delivery origin. |diff --git a/website/docs/reference/tools-reference.md b/website/docs/reference/tools-reference.mdindex 4c0140762eb..2aa0fc0dd42 100644--- a/website/docs/reference/tools-reference.md+++ b/website/docs/reference/tools-reference.md@@ -241,12 +241,14 @@ messaging, and cron sessions.| `read_window_below` | Identify the OS window directly underneath the Hermes desktop window — app name, title, bounds (metadata only, never pixels). On macOS, other apps' titles appear only when Screen Recording is already granted; the tool never prompts for it. | — || `focus_pane` | Reveal and focus a pane in the Hermes desktop app (chat, files, terminal, review, sessions). | — || `react_to_message` | React to a message with a single emoji, iMessage-tapback style. Opt-in via Settings → Appearance (`display.message_reactions`). | — |-| `gui_tour` | Give a live guided tour: dim the screen, highlight an element, and attach a narrated popover (driver.js). Works on the Hermes app's own UI and on any page open in the preview pane; `targets` discovers what's on screen, `show` narrates step-by-step, `start` hands the user Next/Prev controls. | — |+| `gui_tour` | Give a live guided tour: dim the screen, highlight an element, and attach a narrated popover (driver.js). Works on the Hermes app's own UI and on any page open in the preview pane; `targets` discovers what's on screen, `show` narrates step-by-step, `start` with `steps` hands the user Next/Prev controls, and `start` with no `steps` runs the app's own built-in tour (`preset`: `quick` or `full`, default `full`; app surface only). | — || `show_tip` | Point at one element with a small accent bubble and an arrow — the quiet sibling of `gui_tour`, with no dimming, no spotlight, and no Next/Prev. Same `data-tour` handles and the same `tour(action='targets')` discovery call. | — || `apply_layout` | Apply a saved layout preset to the Hermes desktop app when the user asks to rearrange the workspace. Built-ins: default (chat + sidebars), focus (chat only), terminal-deck, quad; plugin/user presets by id. To reveal ONE pane, use `focus_pane` instead. | — |### Tours+For the app's own walkthrough, call `start` without `steps`: `preset='quick'` runs the short built-in tour and `preset='full'` (the default) the longer one. Everything below is for a custom tour.+The `gui_tour` tool discovers its own targets — call `action='targets'` and it returns every addressable element on screen with a selector, a label, and a `stable` flag. Stable selectors key off identity (`data-tour`, `id`, `data-testid`, `aria-label`) and survive a re-render; positional `nth-child` paths don't, so stable ones sort first and should be preferred.To give an element a durable handle of your own, mark it up:diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 513e5cd79cb..a7ddf91df46 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -3057,7 +3057,7 @@ onboarding:seen: {} # internal latch — leave empty```-- `profile_build` — controls the setup offer on the first message ever, in the CLI, the TUI, the desktop app and messaging direct messages (never in a group chat). `"ask"` (default) adds one closing line to the agent's intro that offers `/initiate-setup` (`/initiate_setup` on Telegram). The offer is skipped when the first message is `/initiate-setup` itself. `"off"` stops only the offer line; the agent still gives a plain intro. The offer fires at most once per profile.+- `profile_build` — controls the setup offer on the first message ever, in the CLI, the TUI, the desktop app and messaging direct messages (never in a group chat). `"ask"` (default) adds one closing line to the agent's intro that offers `/initiate-setup` (`/initiate_setup` on Telegram). The offer is skipped when the first message is `/initiate-setup` itself. `"off"` stops only the offer line; the agent still gives a plain intro. The offer fires at most once per profile. `/initiate-setup` also scans the machine automatically; see [The setup chat's machine scan](./desktop.md#the-setup-chats-machine-scan).- `seen` — internal state. Hermes latches each shown hint here so it never fires again; the setup offer is also recorded here once shown. Don't hand-edit it — wipe the whole `onboarding` section if you want to re-see all hints.## Dashboarddiff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.mdindex 66d03f7659e..6d94d38902c 100644--- a/website/docs/user-guide/desktop.md+++ b/website/docs/user-guide/desktop.md@@ -256,6 +256,16 @@ Manage providers, models, tools, and credentials from a real UI instead of editiFirst-run onboarding has been redesigned on a unified overlay design system, and you can pick **Choose provider later** to skip provider setup and get into the app first.+#### The setup chat's machine scan++The setup chat tailors its questions to your computer, so Hermes scans the machine once, automatically. There is no separate consent step.++- **When it runs.** When the desktop app creates or opens the setup profile on first run, while the welcome plays. `/initiate-setup` runs it too and reuses a recent result.+- **Where it runs.** On the machine that runs Hermes, inside the Hermes process: the desktop backend, the CLI or the messaging gateway. With a remote backend, it scans the remote machine, not the computer in front of you.+- **What it reads.** Your own account only. It reads hardware and OS basics; your full name, language and home-folder age from the account record; installed apps and signs of which ones you use; developer tools and AI agents (installed, and how many sessions); and your browser history, recent-file lists and usage records. From the history and activity records it keeps only counts and categories, for example visit counts, a coarse category mix of visited sites and download counts. Search terms, visited site names, repository names and file names are dropped before the result is stored. The one exception is the search engines you use: the names of up to three (for example `google.com`), with visit counts, are kept. Cookies, saved passwords and credential files are checked for presence only and never opened.+- **What reaches the model.** A short block of derived facts, not the raw scan. It holds the machine basics, your suggested name and language, whether the machine looks new, a rough experience level, which common apps you seem to use, the AI agents you run with session counts, your primary browser and similar summaries. The block rides in the first message of the setup chat, so it goes to the inference provider that the setup chat uses and stays in that chat's history. The scan sends nothing anywhere else.+- **Where the cache lives.** `insights/profile.json` in the setup profile's home, readable only by your account (mode `0600`). Hermes reuses it for up to 24 hours, unless a quick presence re-check finds apps or tools added or removed. Delete the file to discard it.+#### Per-profile settings: the "Applies to" scopeWhen you have two or more [profiles](./profiles.md), the config-backed settings pages — **Model, Workspace, Safety, Memory & Context, Voice, Chat, Advanced, and Tools & Keys** — plus **Providers → Custom Endpoints** and the **Messaging** overlay show a shared **Applies to** chip row at the top. It selects which profile your edits target: