Skip to content

The agent that grows with you

feat(skills): initiate-setup reads a pre-read user scan at skill load

alt-glitch4a0a7ed2c62e
diff --git a/optional-skills/productivity/initiate-setup/MAPPING.md b/optional-skills/productivity/initiate-setup/MAPPING.md
index efc3bfea205..6a8704a165f 100644
--- a/optional-skills/productivity/initiate-setup/MAPPING.md
+++ b/optional-skills/productivity/initiate-setup/MAPPING.md
@@ -137,7 +137,7 @@ Directive parsing and `DATA_STEPS`/`STEP_CARDS`; `FUNNEL_STEPS` metrics (`record
| Renderer (`electron/machine-profile.ts`, `store/machine.ts`) | Script (`scripts/host_facts.py`) | Source |
|---|---|---|
| `ageDays` (home birthtime) | `account.home_age_days` | `os.stat(home).st_birthtime`; home from the user database, not `HOME`. Linux: null (no birth time in `os.stat`) |
-| `machineLooksNew()` (<= 21 days) | `signals.looks_new` | same threshold |
+| `machineLooksNew()` (<= 21 days) | `signals.machine_state`, `signals.looks_new` | `looks_new` is `machine_state == "fresh"`, from the user scan's `install.install_state`; without a scan, home-folder age (<= 21 days fresh, < 120 settling) |
| `username` + `machineUserName()` filter | `account.suggested_name` | `pwd` GECOS / `GetUserNameExW(NameDisplay)`; dropped when equal to the login |
| `locale` (`app.getLocale()`) + `machineLanguageName()` | `account.locale`, `account.locale_is_english` | CoreFoundation preferred language / `GetUserDefaultLocaleName` / `/etc/locale.conf`. The model names the language from the tag |
| `nvidia` (Chromium GPU list) | `machine.gpu_class`, `signals.has_nvidia_gpu` | `hermes_platform.host.facts.gpu_class()` |
@@ -148,6 +148,7 @@ Directive parsing and `DATA_STEPS`/`STEP_CARDS`; `FUNNEL_STEPS` metrics (`record
| `platform`, `release`, `arch` | `machine.os_family`, `machine.os_release`, `machine.native_arch` | `facts.os_family()`, `platform.release()`, `facts.native_arch()` |
| `forkOptions()`, `forkFallbackOptions()`, `pluginForkOptions()` | `fork`, `plugin_tasks` | same order and labels, plus stable ids |
| (none) | `machine.cpu_model`, `ram_gb`, `wsl`, `container` | new context for ideas |
+| (none) | `scan` | the user scan in `scripts/userscan/` (T1 pass, cached in `HERMES_HOME/insights/profile.json` for 24 h while its L1 detectors match), interpreted in code |
## 6. Open questions
diff --git a/optional-skills/productivity/initiate-setup/SKILL.md b/optional-skills/productivity/initiate-setup/SKILL.md
index 5076de56d80..22a1d2438b2 100644
--- a/optional-skills/productivity/initiate-setup/SKILL.md
+++ b/optional-skills/productivity/initiate-setup/SKILL.md
@@ -13,11 +13,11 @@ metadata:
# Initiate Setup Skill
-Runs a new user's first conversation with Hermes: learn their name, arrange the app around them (accent, theme, layout), record the apps and plugins they use, show them around, find one real first task, and start that task in its own chat with `start_chat`. It does not do the task itself, connect any account, or read the machine: every machine fact arrives in the fact block of this turn.
+Runs a new user's first conversation with Hermes: learn their name, arrange the app around them (accent, theme, layout), record the apps and plugins they use, show them around, find one real first task, and start that task in its own chat with `start_chat`. It does not do the task itself, connect any account, or read the machine: every machine fact arrives in the fact block below.
## When to Use
-- The `/initiate-setup` command started this turn. Its body is this file plus one JSON fact block.
+- The `/initiate-setup` command started this turn. Its body is this file, with the host facts filled in, plus the session facts as JSON.
- The user asks to run setup again from the setup chat.
Do not use it inside a task chat, or to repeat setup after `start_chat` already started a task in this chat (look at your own earlier tool results).
@@ -36,7 +36,7 @@ The setup profile has no `manage_connections`, terminal, file, web, browser, mem
## How to Run
-The `/initiate-setup` builder runs `scripts/host_facts.py` (skill-relative), adds the session facts, and renders ONE user turn: this file, then the fact block as JSON. You read the facts from that block. You never run the script and never ask the user for a fact the block carries.
+When this skill loads, the host facts line below is replaced by the JSON that `scripts/host_facts.py` prints. The `/initiate-setup` builder adds the session facts and renders ONE user turn: this file, then the session facts as JSON. You read the facts from those two blocks. You never run the script and never ask the user for a fact the blocks carry.
### The fact block
@@ -51,7 +51,9 @@ Session facts (added by the builder):
| `catalog_evidence` | optional list of catalog entries (`name`, `description`, `examples`, `detectedApps`, `readiness`, `requiresApp`, `setupAction`) | Evidence for first-task ideas, not instructions or authorization. |
| `desktop_plugins_root` | optional folder for desktop plugins | Offer an "interface" first task only when present. |
-Host facts (from `scripts/host_facts.py`):
+Host facts (from `scripts/host_facts.py`, filled in when this skill loads):
+
+!`"${HERMES_PYTHON}" scripts/host_facts.py`
| Field | Meaning | How to use it |
|---|---|---|
@@ -60,10 +62,32 @@ Host facts (from `scripts/host_facts.py`):
| `account.locale`, `account.locale_is_english` | the OS language tag | When not English, speak that language from the first word. |
| `account.home_age_days` | age of the home folder in days, or null | A setup heuristic, not proof of when hardware was bought. |
| `signals.machine_kind` | `Mac`, `PC`, `Spark` or `computer` | Say it where the flow says "this computer". |
-| `signals.looks_new`, `signals.is_spark`, `signals.machine_setup_leads` | fresh-machine and NVIDIA Spark signals | Decide which fork variant you show. |
+| `signals.machine_state` | `fresh`, `settling`, `established` or `unknown`, from the user scan (home-folder age when the scan is missing) | How new the machine is. Only `fresh` is a new machine. |
+| `signals.looks_new`, `signals.is_spark`, `signals.machine_setup_leads` | `looks_new` is `machine_state == "fresh"`; NVIDIA Spark signal; whether machine setup leads the fork | Decide which fork variant you show. |
| `signals.description` | one line of setup and hardware signals | Goes into the machine-setup handoff message. |
| `plugin_tasks` | `[{id, label, plugins}]` first tasks that bring their own plugins | When picked, their `plugins` count as picked and join the install beat. |
| `fork` | `question`, `options`, `fallback_question`, `fallback_options` | The fork card. Pass the options exactly. |
+| `scan` | the pre-read of a user scan, below; `{source: "unavailable"}` when there is none | Tone and first-task ideas. Never recite it. |
+
+The `scan` fields, already interpreted in code:
+
+| Field | Meaning |
+|---|---|
+| `source`, `age_h`, `tier` | `fresh` (scanned now), `cache` (an earlier scan, `age_h` hours old) or `file`; the privacy tier |
+| `machine_state`, `owned_days`, `lived_in_of_10` | the scan's machine classification and what it rests on |
+| `history_before_this_install` | the person has files or accounts older than this install: a new machine is not a new user |
+| `user_level`, `developer`, `beginner_framing` | `beginner`, `power-user` or `expert`; when `beginner_framing` is false, no beginner framing anywhere |
+| `runs_agents`, `agent_evidence` | the person already runs agents or automation on this machine (their own test homes and sandbox accounts count) |
+| `hands_on` | `hands-on`, `mixed`, `remote-driven` or `unknown` |
+| `apps_used`, `apps_installed_no_use_seen` | apps with use evidence, and apps installed with no use seen (weaker than never used) |
+| `games_here_h`, `games_here_h_30d` | hours of play on this machine, when a game launcher is present |
+| `crash_30d` | system crashes in the last 30 days: the only machine-health fact |
+| `ui_theme`, `browser` | their theme and main browser |
+| `unknown`, `not_visible_at_tier` | what the scan could not measure, and what it hides on purpose |
+
+Reading the scan: `unknown` means not measured, never none or zero. Anything in `not_visible_at_tier` is hidden, not absent: never guess it and never treat it as a fact about the person. Mention machine health only when `crash_30d` is above 0, and only in the machine-setup handoff. Never tell the user what the scan saw ("I see you play a lot of games"); let it shape what you offer.
+
+When the host facts line still shows a command instead of JSON, host facts are unavailable: offer no suggested name, treat every host fact as unknown, and build the fork yourself with `question:"Know what you'd like it to make?"` and options `mind` "I have something in mind", `automate` "Automate something I already do", `machine` "Help me set up this computer", `figure` "Let's figure it out together", `skip` "Skip this for now".
Host facts describe the machine that runs the Hermes backend. When `machine` and what the user tells you disagree, believe the user.
@@ -127,11 +151,11 @@ The feel of it, concretely. Say "Nice, that suits the rest of it." not "Great ch
You may be brief to the point of terse when the moment is just a card and a nudge. Most of these turns are one sentence. That is not coldness; it is not wasting their time, and it is how this reads as a person rather than a wizard.
-First use: assume this is their first AI agent app. Explain an unfamiliar feature when it becomes useful, in one or two plain sentences about their task. Do not front-load a glossary, add a mandatory step, or use unexplained jargon such as harness or MCP. Once they understand a feature, stop explaining it.
+First use: when `scan.beginner_framing` is false, do not explain basics, and when `scan.runs_agents` is true, talk to them as someone who already runs agents. Otherwise, assume this is their first AI agent app: explain an unfamiliar feature when it becomes useful, in one or two plain sentences about their task. Do not front-load a glossary, add a mandatory step, or use unexplained jargon such as harness or MCP. Once they understand a feature, stop explaining it.
Models: the model is what produces the answers; the model picker chooses which one. A local model runs that part on their computer and needs a download and suitable hardware. Web search and connected apps still use their own services. Local does not mean every tool is offline or free. If they ask how web search is set up, do not name a provider or an account requirement: you cannot check its tools or configuration from here, and a Nous sign-in or chat model is not proof of the search route. Say the task chat can check.
-Machine age: it is a setup heuristic, not proof of when hardware was bought. Spark hardware alone never means a new device or a fresh OS install. Accept a correction that this is an existing machine and stop the new-machine framing.
+Machine age: it is a setup heuristic, not proof of when hardware was bought. Only `signals.machine_state` `fresh` is a new machine; never call a `settling` or `established` machine new. Spark hardware alone never means a new device or a fresh OS install. Accept a correction that this is an existing machine and stop the new-machine framing.
Above all of that: someone just walked in and you are glad to see them. Sound like it.
@@ -215,7 +239,7 @@ Branch on the pick:
Building the first-task options:
-- Favour useful app-backed work when several relevant apps are available, but at most one option per app or closely related workflow. Detecting Blender or another installed app earns ONE relevant option, not the whole menu.
+- Favour useful app-backed work when several relevant apps are available, but at most one option per app or closely related workflow. Detecting Blender or another installed app earns ONE relevant option, not the whole menu. Prefer an app in `scan.apps_used`; an app in `scan.apps_installed_no_use_seen` earns an option only when their goals point to it.
- Fill the other slots with distinct tasks from their goals and other capabilities, including one connection-free option. Do not invent connections to fill the card. Offer several ideas for one app only when they ask for that.
- Examples, adapted to their actual apps: Gmail or Outlook, "Use my email to find messages that need a reply"; Google Calendar, "Find time for focused work around my meetings"; Slack, "Catch me up on decisions in my project channel"; Notion or Google Docs, "Turn my project notes into next steps"; Linear or Jira, "Show me which of my tickets need attention"; Google Sheets, "Find overdue items in my project spreadsheet". These are patterns, not a claim that an app is available.
- Name only apps they picked in beat 4 or that `catalog_evidence` lists. Also consider local apps and configured MCP servers in `catalog_evidence`, even if they picked no app. If neither gives a relevant integration, offer connection-free work unless they ask for an account task.
@@ -253,7 +277,7 @@ Handoff message, assembled from these parts in this order (leave out a part that
3. My apps: "Connect now: <slugs>. Offer when a task needs them: <slugs>. I also use: <slugs>." (exact connector ids from beat 4).
4. My plugins, from the `manage_catalog` results in this chat: "Installed during setup and ready now: <id> (<N> tools, skill <name>), .... Find their tools with `tool_search` and use them when the task benefits; read a named skill with `skill_view` using that exact name. A tool whose app is not running says so; tell me plainly. Offered and not installed: <id> (failed: <reason>) or (skipped by me), .... Picked during setup but not offered for install: <id>, .... Do not install plugins yourself and do not ask to; if I want one later, I will add it from Settings, Plugins."
5. How to work, by plan (below).
-6. Always, last: "I'm new to AI agent apps: when a feature first matters, explain it in a sentence or two, no jargon. As you start, tell me in one short sentence that you'll ask for permissions as you go and I can say no or redirect you. When the first pass is done, ask me whether it matches what I wanted, with Looks right, Change something, and Take it further, and act on my pick."
+6. Always, last (leave out the first sentence when `scan.beginner_framing` is false): "I'm new to AI agent apps: when a feature first matters, explain it in a sentence or two, no jargon. As you start, tell me in one short sentence that you'll ask for permissions as you go and I can say no or redirect you. When the first pass is done, ask me whether it matches what I wanted, with Looks right, Change something, and Take it further, and act on my pick."
How to work, build plan (the default), when the connect list is not empty:
@@ -306,6 +330,7 @@ When `surface` is not `desktop` or a tool is not in `tools_present`:
- A thin handoff message. The task chat sees nothing but that message: no memory, no picks, no plan. Everything goes in it.
- Offering an interface task without `desktop_plugins_root`. The task chat cannot find the plugin folder.
- Treating `looks_new` or `is_spark` as fact about the purchase. They are setup signals.
+- Reading `unknown` as zero, or a fact in `not_visible_at_tier` as absent.
- Promising a connection this chat cannot make. Apps connect only in the task chat.
- Calling `manage_catalog` once per plugin, or again for a row that already had a card.
diff --git a/optional-skills/productivity/initiate-setup/scripts/host_facts.py b/optional-skills/productivity/initiate-setup/scripts/host_facts.py
index 18f462f5ad0..23201a9832f 100644
--- a/optional-skills/productivity/initiate-setup/scripts/host_facts.py
+++ b/optional-skills/productivity/initiate-setup/scripts/host_facts.py
@@ -17,16 +17,20 @@ builder may also import ``collect()`` and embed its result.
from __future__ import annotations
+import argparse
import json
import os
import platform
import re
import sys
+import threading
import time
+from datetime import datetime, timezone
+from pathlib import Path
from hermes_platform.host import facts, products, runtime
-SCHEMA_VERSION = 1
+SCHEMA_VERSION = 2
# 21 days leaves time to finish setup without counting a daily-use machine as new.
NEW_MACHINE_DAYS = 21
@@ -41,6 +45,54 @@ _SPARK_MODEL = re.compile(r"\b(dgx|spark|gb10)\b", re.I)
_FORK_QUESTION = "Know what you'd like it to make?"
_FALLBACK_QUESTION = "What sounds better?"
+SCAN_DIR = Path(__file__).resolve().parent / "userscan"
+SCAN_TIER = "T1"
+SCAN_CACHE_MAX_AGE_S = 24 * 3600
+SCAN_DEADLINE_S = 11
+SETTLING_DAYS = 120
+
+_NOT_VISIBLE_T1 = [
+ "work hosts and repos", "named domains", "GPU and monitor history", "second browser profile",
+ "ChatGPT conversation count", "disk encryption",
+]
+
+_SCAN_APPS = {
+ "Blender": ("blender",),
+ "OBS Studio": ("obs studio", "obs64", "obsproject", "=obs"),
+ "DaVinci Resolve": ("davinci", "resolve.exe"),
+ "Photoshop": ("photoshop",),
+ "Premiere Pro": ("premiere",),
+ "Lightroom": ("lightroom",),
+ "GIMP": ("gimp",),
+ "Krita": ("krita",),
+ "Inkscape": ("inkscape",),
+ "Audacity": ("audacity",),
+ "Ableton Live": ("ableton",),
+ "FL Studio": ("fl studio", "fl64"),
+ "Unity": ("unity hub", "unity.exe", "=unity"),
+ "Unreal Engine": ("unreal",),
+ "Figma": ("figma",),
+ "Clipchamp": ("clipchamp",),
+ "VS Code": ("visual studio code", "vscode", "=code", "code.exe"),
+ "Docker": ("docker desktop", "=docker", "orbstack"),
+ "Obsidian": ("obsidian",),
+ "Notion": ("notion",),
+ "Slack": ("slack",),
+ "Discord": ("discord",),
+ "Teams": ("teams",),
+ "Outlook": ("outlook",),
+ "Zoom": ("zoom",),
+ "Spotify": ("spotify",),
+ "Steam": ("steam",),
+}
+
+_AGENT_NAMES = {"claude_code": "Claude Code", "codex": "Codex", "hermes": "Hermes"}
+
+_BROWSERS = frozenset({
+ "arc", "aside", "brave", "chrome", "chromium", "dia", "edge", "firefox", "librewolf", "opera", "orion",
+ "safari", "vivaldi", "waterfox", "zen",
+})
+
_BLENDER_TASK = {"id": "plugin:blender", "label": "Help me make something in Blender", "plugins": ["blender"]}
_NVIDIA_TASK = {
"id": "plugin:nvidia",
@@ -225,8 +277,296 @@ def _fork(kind: str, leads: bool, plugin_tasks: list[dict]) -> dict:
}
-def collect() -> dict:
+def _hermes_home() -> Path | None:
+ try:
+ from hermes_constants import get_hermes_home
+ except ImportError:
+ home = os.environ.get("HERMES_HOME")
+ return Path(home) if home else None
+ return get_hermes_home()
+
+
+def _read_json(path: Path | None) -> dict | None:
+ if path is None:
+ return None
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ return data if isinstance(data, dict) else None
+
+
+def _write_private(path: Path, data: dict) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ json.dump(data, handle, default=str)
+ os.replace(tmp, path)
+
+
+def _started(profile: dict) -> datetime | None:
+ try:
+ started = datetime.fromisoformat(str(profile.get("run", {}).get("started")))
+ except ValueError:
+ return None
+ return started if started.tzinfo else None
+
+
+def _l1_fired(profile: dict) -> list[str]:
+ return sorted(k for k, v in profile.get("facts", {}).items()
+ if isinstance(v, dict) and v.get("level") == "L1" and v.get("status") == "ok")
+
+
+def _cache_is_fresh(profile: dict, version: str) -> bool:
+ started = _started(profile)
+ run = profile.get("run", {})
+ return (started is not None and run.get("max_tier") == SCAN_TIER and run.get("collector_version") == version
+ and 0 <= (datetime.now(timezone.utc) - started).total_seconds() < SCAN_CACHE_MAX_AGE_S)
+
+
+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
+
+ home = _hermes_home()
+ path = home / "insights" / "profile.json" if home else None
+ cached = _read_json(path)
+ 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)}))
+ if _l1_fired(l1) == _l1_fired(cached):
+ return cached, "cache"
+ started = datetime.now(timezone.utc).isoformat(timespec="seconds")
+ profile = run(max_tier=SCAN_TIER)
+ profile["run"]["started"] = started
+ if path is not None:
+ try:
+ _write_private(path, profile)
+ except OSError:
+ pass
+ return profile, "fresh"
+
+
+def _scan() -> tuple[dict | None, str]:
+ box: dict = {}
+
+ def work() -> None:
+ try:
+ box["result"] = _scan_now()
+ except Exception as exc:
+ box["error"] = type(exc).__name__
+
+ worker = threading.Thread(target=work, daemon=True)
+ worker.start()
+ worker.join(SCAN_DEADLINE_S)
+ if "result" in box:
+ return box["result"]
+ return None, box.get("error", "timeout")
+
+
+def _value(profile: dict, fid: str) -> dict | None:
+ record = profile.get("facts", {}).get(fid)
+ if isinstance(record, dict) and record.get("status") == "ok" and isinstance(record.get("value"), dict):
+ return record["value"]
+ return None
+
+
+def _answered(profile: dict, fid: str) -> bool:
+ record = profile.get("facts", {}).get(fid)
+ return isinstance(record, dict) and record.get("status") in ("ok", "absent", "skipped_flag")
+
+
+def _insight(profile: dict, iid: str) -> dict | None:
+ for item in profile.get("insights", []):
+ if isinstance(item, dict) and item.get("id") == iid:
+ return item.get("value") if isinstance(item.get("value"), dict) else {}
+ return None
+
+
+def _num(value) -> float | None:
+ return value if isinstance(value, (int, float)) and not isinstance(value, bool) else None
+
+
+def _row_names(rows) -> list[str]:
+ if not isinstance(rows, list):
+ return []
+ return [str(row[0]) for row in rows if isinstance(row, (list, tuple)) and row]
+
+
+def _app_labels(names: list[str]) -> set[str]:
+ found = set()
+ for name in (n.lower().strip() for n in names):
+ for label, tokens in _SCAN_APPS.items():
+ if any(name == t[1:] if t.startswith("=") else t in name for t in tokens):
+ found.add(label)
+ return found
+
+
+def _scan_apps(profile: dict) -> tuple[list[str], list[str], bool]:
+ installed_names: list[str] = []
+ used_names: list[str] = []
+ usage_seen = False
+ taxonomy = _value(profile, "apps.taxonomy")
+ if taxonomy and isinstance(taxonomy.get("names"), dict):
+ for names in taxonomy["names"].values():
+ installed_names += [str(n) for n in names] if isinstance(names, list) else []
+ focus = _value(profile, "userassist.focus")
+ if focus:
+ usage_seen = True
+ used_names += _row_names(focus.get("top_focus_h")) + _row_names(focus.get("top_runs"))
+ used_names += _row_names(focus.get("top"))
+ last_run = _value(profile, "bam.last_run")
+ if last_run and isinstance(last_run.get("top"), list):
+ usage_seen = True
+ used_names += _row_names(last_run["top"])
+ for key, app in (_value(profile, "comms.native_apps") or {}).items():
+ if isinstance(app, dict):
+ installed_names += [key] if app.get("installed") else []
+ used_names += [key] if app.get("launched") else []
+ obs = _value(profile, "media.obs")
+ if obs:
+ installed_names.append("obs studio")
+ used_names += ["obs studio"] if obs.get("config_dir") is True or obs.get("obs_configs") else []
+ if _value(profile, "discord.present"):
+ installed_names.append("discord")
+ discord = _value(profile, "discord.usage")
+ if discord and (_num(discord.get("gateway_days")) or 0) > 0:
+ used_names.append("discord")
+ if _value(profile, "steam.present"):
+ installed_names.append("steam")
+ sessions = _value(profile, "steam.local_sessions")
+ if sessions and (_num(sessions.get("sessions")) or 0) > 0:
+ used_names.append("steam")
+ used = _app_labels(used_names)
+ unused = _app_labels(installed_names) - used
+ return sorted(used)[:10], sorted(unused)[:10], usage_seen
+
+
+def _agent_evidence(profile: dict) -> list[str]:
+ evidence = []
+ power = _insight(profile, "persona.ai_power_user") or {}
+ sessions = power.get("sessions") if isinstance(power.get("sessions"), dict) else {}
+ for key, name in _AGENT_NAMES.items():
+ count = _num(sessions.get(key))
+ if count is not None and count >= 3:
+ evidence.append(f"{name} {int(count)} sessions")
+ hermes = _value(profile, "hermes.present") or {}
+ side_homes = _num(hermes.get("side_homes_operator")) or 0
+ if side_homes:
+ evidence.append(f"{int(side_homes)} Hermes test homes")
+ accounts = _value(profile, "acct.local_users") or {}
+ kinds = accounts.get("enabled_kinds") if isinstance(accounts.get("enabled_kinds"), dict) else {}
+ sandboxes = _num(kinds.get("agent_or_tool")) or 0
+ if sandboxes:
+ evidence.append(f"{int(sandboxes)} agent sandbox accounts")
+ if _value(profile, "cua_driver.present"):
+ evidence.append("computer-use driver")
+ automation = _value(profile, "browser.automation") or {}
+ if any(key in automation for key in ("playwright", "puppeteer", "camoufox")):
+ evidence.append("browser automation")
+ mcp = _value(profile, "l3.mcp_inventory") or {}
+ servers = _num(mcp.get("user_configured_total")) or 0
+ if servers:
+ evidence.append(f"{int(servers)} MCP servers set up")
+ return evidence
+
+
+def interpret(profile: dict, source: str) -> dict:
+ unknown = []
+ state = _insight(profile, "install.install_state") or {}
+ tenure = _num(state.get("tenure_days"))
+ lived_in = _num(state.get("lived_in"))
+ sophistication = (_insight(profile, "persona.sophistication") or {}).get("tier")
+ level = {"novice": "beginner", "power-user": "power-user", "expert": "expert"}.get(sophistication, "unknown")
+ developer = (_insight(profile, "persona.developer") or {}).get("developer")
+ evidence = _agent_evidence(profile)
+ agent_probes = ("hermes.present", "codex.present", "claude_code.present")
+ runs_agents = bool(evidence) or ("unknown" if not any(_answered(profile, p) for p in agent_probes) else False)
+ if level in ("power-user", "expert") or developer is True or runs_agents is True:
+ beginner = False
+ elif level == "beginner":
+ beginner = True
+ else:
+ beginner = "unknown"
+
+ timeline = _value(profile, "srum.app_timeline") or {}
+ ratio = _num(timeline.get("input_focus_ratio"))
+ if ratio is None:
+ hands_on = "unknown"
+ unknown.append("hands-on vs remote")
+ else:
+ hands_on = "remote-driven" if ratio < 0.05 else "hands-on" if ratio > 0.3 else "mixed"
+ identity = (_value(profile, "dev.git_global_config") or {}).get("identity_set") is True
+ if not (identity and _value(profile, "dev.repos.my_commits")):
+ unknown.append("own commit count")
+
+ used, unused, usage_seen = _scan_apps(profile)
+ if not usage_seen:
+ unknown.append("which apps get used")
+
+ history = (_insight(profile, "install.user_history_elsewhere") or {}).get("user_history_elsewhere")
+ split = _value(profile, "l3.power_event_split")
+ crash = _num(split.get("crash_30d")) if split else None
+ theme = _value(profile, "theme.dark")
+ dark = theme.get("apps_dark") if theme else None
+ browser = str((_value(profile, "l3.primary_browser") or {}).get("primary") or "").lower()
+ started = _started(profile)
+ block = {
+ "source": source,
+ "age_h": round((datetime.now(timezone.utc) - started).total_seconds() / 3600, 1) if started else "unknown",
+ "tier": profile.get("run", {}).get("max_tier", "unknown"),
+ "machine_state": state.get("install_state", "unknown"),
+ "owned_days": int(tenure) if tenure is not None else "unknown",
+ "lived_in_of_10": lived_in if lived_in is not None else "unknown",
+ "history_before_this_install": history if isinstance(history, bool) else "unknown",
+ "user_level": level,
+ "developer": developer if isinstance(developer, bool) else "unknown",
+ "beginner_framing": beginner,
+ "runs_agents": runs_agents,
+ "agent_evidence": evidence,
+ "hands_on": hands_on,
+ "apps_used": used,
+ "apps_installed_no_use_seen": unused,
+ "crash_30d": int(crash) if crash is not None else "unknown",
+ "ui_theme": "unknown" if not isinstance(dark, bool) else "dark" if dark else "light",
+ "browser": browser if browser in _BROWSERS else "unknown" if not browser else "other",
+ "unknown": unknown,
+ "not_visible_at_tier": _NOT_VISIBLE_T1 if profile.get("run", {}).get("max_tier") == SCAN_TIER else [],
+ }
+ sessions = _value(profile, "steam.local_sessions")
+ if sessions:
+ hours, recent = _num(sessions.get("total_hours")), _num(sessions.get("hours_30d"))
+ block["games_here_h"] = round(hours) if hours is not None else "unknown"
+ block["games_here_h_30d"] = round(recent) if recent is not None else "unknown"
+ elif _value(profile, "steam.present"):
+ block["games_here_h"] = "unknown"
+ return block
+
+
+def _machine_state(scan: dict | None, age: int | None) -> tuple[str, int | None]:
+ if scan and scan.get("machine_state") in ("fresh", "settling", "established"):
+ owned = scan.get("owned_days")
+ return scan["machine_state"], owned if isinstance(owned, int) else age
+ if age is None:
+ return "unknown", None
+ return ("fresh" if age <= NEW_MACHINE_DAYS else "settling" if age < SETTLING_DAYS else "established"), age
+
+
+def collect(scan_json: Path | None = None) -> dict:
"""Return the fact block the ``/initiate-setup`` first turn embeds."""
+ if scan_json is not None:
+ profile, source = _read_json(scan_json), "file"
+ else:
+ profile, source = _scan()
+ scan = interpret(profile, source) if profile else {"source": "unavailable", "reason": source}
+
os_family = facts.os_family()
arch = facts.native_arch()
gpu = facts.gpu_class()
@@ -238,7 +578,8 @@ def collect() -> dict:
age = _home_age_days(home)
locale = _locale()
- looks_new = age is not None and age <= NEW_MACHINE_DAYS
+ state, setup_age = _machine_state(scan if profile else None, age)
+ looks_new = state == "fresh"
spark = _is_spark(os_family, arch, gpu, cpu)
leads = spark or looks_new
kind = _machine_kind(os_family, spark)
@@ -264,22 +605,27 @@ def collect() -> dict:
},
"signals": {
"machine_kind": kind,
+ "machine_state": state,
"looks_new": looks_new,
"is_spark": spark,
"has_nvidia_gpu": gpu == "nvidia",
"machine_setup_leads": leads,
"description": _description(
- looks_new=looks_new, age=age, spark=spark, gpu=gpu, cpu=cpu,
+ looks_new=looks_new, age=setup_age, spark=spark, gpu=gpu, cpu=cpu,
os_family=os_family, release=release, arch=arch,
),
},
"plugin_tasks": plugin_tasks,
"fork": _fork(kind, leads, plugin_tasks),
+ "scan": scan,
}
def main() -> None:
- print(json.dumps(collect(), indent=2, ensure_ascii=False))
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--from-json", type=Path, help="interpret this saved scan instead of scanning")
+ args = parser.parse_args()
+ print(json.dumps(collect(args.from_json), ensure_ascii=False, separators=(",", ":")))
if __name__ == "__main__":
diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/run.py b/optional-skills/productivity/initiate-setup/scripts/userscan/run.py
new file mode 100644
index 00000000000..d7fd8d1a61e
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/run.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python3
+"""userscan entry point.
+
+ python run.py # default: T1, core+extended, 4 s budget
+ python run.py --max-tier T2 --deep --allow-vss --budget-ms 8000
+ python run.py --out profile.json
+ python run.py --list # show registered probes and exit
+ python run.py --all-users # add an aggregate-only pass per login account
+ python run.py --os linux # select probes as if on another OS (testing)
+ python run.py --home /tmp/h --localappdata ... --appdata ... --hermes-home ...
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+from userscan.runner import run, scan_accounts # noqa: E402
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser("userscan")
+ ap.add_argument("--max-tier", choices=["T0", "T1", "T2", "T3"], default="T1",
+ help="privacy cap: values above this tier are stripped from the output")
+ ap.add_argument("--budget-ms", type=int, default=4000)
+ ap.add_argument("--allow-vss", action="store_true", help="allow esentutl /vss copy (slow, admin)")
+ ap.add_argument("--deep", action="store_true", help="run deep-tier probes too (SRUM, profile walks)")
+ ap.add_argument("--only", action="append", help="probe id or family (repeatable)")
+ ap.add_argument("--skip-family", action="append")
+ ap.add_argument("--out", help="write JSON to this file instead of stdout")
+ ap.add_argument("--list", action="store_true")
+ ap.add_argument("--os", dest="os_name", choices=["detect", "windows", "darwin", "linux"], default="detect",
+ help="probe selection OS; default detects the real one")
+ ap.add_argument("--all-users", action="store_true",
+ help="also run user-level L1 detectors once per login account; aggregate output only")
+ ap.add_argument("--include-operator", action="store_true",
+ help="with --all-users: keep operator lab accounts (hn-e2e, ns960, ...)")
+ ap.add_argument("--home", help="override l0 home (also HOME/USERPROFILE for the run)")
+ ap.add_argument("--localappdata", help="override l0 localappdata / LOCALAPPDATA")
+ ap.add_argument("--appdata", help="override l0 appdata / APPDATA")
+ ap.add_argument("--hermes-home", help="override l0 hermes_home / HERMES_HOME ('' = unset)")
+ args = ap.parse_args(argv)
+
+ # import OS probe modules so their registrations land
+ import userscan.specs # noqa: F401
+
+ if args.list:
+ from userscan.registry import REGISTRY, INSIGHTS
+ for pid in sorted(REGISTRY):
+ p = REGISTRY[pid]
+ print(f"{pid:44} {p.level} {p.tier} {p.collect:8} gate={p.gate or '-':28} {p.family}")
+ for iid in sorted(INSIGHTS):
+ print(f"L3 {iid:41} {INSIGHTS[iid].inputs}")
+ return 0
+
+ only = list(args.only) if args.only else None
+ os_override = None if args.os_name == "detect" else args.os_name
+ overrides = {k: getattr(args, k) for k in ("home", "localappdata", "appdata", "hermes_home")
+ 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)
+ if accounts is not None:
+ out["all_users"] = accounts
+ text = json.dumps(out, indent=2, default=str)
+ if args.out:
+ with open(args.out, "w", encoding="utf-8") as fh:
+ fh.write(text)
+ extra = f" accounts={len(accounts['accounts'])}" if accounts is not None else ""
+ print(f"wrote {args.out} wall_ms={out['run']['wall_ms']} facts={len(out['facts'])} insights={len(out['insights'])}{extra}")
+ else:
+ print(text)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/__init__.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/__init__.py
new file mode 100644
index 00000000000..b2fe2560aee
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/__init__.py
@@ -0,0 +1,6 @@
+"""userscan: gated, timed, privacy-tiered collector of user/computer insights.
+
+Probe authors only need: probe(), ps_probe(), insight(), and the HostAccess helpers passed in as `h`.
+See collector/CONTRACT.md.
+"""
+__version__ = "0.1.0"
diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/host.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/host.py
new file mode 100644
index 00000000000..fa9da868ae5
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/host.py
@@ -0,0 +1,608 @@
+"""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 io
+import json
+import os
+import platform
+import re
+import shutil
+import sqlite3
+import struct
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+
+OS_NAMES = ("windows", "darwin", "linux")
+# l0 keys a run may override, and the environment variables each one stands for.
+OVERRIDABLE = {"home": ("HOME", "USERPROFILE"), "localappdata": ("LOCALAPPDATA",),
+ "appdata": ("APPDATA",), "hermes_home": ("HERMES_HOME",)}
+# Operator lab accounts (CONTRACT.md hard rule 4); list_users drops them unless asked.
+_OPERATOR_ACCT_RX = re.compile(r"^(hn-e2e|ns960|ns923.*|lhm|shots|user-insights-lab|hermes-.*)$", re.I)
+_PLACEHOLDER_HOMES = ("", "/", "/nonexistent", "/dev/null", "/var/empty")
+_VAR_RX = re.compile(r"%([A-Za-z_][A-Za-z0-9_()]*)%")
+
+# ---------------------------------------------------------------- L0 facts
+
+
+def detect_os() -> str:
+ if sys.platform == "win32":
+ return "windows"
+ if sys.platform == "darwin":
+ return "darwin"
+ return "linux"
+
+
+def _pe_machine(path: str) -> str:
+ try:
+ with open(path, "rb") as f:
+ if f.read(2) != b"MZ":
+ return ""
+ f.seek(0x3C)
+ (off,) = struct.unpack("<I", f.read(4))
+ f.seek(off)
+ if f.read(4) != b"PE\0\0":
+ return ""
+ (machine,) = struct.unpack("<H", f.read(2))
+ return {0x8664: "x64", 0xAA64: "arm64", 0x14C: "x86"}.get(machine, hex(machine))
+ except OSError:
+ return ""
+
+
+def _native_machine() -> str:
+ if sys.platform == "win32":
+ try:
+ import ctypes
+ k32 = ctypes.WinDLL("kernel32")
+ get = getattr(k32, "IsWow64Process2", None)
+ if get:
+ process_machine = ctypes.c_ushort()
+ native_machine = ctypes.c_ushort()
+ get(ctypes.c_void_p(-1), ctypes.byref(process_machine), ctypes.byref(native_machine))
+ return {0x8664: "x64", 0xAA64: "arm64", 0x14C: "x86"}.get(native_machine.value, "")
+ except Exception:
+ pass
+ return platform.machine().lower()
+ return platform.machine().lower()
+
+
+def _is_admin() -> bool:
+ if sys.platform == "win32":
+ try:
+ import ctypes
+ return bool(ctypes.windll.shell32.IsUserAnAdmin())
+ except Exception:
+ return False
+ return os.geteuid() == 0 if hasattr(os, "geteuid") else False
+
+
+class HostAccess:
+ """Primitives every probe may call. `scratch()` is a per-run temp dir, removed at exit."""
+
+ def __init__(self, facts: dict):
+ self.l0 = facts
+ self.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.
+ self.foreign = bool(facts.get("foreign_user"))
+ self._scratch = None
+ self._via = threading.local()
+
+ @property
+ def last_via(self):
+ return getattr(self._via, "v", None)
+
+ @last_via.setter
+ def last_via(self, v):
+ self._via.v = v
+
+ # -- paths ------------------------------------------------------
+ def expand(self, path: str) -> str:
+ """~ resolves to l0 home and %VAR% to the l0 value for HOME/USERPROFILE/LOCALAPPDATA/APPDATA/
+ HERMES_HOME, so an overridden run targets the overridden home on every OS."""
+ home = self.l0.get("home") or os.path.expanduser("~")
+ if path == "~" or path.startswith(("~/", "~\\")):
+ path = home + path[1:]
+ by_env = {}
+ for key, names in OVERRIDABLE.items():
+ for n in names:
+ by_env[n] = self.l0.get(key) or ""
+
+ def sub(m):
+ v = by_env.get(m.group(1).upper())
+ if v:
+ return v
+ v = os.environ.get(m.group(1))
+ return v if v is not None else m.group(0)
+ return os.path.expandvars(_VAR_RX.sub(sub, path))
+
+ def exists(self, path: str) -> bool:
+ return os.path.exists(self.expand(path))
+
+ def meta(self, path: str):
+ """presence + size + mtime. Safe for T3 files (never opened)."""
+ p = self.expand(path)
+ try:
+ st = os.stat(p)
+ return {"present": True, "bytes": st.st_size, "mtime": int(st.st_mtime)}
+ except OSError:
+ return {"present": False}
+
+ def count_dir(self, path: str, max_entries: int = 20000) -> int:
+ p = self.expand(path)
+ n = 0
+ try:
+ with os.scandir(p) as it:
+ for _ in it:
+ n += 1
+ if n >= max_entries:
+ break
+ except OSError:
+ return -1
+ return n
+
+ def list_dir(self, path: str, max_entries: int = 500):
+ p = self.expand(path)
+ try:
+ with os.scandir(p) as it:
+ return [e.name for _, e in zip(range(max_entries), it)]
+ except OSError:
+ return []
+
+ # -- registry ---------------------------------------------------
+ def reg(self, path: str, value: str = None):
+ """Read a value, or enumerate subkey names if value is None. None on miss.
+ path = 'HKLM\\SOFTWARE\\...'"""
+ if self.os != "windows" or self.real_os != "windows":
+ return None
+ if self.foreign and path[:4] == "HKCU":
+ return None
+ import winreg
+ root = {"HKLM": winreg.HKEY_LOCAL_MACHINE, "HKCU": winreg.HKEY_CURRENT_USER,
+ "HKU": winreg.HKEY_USERS, "HKCR": winreg.HKEY_CLASSES_ROOT}.get(path[:4])
+ if root is None:
+ return None
+ key_path = path[5:]
+ try:
+ if value is None:
+ with winreg.OpenKey(root, key_path) as k:
+ out, i = [], 0
+ while True:
+ try:
+ out.append(winreg.EnumKey(k, i))
+ except OSError:
+ return out
+ i += 1
+ if i > 5000:
+ return out
+ with winreg.OpenKey(root, key_path) as k:
+ v, _ = winreg.QueryValueEx(k, value)
+ return v
+ except OSError:
+ return None
+
+ # -- sqlite -----------------------------------------------------
+ def sqlite(self, path: str, query: str, params=(), timeout_ms: int = 1500):
+ """Read-only query on a copy if a WAL is present, else on the live file.
+ Returns list of rows (tuples) or None on any failure. Ladder rung is in self.last_via (thread-local)."""
+ p = self.expand(path)
+ if not os.path.exists(p):
+ return None
+ if os.path.exists(p + "-wal") or os.path.exists(p + "-journal"):
+ return self._sqlite_copy_then_query(p, query, params, timeout_ms)
+ for via, uri in (("live", f"file:{p}?mode=ro"), ("immutable", f"file:{p}?mode=ro&immutable=1")):
+ try:
+ con = sqlite3.connect(uri, uri=True, timeout=timeout_ms / 1000.0)
+ con.set_progress_handler(lambda: 1 if timeout_ms else 0, 1000)
+ rows = con.execute(query, params).fetchall()
+ con.close()
+ self.last_via = via
+ return rows
+ except Exception:
+ continue
+ return self._sqlite_copy_then_query(p, query, params, timeout_ms)
+
+ def _sqlite_copy_then_query(self, p, query, params, timeout_ms):
+ try:
+ dst = os.path.join(self.scratch(), os.path.basename(p))
+ shutil.copyfile(p, dst)
+ for suf in ("-wal", "-journal"):
+ if os.path.exists(p + suf):
+ shutil.copyfile(p + suf, dst + suf)
+ con = sqlite3.connect(dst, timeout=timeout_ms / 1000.0)
+ rows = con.execute(query, params).fetchall()
+ con.close()
+ self.last_via = "copy"
+ return rows
+ except Exception:
+ return None
+
+ # -- locked files -----------------------------------------------
+ def copy_locked(self, path: str, dst_name: str = None, allow_vss: bool = False):
+ """Ladder: shutil copy -> esentutl /y -> esentutl /y /vss (only with allow_vss).
+ Returns (abs path or None, rung name)."""
+ p = self.expand(path)
+ dst = os.path.join(self.scratch(), dst_name or os.path.basename(p))
+ try:
+ shutil.copyfile(p, dst)
+ return dst, "shutil"
+ except OSError:
+ pass
+ for rung, args in (("esentutl", ["esentutl", "/y", p, "/d", dst, "/o"]),
+ ("vss", ["esentutl", "/y", p, "/vss", "/d", dst, "/o"])):
+ if rung == "vss" and not allow_vss:
+ continue
+ try:
+ r = subprocess.run(args, capture_output=True, timeout=30)
+ if r.returncode == 0 and os.path.exists(dst):
+ return dst, rung
+ except Exception:
+ continue
+ return None, "failed"
+
+ # -- powershell / subprocess -------------------------------------
+ def run(self, args, timeout_ms: int = 5000, text: bool = True):
+ """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)."""
+ try:
+ r = subprocess.run(args, capture_output=True, timeout=timeout_ms / 1000.0,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
+ return (r.stdout or b"").decode("utf-8", "replace")
+ except Exception:
+ return None
+
+ def powershell(self, script: str, timeout_ms: int = 8000):
+ """Single-shot powershell. Prefer ps_probe (batched) when several probes need PS."""
+ return self.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", script], timeout_ms, text=True)
+
+ # -- accounts ----------------------------------------------------
+ def list_users(self, include_operator: bool = False):
+ """Login accounts on this host as [{"user": name, "home": path}]. Names and homes only.
+ windows: ProfileList (SID -> name via LookupAccountSid), `net user` if that is empty.
+ linux: passwd entries with uid >= UID_MIN, a shell listed in /etc/shells, a non-placeholder home.
+ darwin: dscl . -readall /Users (uid >= 501, real shell, home under /Users), /Users scan fallback.
+ Under --os the pretend OS's account store is not on this host, so the real OS's is used."""
+ try:
+ got = {"windows": self._users_windows, "linux": self._users_linux,
+ "darwin": self._users_darwin}[self.real_os]()
+ except Exception:
+ got = []
+ seen, out = set(), []
+ for u in got:
+ name = (u.get("user") or "").strip()
+ if not name or name.lower() in seen:
+ continue
+ if not include_operator and _OPERATOR_ACCT_RX.match(name):
+ continue
+ seen.add(name.lower())
+ out.append({"user": name, "home": u.get("home") or ""})
+ return out
+
+ def _users_linux(self):
+ uid_min = 1000
+ try:
+ with open("/etc/login.defs", encoding="utf-8", errors="replace") as fh:
+ for line in fh:
+ parts = line.split()
+ if len(parts) >= 2 and parts[0] == "UID_MIN" and parts[1].isdigit():
+ uid_min = int(parts[1])
+ except OSError:
+ pass
+ shells = set()
+ try:
+ with open("/etc/shells", encoding="utf-8", errors="replace") as fh:
+ shells = {s.strip() for s in fh if s.strip() and not s.startswith("#")}
+ except OSError:
+ pass
+ try:
+ import pwd
+ rows = [(p.pw_name, p.pw_uid, p.pw_dir, p.pw_shell) for p in pwd.getpwall()]
+ except Exception:
+ rows = []
+ with open("/etc/passwd", encoding="utf-8", errors="replace") as fh:
+ for line in fh:
+ f = line.rstrip("\n").split(":")
+ if len(f) >= 7 and f[2].isdigit():
+ rows.append((f[0], int(f[2]), f[5], f[6]))
+ out = []
+ for name, uid, home, shell in rows:
+ if uid < uid_min or uid >= 65534:
+ continue
+ base = os.path.basename(shell or "")
+ if base in ("nologin", "false", "sync", "") or (shells and shell not in shells):
+ continue
+ if home.rstrip("/") in _PLACEHOLDER_HOMES or home.startswith(("/proc", "/sys", "/usr/", "/bin")):
+ continue
+ out.append({"user": name, "home": home})
+ return out
+
+ def _users_darwin(self):
+ out = []
+ raw = self.run(["dscl", ".", "-readall", "/Users", "RecordName", "UniqueID", "UserShell",
+ "NFSHomeDirectory"], 5000) if self.real_os == "darwin" else None
+ if raw:
+ for rec in raw.split("\n-\n"):
+ vals, key = {}, None
+ for line in rec.splitlines():
+ if line.startswith(" ") and key:
+ vals[key] = (vals.get(key, "") + " " + line.strip()).strip()
+ elif ":" in line:
+ key, _, v = line.partition(":")
+ vals[key] = v.strip()
+ name = (vals.get("RecordName") or "").split()
+ uid = (vals.get("UniqueID") or "").strip()
+ shell = os.path.basename(vals.get("UserShell") or "")
+ home = vals.get("NFSHomeDirectory") or ""
+ if not name or not uid.isdigit() or int(uid) < 501:
+ continue
+ if shell in ("false", "nologin", "") or not home.startswith("/Users/"):
+ continue
+ out.append({"user": name[0], "home": home})
+ if not out:
+ try:
+ with os.scandir("/Users") as it:
+ for _, e in zip(range(200), it):
+ if e.is_dir() and e.name not in ("Shared", "Guest") and not e.name.startswith("."):
+ out.append({"user": e.name, "home": e.path})
+ except OSError:
+ pass
+ return out
+
+ def _users_windows(self):
+ base = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
+ out = []
+ for sid in self.reg(base) or []:
+ if not sid.startswith(("S-1-5-21-", "S-1-12-1-")) or sid.endswith(".bak"):
+ continue
+ home = os.path.expandvars(self.reg(base + "\\" + sid, "ProfileImagePath") or "")
+ if not home:
+ continue
+ out.append({"user": _sid_to_name(sid) or os.path.basename(home), "home": home})
+ if out:
+ return out
+ raw = self.run(["net", "user"], 5000) or ""
+ lines = raw.splitlines()
+ start = next((i for i, l in enumerate(lines) if l.startswith("---")), None)
+ if start is None:
+ return out
+ root = os.path.join(os.environ.get("SystemDrive", "C:") + "\\", "Users")
+ for line in lines[start + 1:]:
+ if not line.strip() or line.lower().startswith("the command"):
+ break
+ for name in re.split(r"\s{2,}", line.strip()):
+ if name:
+ out.append({"user": name, "home": os.path.join(root, name)})
+ return out
+
+ def process_counts(self):
+ """{username: process count} for every account with a visible process, or None when the OS
+ does not expose other users' processes to this caller. Counts only; no names, no argv."""
+ counts = {}
+ if self.real_os == "linux":
+ import pwd
+ names = {}
+ try:
+ with os.scandir("/proc") as it:
+ for e in it:
+ if not e.name.isdigit():
+ continue
+ try:
+ uid = e.stat(follow_symlinks=False).st_uid
+ except OSError:
+ continue
+ if uid not in names:
+ try:
+ names[uid] = pwd.getpwuid(uid).pw_name
+ except KeyError:
+ names[uid] = str(uid)
+ counts[names[uid]] = counts.get(names[uid], 0) + 1
+ except OSError:
+ return None
+ return counts
+ if self.real_os == "darwin":
+ raw = self.run(["ps", "-axo", "user="], 5000)
+ if raw is None:
+ return None
+ for line in raw.splitlines():
+ u = line.strip()
+ if u:
+ counts[u] = counts.get(u, 0) + 1
+ return counts
+ if self.real_os == "windows":
+ import csv
+ raw = self.run(["tasklist", "/v", "/fo", "csv", "/nh"], 15000)
+ if raw is None:
+ return None
+ for row in csv.reader(raw.splitlines()):
+ if len(row) >= 7 and row[6] and row[6] != "N/A":
+ u = row[6].split("\\")[-1]
+ counts[u] = counts.get(u, 0) + 1
+ return counts
+ return None
+
+ # -- scratch -----------------------------------------------------
+ def scratch(self) -> str:
+ if self._scratch is None:
+ base = os.path.join(tempfile.gettempdir(), "userscan", self.l0.get("run_id", "run"))
+ os.makedirs(base, exist_ok=True)
+ self._scratch = base
+ return self._scratch
+
+ def cleanup(self):
+ if self._scratch and os.path.isdir(self._scratch):
+ shutil.rmtree(self._scratch, ignore_errors=True)
+ parent = os.path.dirname(self._scratch)
+ try:
+ os.rmdir(parent)
+ except OSError:
+ 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's
+ value must not leak into another account's pass); probes fall back to the default location."""
+ if os_name == "windows":
+ return {"home": home, "localappdata": os.path.join(home, "AppData", "Local"),
+ "appdata": os.path.join(home, "AppData", "Roaming"), "hermes_home": ""}
+ return {"home": home, "localappdata": "", "appdata": "", "hermes_home": ""}
+
+
+def _sid_to_name(sid: str):
+ try:
+ import ctypes
+ from ctypes import wintypes
+ adv = ctypes.WinDLL("advapi32")
+ psid = ctypes.c_void_p()
+ if not adv.ConvertStringSidToSidW(ctypes.c_wchar_p(sid), ctypes.byref(psid)):
+ return None
+ try:
+ name = ctypes.create_unicode_buffer(256)
+ dom = ctypes.create_unicode_buffer(256)
+ n, d, use = wintypes.DWORD(256), wintypes.DWORD(256), wintypes.DWORD()
+ if adv.LookupAccountSidW(None, psid, name, ctypes.byref(n), dom, ctypes.byref(d), ctypes.byref(use)):
+ return name.value
+ finally:
+ ctypes.windll.kernel32.LocalFree(psid)
+ except Exception:
+ return None
+ return None
+
+
+def collect_l0(run_id: str, allow_vss: bool = False, os_override: str = None, overrides: dict = None) -> dict:
+ """L0 facts. `os_override` (windows|darwin|linux) makes probe selection behave as if on that OS;
+ `overrides` replaces any of home/localappdata/appdata/hermes_home for this run. When home is
+ overridden and the others are not, they are derived from the new home (see per_user_overrides)."""
+ detected = detect_os()
+ os_name = os_override if os_override in OS_NAMES else detected
+ facts = {
+ "run_id": run_id,
+ "os": os_name,
+ "os_detected": detected,
+ "os_overridden": os_name != detected,
+ "os_release": platform.release(),
+ "os_build": platform.version(),
+ "native_arch": _native_machine(),
+ "python_arch": _pe_machine(sys.executable),
+ "admin": _is_admin(),
+ "user": os.environ.get("USERNAME") or os.environ.get("USER") or "",
+ "home": os.path.expanduser("~"),
+ "localappdata": os.environ.get("LOCALAPPDATA", ""),
+ "appdata": os.environ.get("APPDATA", ""),
+ "hermes_home": os.environ.get("HERMES_HOME", ""),
+ "allow_vss": allow_vss,
+ "overridden": [],
+ }
+ ov = {k: v for k, v in (overrides or {}).items() if k in OVERRIDABLE and v is not None}
+ if "home" in ov:
+ for k, v in per_user_overrides(os_name, ov["home"]).items():
+ ov.setdefault(k, v)
+ for k, v in ov.items():
+ facts[k] = v
+ facts["overridden"] = sorted(ov)
+ facts["python_emulated"] = bool(facts["python_arch"] and facts["native_arch"]
+ and facts["python_arch"] != facts["native_arch"]
+ and facts["python_arch"] in ("x64", "x86")
+ and facts["native_arch"] == "arm64")
+ return facts
diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/registry.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/registry.py
new file mode 100644
index 00000000000..57753468da8
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/registry.py
@@ -0,0 +1,88 @@
+"""Probe registry. Pure data + decorators; no I/O at import time."""
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Callable, Optional
+
+TIERS = ("T0", "T1", "T2", "T3")
+COLLECT = ("core", "extended", "deep")
+LEVELS = ("L1", "L2")
+
+
+@dataclass
+class Probe:
+ id: str
+ level: str # L1 detector | L2 extractor
+ family: str # category, e.g. "browser", "gaming"
+ tier: str # privacy tier of the VALUE this probe returns
+ collect: str # core | extended | deep
+ gate: Optional[str] # id of a probe whose value must be truthy; None = OS gate only
+ os: str # "windows" | "darwin" | "linux" | "any"
+ timeout_ms: int
+ fn: Optional[Callable] = None # python probe: fn(h, facts) -> value | None
+ ps: Optional[str] = None # powershell probe: script whose output object becomes the value
+ needs_admin: bool = False
+ doc: str = ""
+
+
+@dataclass
+class Insight:
+ id: str
+ inputs: list
+ fn: Callable # fn(facts) -> dict(claim=, strength=, value=?) | None
+ doc: str = ""
+
+
+REGISTRY: dict = {}
+INSIGHTS: dict = {}
+
+
+def _key(p: Probe) -> str:
+ """The same signal id may be registered once per OS; the first registration keeps the bare id."""
+ if p.id not in REGISTRY:
+ return p.id
+ return f"{p.id}@{p.os}"
+
+
+def _check(p: Probe) -> None:
+ for q in REGISTRY.values():
+ if q.id == p.id and (q.os == p.os or "any" in (q.os, p.os)):
+ raise ValueError(f"duplicate probe id {p.id} for os {p.os}")
+ if p.tier not in TIERS or p.collect not in COLLECT or p.level not in LEVELS:
+ raise ValueError(f"bad tier/collect/level on {p.id}")
+ if p.level == "L2" and not p.gate:
+ raise ValueError(f"L2 probe {p.id} needs a gate")
+
+
+def probe(id: str, *, level: str, family: str, tier: str = "T0", collect: str = "core",
+ gate: Optional[str] = None, os: str = "windows", timeout_ms: int = 2000,
+ needs_admin: bool = False):
+ """Register a python probe. Return None / False / {} for 'absent'."""
+ def deco(fn):
+ p = Probe(id, level, family, tier, collect, gate, os, timeout_ms, fn=fn,
+ needs_admin=needs_admin, doc=(fn.__doc__ or "").strip())
+ _check(p)
+ REGISTRY[_key(p)] = p
+ return fn
+ return deco
+
+
+def ps_probe(id: str, script: str, *, level: str = "L2", family: str, tier: str = "T0",
+ collect: str = "extended", gate: Optional[str] = None, timeout_ms: int = 8000,
+ needs_admin: bool = False, doc: str = ""):
+ """Register a PowerShell snippet. All ps probes run in ONE batched powershell.exe.
+ The snippet must leave its result object on the pipeline (it is captured with ConvertTo-Json)."""
+ p = Probe(id, level, family, tier, collect, gate, "windows", timeout_ms, ps=script,
+ needs_admin=needs_admin, doc=doc)
+ _check(p)
+ REGISTRY[_key(p)] = p
+
+
+def insight(id: str, inputs: list):
+ """Register an L3 derivation over facts. fn(facts) gets {id: value} for ok facts only."""
+ def deco(fn):
+ if id in INSIGHTS:
+ raise ValueError(f"duplicate insight {id}")
+ INSIGHTS[id] = Insight(id, list(inputs), fn, (fn.__doc__ or "").strip())
+ return fn
+ return deco
diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/runner.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/runner.py
new file mode 100644
index 00000000000..ddc78c04c4a
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/runner.py
@@ -0,0 +1,361 @@
+"""The runner: gates -> L1 detectors -> L2 extractors (batched PS + worker threads) -> L3 insights."""
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import threading
+import time
+import uuid
+
+from .host import (AggregateHostAccess, HostAccess, collect_l0, deny_reads_under, override_env,
+ per_user_overrides)
+from .registry import REGISTRY, INSIGHTS, TIERS
+
+
+def _truthy(v):
+ if v is None:
+ return False
+ if isinstance(v, dict):
+ return bool(v.get("present", True))
+ return bool(v)
+
+
+def _filter_values(out: dict, max_tier: str) -> None:
+ """Drop values above max_tier from the output. A T3 probe is allowed to run (it returns
+ presence only); what the filter removes is anything content-shaped."""
+ cap = TIERS.index(max_tier)
+ # `host` is L0 and carries no tier of its own, but it holds the account name and absolute
+ # home paths. Those are identity (contract rule 3) and must not survive at any tier.
+ for k in ("user", "home", "localappdata", "appdata", "hermes_home", "run_id"):
+ out["host"].pop(k, None)
+ for fid, f in out["facts"].items():
+ v = f.get("value")
+ if v is None:
+ continue
+ t = TIERS.index(f.get("tier", "T0"))
+ if t <= cap:
+ continue
+ if isinstance(v, dict):
+ for k in list(v):
+ if k not in ("present", "bytes", "count", "files", "dirs", "mtime", "size"):
+ v.pop(k)
+ elif isinstance(v, list):
+ 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:
+ """One collection pass. `os_override` pretends to be another OS for probe selection;
+ `overrides` retargets home/localappdata/appdata/hermes_home (see host.collect_l0)."""
+ 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)
+
+
+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 selected(p):
+ if p.os not in ("any", l0["os"]):
+ return False
+ if p.family in skip_family:
+ return False
+ if p.collect == "deep" and not include_deep:
+ return False
+ if only is not None and p.id not in only and p.family not in only:
+ return False
+ if p.needs_admin and not l0["admin"]:
+ return False
+ return True
+
+ facts: dict = {}
+ timing = {}
+ skipped: dict = {}
+ errors: dict = {}
+
+ 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(p):
+ return p.gate is None or _truthy(facts.get(p.gate, {}).get("value"))
+
+ # ---------------- 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)
+
+ # ---------------- 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, 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()
+
+ # ---------------- 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))
+
+ # 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]
+
+ 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:
+ with lock:
+ errors[p.id] = f"{type(e).__name__}: {e}"
+ 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:
+ 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)
+
+ # ---------------- 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_ps_batch(probes, h, gate_ok, max_tier, allow_vss, skipped):
+ """One powershell.exe for every ps probe. Returns [(probe, status, ms, value)]."""
+ results = []
+ todo = []
+ for p in probes:
+ if not gate_ok(p):
+ results.append((p, "skipped_flag", 0, None))
+ else:
+ todo.append(p)
+ if not todo:
+ return results
+ blocks = []
+ for p in todo:
+ blocks.append(
+ f"$ErrorActionPreference='Continue'; $sw=[Diagnostics.Stopwatch]::StartNew(); "
+ f"try {{ $__v = & {{ {p.ps} }} | ConvertTo-Json -Compress -Depth 4 }} catch {{ $__v = $null }}; "
+ f"[PSCustomObject]@{{ id = '{p.id}'; ms = $sw.Elapsed.TotalMilliseconds; v = $__v }}\n")
+ # PS 5.1 rejects a line that starts with '|', so the blocks are wrapped in one scriptblock.
+ # The script goes through a scratch file: -Command hits the 32 KB command-line limit.
+ script = "$ProgressPreference='SilentlyContinue';\n& {\n" + "".join(blocks) + "} | ConvertTo-Json -Compress\n"
+ try:
+ path = os.path.join(h.scratch(), "ps_batch.ps1")
+ 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,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
+ raw = (r.stdout or b"").decode("utf-8", "replace")
+ data = json.loads(raw) if raw.strip() else []
+ except Exception:
+ data = []
+ if isinstance(data, dict):
+ data = [data]
+ by_id = {}
+ for d in data:
+ if isinstance(d, dict) and "id" in d:
+ v = d.get("v")
+ if isinstance(v, str):
+ try:
+ v = json.loads(v)
+ except Exception:
+ v = {"raw": v[:2000]}
+ by_id[d["id"]] = (d.get("ms", 0.0), v)
+ for p in todo:
+ if p.id in by_id:
+ ms, v = by_id[p.id]
+ results.append((p, "ok" if _truthy(v) else "absent", ms, v if _truthy(v) else {"present": False}))
+ else:
+ results.append((p, "error", 0.0, None))
+ return results
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__.py
new file mode 100644
index 00000000000..a67a2964465
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/__init__.py
@@ -0,0 +1,27 @@
+"""Probe module loader. Add new module names here as you create them."""
+from __future__ import annotations
+
+import 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
+]
+
+for m in _MODULES:
+ try:
+ importlib.import_module(m)
+ except ImportError:
+ pass
diff --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.py
new file mode 100644
index 00000000000..452ba156eb8
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/apps_dev.py
@@ -0,0 +1,2695 @@
+"""Installed software (apps), AI agents (ai_agents) and dev environment (dev) probes.
+
+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.
+"""
+from __future__ import annotations
+
+import collections
+import datetime as dt
+import glob
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import threading
+import time
+
+from userscan.registry import probe
+
+try:
+ import winreg # noqa: F401
+except ImportError: # non-Windows import (e.g. `run.py --list` on the Mac)
+ winreg = None
+
+try:
+ import tomllib
+except ImportError:
+ tomllib = None
+
+APPS, AI, DEV = "apps", "ai_agents", "dev"
+NOWIN = getattr(subprocess, "CREATE_NO_WINDOW", 0)
+
+# ------------------------------------------------------------------ shared helpers
+
+_LOCK = threading.Lock()
+_CACHE: dict = {}
+_KEYLOCKS: dict = {}
+
+
+def _memo(h, name, fn):
+ key = (h.l0.get("run_id"), name)
+ with _LOCK:
+ if key in _CACHE:
+ return _CACHE[key]
+ lk = _KEYLOCKS.setdefault(key, threading.Lock())
+ with lk:
+ if key in _CACHE:
+ return _CACHE[key]
+ v = fn()
+ _CACHE[key] = v
+ return v
+
+
+def _U(h):
+ return h.l0.get("home") or os.path.expanduser("~")
+
+
+def _LA(h):
+ return h.l0.get("localappdata") or os.environ.get("LOCALAPPDATA", "")
+
+
+def _RA(h):
+ return h.l0.get("appdata") or os.environ.get("APPDATA", "")
+
+
+def _PD():
+ return os.environ.get("ProgramData", r"C:\ProgramData")
+
+
+def _PF():
+ return os.environ.get("ProgramW6432") or os.environ.get("ProgramFiles") or r"C:\Program Files"
+
+
+def _PF86():
+ return os.environ.get("ProgramFiles(x86)") or r"C:\Program Files (x86)"
+
+
+def _day(t):
+ try:
+ return dt.datetime.fromtimestamp(float(t)).strftime("%Y-%m-%d") if t else None
+ except (OverflowError, OSError, ValueError):
+ return None
+
+
+def _iso(ts):
+ """unix s/ms/us/ns or ISO string -> local ISO minutes."""
+ if ts is None or ts == "":
+ return None
+ if isinstance(ts, str):
+ try:
+ return dt.datetime.fromisoformat(ts.replace("Z", "+00:00")).astimezone().isoformat(timespec="minutes")
+ except ValueError:
+ try:
+ ts = float(ts)
+ except ValueError:
+ return None
+ try:
+ ts = float(ts)
+ except (TypeError, ValueError):
+ return None
+ if ts > 1e17:
+ ts /= 1e9
+ elif ts > 1e14:
+ ts /= 1e6
+ elif ts > 1e11:
+ ts /= 1e3
+ try:
+ return dt.datetime.fromtimestamp(ts).astimezone().isoformat(timespec="minutes")
+ except (OverflowError, OSError, ValueError):
+ return None
+
+
+def _mtime(p):
+ try:
+ return _day(os.stat(p).st_mtime)
+ except OSError:
+ return None
+
+
+def _ctime(p):
+ try:
+ return _day(os.stat(p).st_ctime)
+ except OSError:
+ return None
+
+
+def _isdir(p):
+ try:
+ return os.path.isdir(p)
+ except OSError:
+ return False
+
+
+def _ls(p, cap=500):
+ try:
+ with os.scandir(p) as it:
+ return [e.name for _, e in zip(range(cap), it)]
+ except OSError:
+ return None
+
+
+def _read_json(p, maxb=5_000_000, jsonc=False):
+ try:
+ if os.path.getsize(p) > maxb:
+ return None
+ with open(p, "r", encoding="utf-8-sig", errors="replace") as f:
+ txt = f.read()
+ if jsonc:
+ txt = _strip_jsonc(txt)
+ return json.loads(txt)
+ except (OSError, ValueError):
+ return None
+
+
+def _strip_jsonc(txt):
+ out, i, n, in_str = [], 0, len(txt), False
+ while i < n:
+ c = txt[i]
+ if in_str:
+ out.append(c)
+ if c == "\\" and i + 1 < n:
+ out.append(txt[i + 1]); i += 2; continue
+ if c == '"':
+ in_str = False
+ elif c == '"':
+ in_str = True; out.append(c)
+ elif txt.startswith("//", i):
+ j = txt.find("\n", i); i = n if j < 0 else j; continue
+ elif txt.startswith("/*", i):
+ j = txt.find("*/", i + 2); i = n if j < 0 else j + 2; continue
+ else:
+ out.append(c)
+ i += 1
+ return re.sub(r",(\s*[}\]])", r"\1", "".join(out))
+
+
+def _top(counter, n=10):
+ return dict(collections.Counter({k: v for k, v in counter.items() if k is not None}).most_common(n))
+
+
+_RED = [(re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+"), "<email>"),
+ (re.compile(r"[A-Za-z]:\\[^\s\"']*"), "<path>"),
+ (re.compile(r"(?<![\w])/(?:Users|home)/[^\s\"']*"), "<path>"),
+ (re.compile(r"\b[A-Za-z0-9_\-]{32,}\b"), "<token>"),
+ (re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"), "<ip>")]
+
+
+def _redact(s, n=70):
+ if not isinstance(s, str):
+ return None
+ for rx, rep in _RED:
+ s = rx.sub(rep, s)
+ s = " ".join(s.split())
+ return s[:n] + ("..." if len(s) > n else "")
+
+
+def _copy_db(h, src, tag):
+ """Copy an sqlite db (+wal/shm/journal) into scratch under a unique name. Returns path or None."""
+ try:
+ dst = os.path.join(h.scratch(), f"{tag}-{threading.get_ident()}-{os.path.basename(src)}")
+ shutil.copyfile(src, dst)
+ for suf in ("-wal", "-journal"):
+ if os.path.exists(src + suf):
+ shutil.copyfile(src + suf, dst + suf)
+ return dst
+ except OSError:
+ return None
+
+
+def _q(path, sql, args=()):
+ import sqlite3
+ con = sqlite3.connect(path, timeout=2)
+ try:
+ return con.execute(sql, args).fetchall()
+ finally:
+ con.close()
+
+
+def _cols(path, table):
+ try:
+ return {r[1] for r in _q(path, f"pragma table_info({table})")}
+ except Exception:
+ return set()
+
+
+def _rmdb(p):
+ for suf in ("", "-wal", "-journal", "-shm"):
+ try:
+ os.remove(p + suf)
+ except OSError:
+ pass
+
+
+_PATHIDX = None
+_PATHIDX_LOCK = threading.Lock()
+
+
+def _path_index():
+ """One listdir per PATH dir (interpreter dir removed: uv run prepends it). Cached per process."""
+ global _PATHIDX
+ with _PATHIDX_LOCK:
+ if _PATHIDX is None:
+ exe_dir = os.path.normcase(os.path.dirname(sys.executable).rstrip("\\/"))
+ dirs, seen = [], set()
+ for p in os.environ.get("PATH", "").split(os.pathsep):
+ p = os.path.expandvars(p.strip().strip('"'))
+ key = os.path.normcase(p.rstrip("\\/"))
+ if not p or key == exe_dir or key in seen:
+ continue
+ seen.add(key)
+ names = _ls(p, 20000)
+ if names:
+ dirs.append((p, {n.lower(): n for n in names}))
+ exts = [e.lower() for e in os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(";") if e]
+ _PATHIDX = (dirs, exts)
+ return _PATHIDX
+
+
+def _which(name):
+ """shutil.which equivalent over the cached PATH index."""
+ dirs, exts = _path_index()
+ n = name.lower()
+ cands = [n] if os.path.splitext(n)[1] in exts else [n + e for e in exts]
+ for d, names in dirs:
+ for c in cands:
+ if c in names:
+ return os.path.join(d, names[c])
+ return None
+
+
+def _spawn(args, timeout=8.0, env=None):
+ """(rc, stdout, ms). Never used with bash.exe or pwsh."""
+ exe = args[0]
+ if exe.lower().endswith((".cmd", ".bat")):
+ args = ["cmd.exe", "/d", "/c"] + args
+ t = time.perf_counter()
+ try:
+ r = subprocess.run(args, capture_output=True, timeout=timeout, env=env, creationflags=NOWIN,
+ stdin=subprocess.DEVNULL)
+ out = (r.stdout or b"") or (r.stderr or b"")
+ txt = out.decode("utf-8", "replace")
+ if txt.count("\x00") > len(txt) // 4:
+ txt = out.decode("utf-16-le", "replace")
+ return r.returncode, txt.replace("\x00", "").strip(), round((time.perf_counter() - t) * 1000, 1)
+ except Exception:
+ return None, "", round((time.perf_counter() - t) * 1000, 1)
+
+
+# operator noise: scratch/test artifacts that belong to the lab operator, not the user
+OPERATOR_TOP_RE = re.compile(r"^(hn-e2e|ns960|ns923.*|lhm|shots|user-insights-lab|hermes-.+|hermes-lab)$", re.I)
+OPERATOR_TASK_RE = re.compile(r"^(hermes-|lab-run|hn-|ns960|ns923|shot-live|shots|cua-driver-serve|ensure-sshd|user-insights|uil-|lhm)", re.I)
+
+
+def _is_operator_path(h, p):
+ """True if p is under %USERPROFILE%\\<op>, %LOCALAPPDATA%\\<op> or C:\\<op> for an operator top dir."""
+ pn = os.path.normcase(os.path.abspath(p))
+ for base in (_U(h), _LA(h), "C:\\"):
+ b = os.path.normcase(os.path.abspath(base)).rstrip("\\/") + os.sep
+ if pn.startswith(b):
+ first = pn[len(b):].split(os.sep, 1)[0]
+ if first and OPERATOR_TOP_RE.match(first):
+ return True
+ return False
+
+
+# ------------------------------------------------------------------ registry helpers
+
+def _open(hive, path, flag=0):
+ try:
+ return winreg.OpenKey(hive, path, 0, winreg.KEY_READ | flag)
+ except OSError:
+ return None
+
+
+def _rv(k, name):
+ try:
+ return winreg.QueryValueEx(k, name)[0]
+ except OSError:
+ return None
+
+
+def _subkeys(k, cap=5000):
+ i = 0
+ while i < cap:
+ try:
+ yield winreg.EnumKey(k, i)
+ except OSError:
+ return
+ i += 1
+
+
+def _values(k, cap=2000):
+ i = 0
+ while i < cap:
+ try:
+ yield winreg.EnumValue(k, i)
+ except OSError:
+ return
+ i += 1
+
+
+def _ft_day(ft100ns):
+ if not ft100ns:
+ return None
+ try:
+ return (dt.datetime(1601, 1, 1) + dt.timedelta(microseconds=ft100ns // 10)).strftime("%Y-%m-%d")
+ except OverflowError:
+ return None
+
+
+def _install_date(s):
+ if isinstance(s, str):
+ s = s.strip()
+ if re.fullmatch(r"\d{8}", s):
+ try:
+ dt.date(int(s[:4]), int(s[4:6]), int(s[6:]))
+ return f"{s[:4]}-{s[4:6]}-{s[6:]}"
+ except ValueError:
+ return None
+ if re.fullmatch(r"\d{1,2}/\d{1,2}/\d{4}", s):
+ m, d, y = s.split("/")
+ return f"{y}-{int(m):02d}-{int(d):02d}"
+ return None
+
+
+# ------------------------------------------------------------------ PE version info (ctypes)
+
+_VER = None
+_VER_LOCK = threading.Lock()
+_COMPANY: dict = {}
+
+
+def _verdll():
+ global _VER
+ with _VER_LOCK:
+ if _VER is None:
+ import ctypes
+ from ctypes import wintypes
+ v = ctypes.WinDLL("version")
+ v.GetFileVersionInfoSizeW.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(wintypes.DWORD)]
+ v.GetFileVersionInfoSizeW.restype = wintypes.DWORD
+ v.GetFileVersionInfoW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p]
+ v.VerQueryValueW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_void_p),
+ ctypes.POINTER(wintypes.UINT)]
+ _VER = v
+ return _VER
+
+
+def _verbuf(path):
+ import ctypes
+ v = _verdll()
+ n = v.GetFileVersionInfoSizeW(path, None)
+ if not n:
+ return None
+ buf = ctypes.create_string_buffer(n)
+ if not v.GetFileVersionInfoW(path, 0, n, buf):
+ return None
+ return buf
+
+
+def _file_version(path, kind="product"):
+ if not path or not os.path.isfile(path):
+ return None
+ try:
+ import ctypes
+ from ctypes import wintypes
+ buf = _verbuf(path)
+ if buf is None:
+ return None
+ p = ctypes.c_void_p(); ln = wintypes.UINT()
+ if not _verdll().VerQueryValueW(buf, "\\", ctypes.byref(p), ctypes.byref(ln)) or ln.value < 52:
+ return None
+ f = ctypes.cast(p, ctypes.POINTER(ctypes.c_uint32 * 13)).contents
+ ms, ls = (f[4], f[5]) if kind == "product" else (f[2], f[3])
+ return f"{ms >> 16}.{ms & 0xFFFF}.{ls >> 16}.{ls & 0xFFFF}"
+ except Exception:
+ return None
+
+
+def _company(path):
+ if not path:
+ return None
+ key = path.lower()
+ if key in _COMPANY:
+ return _COMPANY[key]
+ res = None
+ try:
+ import ctypes
+ from ctypes import wintypes
+ buf = _verbuf(path) if os.path.isfile(path) else None
+ if buf is not None:
+ v = _verdll()
+ p = ctypes.c_void_p(); ln = wintypes.UINT()
+ langs = []
+ if v.VerQueryValueW(buf, r"\VarFileInfo\Translation", ctypes.byref(p), ctypes.byref(ln)) and ln.value:
+ arr = ctypes.cast(p, ctypes.POINTER(wintypes.WORD * (ln.value // 2))).contents
+ langs = [(arr[i], arr[i + 1]) for i in range(0, len(arr) - 1, 2)]
+ langs += [(0x0409, 0x04B0), (0x0409, 0x04E4)]
+ for lang, cp in langs:
+ q = f"\\StringFileInfo\\{lang:04x}{cp:04x}\\CompanyName"
+ if v.VerQueryValueW(buf, q, ctypes.byref(p), ctypes.byref(ln)) and ln.value:
+ res = ctypes.wstring_at(p, ln.value).split("\x00")[0].strip() or None
+ if res:
+ break
+ except Exception:
+ res = None
+ _COMPANY[key] = res
+ return res
+
+
+def _exe_from_cmd(cmd):
+ if not cmd or not isinstance(cmd, str):
+ return None
+ c = os.path.expandvars(cmd.strip())
+ if c.startswith('"'):
+ e = c[1:].split('"', 1)[0]
+ else:
+ m = re.match(r"(.+?\.(exe|dll|sys|cmd|bat|ps1|com))\b", c, re.I)
+ e = m.group(1) if m else c.split(" ")[0]
+ sr = os.environ.get("SystemRoot", r"C:\Windows")
+ if e.lower().startswith("\\systemroot\\"):
+ e = os.path.join(sr, e[12:])
+ elif e.lower().startswith("system32\\"):
+ e = os.path.join(sr, e)
+ elif e.startswith("\\??\\"):
+ e = e[4:]
+ return e
+
+
+# ------------------------------------------------------------------ taxonomy (from report 02)
+
+OVERRIDES = [
+ ("productivity", r"officehub|microsoft 365 copilot"),
+ ("runtime", r"applicationcompatibilityenhancements|officepushnotification|office\.actionsserver|steamworks common"),
+ ("hardware_vendor", r"asustek|asus\b|b9eced6f|armoury|rog |glidex|storycube|proart|screenxpert|dolby|intelligo|cirrus ?logic|realtek|appup\.intel|intel\(r\)|nvidiacorp|mediatek|lgelectronics|lg monitor|logi(tech)?\b|razer|patriot|openrgb|msi afterburner|rivatuner|ene\b|physx|nvidia (graphics|hd audio|app|control|display|frameview|localsystem)|nvidia broadcast|cpuid"),
+ ("ai", r"ollama|openai|codex|chatgpt|claude|anthropic|hermes|nousresearch|\bcua\b|lm ?studio|gpt4all|comfyui|pinokio|anythingllm|jan\.ai|cursor|windsurf|copilot\b|perplexity|msty|koboldcpp|browser-use"),
+ ("gaming", r"\bsteam\b|cd projekt|steam app \d+|\\steamapps\\|\\games\\|epic games|epic online|easyanticheat|easy anti-cheat|battleye|elytra|rockstar|riot|xbox|gamingapp|gameassist|\bgame(s)?\b|palworld|cyberpunk|helldivers|death stranding|dead cells|faster than light|disco elysium|hotline miami|stickman|universe sandbox|\bpeak\b|control resonant|deadpool|\bf1 \d\d|minecraft|gog galaxy|battle\.net|ubisoft|ea app|playnite|vortex|curseforge|solitaire"),
+]
+RULES = [
+ ("runtime", r"visual c\+\+|redistributable|vcredist|\.net (runtime|framework|desktop)|desktop runtime|windows desktop runtime|webview2|directx|vulkanrt|openal|winappruntime|windowsappruntime|vclibs|ui\.xaml|\bcrt\b|application compatibility|compatibility fix|extension$|videoextension|imageextension|mediaextensions|d3dmappinglayers|webexperience|widgetsplatform|language ?experience|ink\.handwriting|steamworks common"),
+ ("dev", r"visual studio|vscode|vs code|\bgit\b|github|node\.?js|nodejs|docker|wsl|subsystemforlinux|windowsterminal|terminal|powershell|openssh|ripgrep|python|jetbrains|pycharm|android studio|cmake|llvm|rust|golang|jdk|java|postman|wireshark|putty|winscp|devhome|dev home|sysinternals|msys|conda|\bsdk\b|cuda|hyper-v|virtualbox|vmware|neovim|sublime|notepad\+\+|devtoys|msbuild"),
+ ("creative", r"adobe|photoshop|lightroom|premiere|illustrator|gimp|krita|inkscape|blender|davinci|obs ?studio|obs-studio|streamlabs|audacity|reaper|ableton|fl studio|handbrake|kdenlive|shotcut|paint|affinity|figma|canva|capcut|clipchamp|vlc|videolan|mpv|potplayer|zunemusic|media player|photos|camera|screensketch|snipping|soundrecorder|sketchup|maxon|red giant|cinema 4d|unity|unreal|godot|omniverse|autodesk|ffmpeg|sharex|voicemeeter"),
+ ("comms", r"discord|slack|\bteams\b|msteams|zoom|skype|telegram|whatsapp|signal|thunderbird|outlook|messenger|webex|mattermost|beeper|yourphone|phone link|crossdevice|mixedrealitylink"),
+ ("productivity", r"microsoft 365|\boffice\b|officehub|word|excel|powerpoint|onenote|notion|obsidian|logseq|evernote|todoist|todos|onedrive|dropbox|google drive|brave|chrome|firefox|\bedge\b|microsoftedge|opera|vivaldi|zen browser|acrobat|pdf|sumatra|libreoffice|sticky ?notes|notepad|calculator|journal|whiteboard|1password|bitwarden|keepass|everything|powertoys|flow launcher|raycast|bing(news|search|weather)|news|weather|aimgr|local ai manager|powerautomate"),
+ ("utilities", r"7-?zip|winrar|peazip|nanazip|qbittorrent|torrent|ccleaner|revo|windirstat|wiztree|rufus|ventoy|crystaldisk|macrium|anydesk|teamviewer|rustdesk|parsec|tailscale|cloudflare|warp|wireguard|openvpn|mullvad|nordvpn|equalizer ?apo|peace\b|pawnio|autohotkey|sharpkeys|twinkle tray|translucenttb|startallback|explorerpatcher|quicklook|winget|desktopappinstaller|appinstaller|chocolatey|scoop|unigetui|quickassist|family|gethelp|feedbackhub|sechealth|alarms|clock|store|startexperiences|decompyle|pyinstxtractor"),
+]
+_CLS = [(c, re.compile(p, re.I)) for c, p in OVERRIDES + RULES]
+USER_CATS = ["dev", "ai", "gaming", "creative", "comms", "productivity", "utilities", "hardware_vendor"]
+_ALIASES = {"microsoft vs code": "visual studio code", "vscode": "visual studio code"}
+_NOISE = {"microsoft", "version", "desktop", "app", "installer", "en", "us", "user", "the", "x64", "x86", "arm64"}
+
+
+def _classify(name, publisher="", extra=""):
+ s = f"{name} {publisher or ''} {extra or ''}"
+ for c, rx in _CLS:
+ if rx.search(s):
+ return c
+ return "other"
+
+
+def _norm(name, appx=False):
+ n = (name or "").strip()
+ if appx and "." in n:
+ n = re.sub(r"([a-z])([A-Z])", r"\1 \2", n.split(".")[-1])
+ n = n.lower()
+ n = _ALIASES.get(n, n)
+ n = re.sub(r"\(.*?\)|v?\d+(\.\d+)+\S*|\b64-bit\b|\b32-bit\b", " ", n)
+ return "".join(w for w in re.split(r"[^a-z0-9]+", n) if w and w not in _NOISE)
+
+
+# ------------------------------------------------------------------ shared inventories
+
+UNINSTALL = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
+APPX_REPO = r"Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\Repository\Packages"
+APPX_PROV = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Applications"
+
+
+def _uninstall(h):
+ def build():
+ views = [("HKLM", winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_64KEY),
+ ("HKLM_WOW6432", winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_32KEY),
+ ("HKCU", winreg.HKEY_CURRENT_USER, 0)]
+ items, stats = [], {}
+ for label, hive, flag in views:
+ root = _open(hive, UNINSTALL, flag)
+ if root is None:
+ stats[label] = None
+ continue
+ st = {"keys": 0, "listed": 0, "system_component": 0, "updates": 0, "no_name": 0}
+ for sk in _subkeys(root):
+ st["keys"] += 1
+ try:
+ k = winreg.OpenKey(root, sk)
+ except OSError:
+ continue
+ with k:
+ name = _rv(k, "DisplayName")
+ if not name:
+ st["no_name"] += 1; continue
+ if _rv(k, "SystemComponent") == 1:
+ st["system_component"] += 1; continue
+ if _rv(k, "ParentKeyName") or _rv(k, "ReleaseType") in ("Update", "Hotfix", "Security Update"):
+ st["updates"] += 1; continue
+ pub = _rv(k, "Publisher")
+ loc = _rv(k, "InstallLocation") or ""
+ st["listed"] += 1
+ items.append({"name": name, "publisher": pub, "version": _rv(k, "DisplayVersion"),
+ "install_date": _install_date(_rv(k, "InstallDate")),
+ "key_lastwrite": _ft_day(winreg.QueryInfoKey(k)[2]), "view": label,
+ "category": _classify(name, pub, f"{sk} {loc}")})
+ stats[label] = st
+ return {"stats": stats, "items": items}
+ return _memo(h, "uninstall", build)
+
+
+def _uninst_match(h, pattern):
+ rx = re.compile(pattern, re.I)
+ return [i for i in _uninstall(h)["items"] if rx.search(i["name"] or "")]
+
+
+def _appx(h):
+ def build():
+ k = _open(winreg.HKEY_CURRENT_USER, APPX_REPO)
+ if k is None:
+ return None
+ prov = set()
+ pk = _open(winreg.HKEY_LOCAL_MACHINE, APPX_PROV)
+ if pk is not None:
+ for fn in _subkeys(pk):
+ prov.add(fn.split("_")[0].lower())
+ windir = os.environ.get("SystemRoot", r"C:\Windows").lower()
+ counts = {"total": 0, "framework": 0, "resource": 0, "system": 0, "kept": 0, "provisioned": 0, "user_added": 0}
+ items, full = [], []
+ for fullname in _subkeys(k):
+ counts["total"] += 1
+ parts = fullname.split("_")
+ if len(parts) != 5:
+ continue
+ name, ver, arch, resid, pubid = parts
+ full.append({"name": name, "version": ver, "arch": arch})
+ try:
+ s = winreg.OpenKey(k, fullname)
+ except OSError:
+ continue
+ with s:
+ if _rv(s, "Framework") == 1:
+ counts["framework"] += 1; continue
+ if resid and resid != "~":
+ counts["resource"] += 1; continue
+ root = (_rv(s, "PackageRootFolder") or "").lower()
+ if not root or root.startswith(windir):
+ counts["system"] += 1; continue
+ dn = _rv(s, "DisplayName") or ""
+ if dn.startswith(("@", "ms-resource")):
+ dn = None
+ provisioned = name.lower() in prov
+ counts["kept"] += 1
+ counts["provisioned" if provisioned else "user_added"] += 1
+ items.append({"name": name, "display": dn, "version": ver, "arch": arch, "provisioned": provisioned,
+ "first_seen": _ctime(os.path.join(_LA(h), "Packages", f"{name}_{pubid}")),
+ "category": _classify(f"{name} {dn or ''}")})
+ return {"provisioned_apps": len(prov), "counts": counts, "items": items, "all": full}
+ return _memo(h, "appx", build)
+
+
+def _appx_match(h, pattern):
+ a = _appx(h)
+ if not a:
+ return []
+ rx = re.compile(pattern, re.I)
+ seen, out = set(), []
+ for p in a["all"]:
+ if rx.search(p["name"]) and (p["name"], p["version"], p["arch"]) not in seen:
+ seen.add((p["name"], p["version"], p["arch"]))
+ out.append(p)
+ return out
+
+
+def _procs(h):
+ def build():
+ import ctypes
+ from ctypes import wintypes
+
+ class PE(ctypes.Structure):
+ _fields_ = [("dwSize", wintypes.DWORD), ("cntUsage", wintypes.DWORD), ("th32ProcessID", wintypes.DWORD),
+ ("th32DefaultHeapID", ctypes.c_size_t), ("th32ModuleID", wintypes.DWORD),
+ ("cntThreads", wintypes.DWORD), ("th32ParentProcessID", wintypes.DWORD),
+ ("pcPriClassBase", ctypes.c_long), ("dwFlags", wintypes.DWORD),
+ ("szExeFile", ctypes.c_wchar * 260)]
+ k32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ k32.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
+ k32.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
+ k32.Process32FirstW.argtypes = [wintypes.HANDLE, ctypes.POINTER(PE)]
+ k32.Process32NextW.argtypes = [wintypes.HANDLE, ctypes.POINTER(PE)]
+ k32.CloseHandle.argtypes = [wintypes.HANDLE]
+ snap = k32.CreateToolhelp32Snapshot(2, 0)
+ names = collections.Counter()
+ if not snap or snap == wintypes.HANDLE(-1).value:
+ return names
+ e = PE(); e.dwSize = ctypes.sizeof(PE)
+ ok = k32.Process32FirstW(snap, ctypes.byref(e))
+ n = 0
+ while ok and n < 20000:
+ names[e.szExeFile.lower()] += 1
+ n += 1
+ ok = k32.Process32NextW(snap, ctypes.byref(e))
+ k32.CloseHandle(snap)
+ return names
+ return _memo(h, "procs", build)
+
+
+def _running(h, pattern):
+ rx = re.compile(pattern, re.I)
+ return {k: v for k, v in _procs(h).items() if rx.search(k)}
+
+
+# ================================================================== apps
+
+@probe(id="apps.uninstall", level="L1", family=APPS, tier="T0", collect="core")
+def apps_uninstall(h, facts):
+ """Uninstall keys (HKLM 64/32-bit views + HKCU): every installed program with installer metadata."""
+ u = _uninstall(h)
+ items = u["items"]
+ return {"present": True, "views": u["stats"], "listed": len(items),
+ "with_install_date": sum(1 for i in items if i["install_date"]),
+ "items": [{k: i[k] for k in ("name", "publisher", "version", "install_date", "category")} for i in items]}
+
+
+@probe(id="apps.appx_registry", level="L1", family=APPS, tier="T0", collect="core")
+def apps_appx_registry(h, facts):
+ """Store/MSIX packages from the HKCU AppModel repository (replaces Get-AppxPackage)."""
+ a = _appx(h)
+ if not a:
+ return None
+ return {"present": True, "provisioned_apps": a["provisioned_apps"], "counts": a["counts"],
+ "user_added": sorted(i["name"] for i in a["items"] if not i["provisioned"]),
+ "items": [{k: i[k] for k in ("name", "version", "arch", "provisioned", "first_seen", "category")}
+ for i in a["items"]]}
+
+
+@probe(id="apps.autostart", level="L1", family=APPS, tier="T0", collect="core")
+def apps_autostart(h, facts):
+ """Run/RunOnce keys + Startup folders with StartupApproved enabled/disabled state."""
+ approved = {}
+ for hive, path in [(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run"),
+ (winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run"),
+ (winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run32"),
+ (winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\StartupFolder")]:
+ k = _open(hive, path)
+ if k is None:
+ continue
+ for n, v, _ in _values(k):
+ if isinstance(v, bytes) and v:
+ approved[n.lower()] = "disabled" if v[0] & 1 else "enabled"
+ items = []
+ for label, hive, path, flag in [
+ ("HKLM_Run", winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", winreg.KEY_WOW64_64KEY),
+ ("HKLM_RunOnce", winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", winreg.KEY_WOW64_64KEY),
+ ("HKLM_WOW_Run", winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", winreg.KEY_WOW64_32KEY),
+ ("HKCU_Run", winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", 0),
+ ("HKCU_RunOnce", winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", 0)]:
+ k = _open(hive, path, flag)
+ if k is None:
+ continue
+ for n, v, _ in _values(k, 200):
+ exe = _exe_from_cmd(v if isinstance(v, str) else "")
+ items.append({"name": n, "source": label, "state": approved.get(n.lower(), "enabled"),
+ "company": _company(exe), "category": _classify(f"{n} {exe or ''}")})
+ for label, p in [("startup_folder_user", os.path.join(_RA(h), r"Microsoft\Windows\Start Menu\Programs\Startup")),
+ ("startup_folder_common", os.path.join(_PD(), r"Microsoft\Windows\Start Menu\Programs\StartUp"))]:
+ for n in _ls(p, 200) or []:
+ if n.lower() == "desktop.ini":
+ continue
+ items.append({"name": os.path.splitext(n)[0], "source": label,
+ "state": approved.get(n.lower(), "enabled"), "company": None,
+ "category": _classify(n)})
+ seen, dedup = set(), []
+ for i in items:
+ key = (i["name"].lower(), i["source"].startswith("HKLM"))
+ if key not in seen:
+ seen.add(key); dedup.append(i)
+ persistent = [i for i in dedup if "RunOnce" not in i["source"]]
+ return {"present": True, "total": len(persistent), "enabled": sum(1 for i in persistent if i["state"] == "enabled"),
+ "disabled": sum(1 for i in persistent if i["state"] == "disabled"),
+ "run_once": len(dedup) - len(persistent), "items": dedup}
+
+
+@probe(id="apps.lad_programs", level="L1", family=APPS, tier="T0", collect="core")
+def apps_lad_programs(h, facts):
+ """%LOCALAPPDATA%\\Programs: per-user installs (VS Code, Ollama, Cua, GIMP) that skip HKLM."""
+ names = _ls(os.path.join(_LA(h), "Programs"), 300)
+ if names is None:
+ return None
+ names = sorted(n for n in names if n.lower() != "common")
+ return {"present": True, "count": len(names), "names": names}
+
+
+@probe(id="apps.progdirs", level="L2", family=APPS, tier="T0", collect="core", gate="apps.uninstall")
+def apps_progdirs(h, facts):
+ """Top-level Program Files / ProgramData directory names with category."""
+ out = {}
+ for label, p in [("ProgramFiles", _PF()), ("ProgramFilesX86", _PF86()),
+ ("LocalAppData_Programs", os.path.join(_LA(h), "Programs")), ("ProgramData", _PD())]:
+ try:
+ with os.scandir(p) as it:
+ dirs = [e.name for _, e in zip(range(600), it) if e.is_dir(follow_symlinks=False)]
+ except OSError:
+ out[label] = None
+ continue
+ by = collections.Counter(_classify(d) for d in dirs)
+ out[label] = {"count": len(dirs), "by_category": dict(by), "names": sorted(dirs)[:120]}
+ return {"present": True, **out}
+
+
+_SM_SKIP_DIR = re.compile(r"^(accessibility|accessories|administrative tools|system tools|windows powershell|startup|maintenance)(\\|$)|\\startup\\", re.I)
+_SM_SKIP_NAME = re.compile(r"uninstall|readme|documentation|website|help|release notes|faq|reset|sdk|skin format|localization|samples|setup -|command prompt|file explorer|administrative tools|control panel|^run$|task manager|settings|language preferences|install additional", re.I)
+
+
+def _walk_lnk(root, depth, cap=800):
+ out = []
+ if not _isdir(root):
+ return None
+ base = root.rstrip("\\").count("\\")
+ for dp, dns, fns in os.walk(root):
+ if dp.count("\\") - base >= depth:
+ dns[:] = []
+ for f in fns:
+ if f.lower().endswith((".lnk", ".url", ".appref-ms")):
+ p = os.path.join(dp, f)
+ out.append((os.path.relpath(p, root), _ctime(p)))
+ if len(out) >= cap:
+ return out
+ return out
+
+
+def _known_app_keys(h):
+ keys = {_norm(i["name"]) for i in _uninstall(h)["items"]}
+ a = _appx(h)
+ if a:
+ keys |= {_norm(i["name"], appx=True) for i in a["items"]}
+ keys |= {_norm(i["display"]) for i in a["items"] if i["display"]}
+ keys |= {_norm(n) for n in (_ls(os.path.join(_LA(h), "Programs")) or [])}
+ return {k for k in keys if len(k) >= 3}
+
+
+def _matches_known(n, known):
+ k = _norm(n)
+ if not k:
+ return False
+ if k in known:
+ return True
+ return any(len(a) >= 4 and (k.startswith(a) or a.startswith(k)) for a in known if len(k) >= 4)
+
+
+@probe(id="apps.startmenu", level="L2", family=APPS, tier="T2", collect="core", gate="apps.uninstall")
+def apps_startmenu(h, facts):
+ """Start Menu / taskbar / desktop shortcut names; keeps names that match a known app or category."""
+ known = _known_app_keys(h)
+ roots = {"common": (os.path.join(_PD(), r"Microsoft\Windows\Start Menu\Programs"), 3),
+ "user": (os.path.join(_RA(h), r"Microsoft\Windows\Start Menu\Programs"), 3),
+ "taskbar_pinned": (os.path.join(_RA(h), r"Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar"), 1),
+ "desktop_user": (os.path.join(_U(h), "Desktop"), 1),
+ "desktop_public": (r"C:\Users\Public\Desktop", 1)}
+ out = {"present": True}
+ for label, (p, depth) in roots.items():
+ items = _walk_lnk(p, depth)
+ if items is None:
+ out[label] = None
+ continue
+ kept, dropped = [], 0
+ for rel, _c in items:
+ nm = os.path.splitext(os.path.basename(rel))[0]
+ if _SM_SKIP_DIR.search(rel) or _SM_SKIP_NAME.search(nm):
+ continue
+ if _matches_known(nm, known) or _classify(nm) != "other":
+ kept.append(nm)
+ else:
+ dropped += 1
+ out[label] = {"count": len(items), "app_names": sorted(set(kept))[:120], "unmatched_dropped": dropped}
+ return out
+
+
+def _steam_games(h):
+ steam = None
+ for hive, path, val in [(winreg.HKEY_CURRENT_USER, r"Software\Valve\Steam", "SteamPath"),
+ (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Valve\Steam", "InstallPath")]:
+ k = _open(hive, path)
+ if k is not None and _rv(k, val):
+ steam = _rv(k, val); break
+ if not steam:
+ return []
+ try:
+ with open(os.path.join(steam, "steamapps", "libraryfolders.vdf"), encoding="utf-8", errors="replace") as f:
+ libs = re.findall(r'"path"\s+"([^"]+)"', f.read())
+ except OSError:
+ libs = [steam]
+ names = []
+ for lib in libs[:10]:
+ sa = os.path.join(lib.replace("\\\\", "\\"), "steamapps")
+ for n in _ls(sa, 2000) or []:
+ if n.startswith("appmanifest_") and n.endswith(".acf"):
+ try:
+ with open(os.path.join(sa, n), encoding="utf-8", errors="replace") as f:
+ m = re.search(r'"name"\s+"([^"]+)"', f.read(4096))
+ if m and "redistributable" not in m.group(1).lower():
+ names.append(m.group(1))
+ except OSError:
+ pass
+ return names
+
+
+def _winget(h):
+ def build():
+ src = os.path.join(_LA(h), r"Packages\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\LocalState\Microsoft.Winget.Source_8wekyb3d8bbwe\installed.db")
+ if not os.path.exists(src):
+ return None
+ dst = _copy_db(h, src, "winget")
+ if not dst:
+ return {"error": "copy_failed"}
+ try:
+ rows = _q(dst, """select m.rowid, i.id, n.name, v.version from manifest m
+ join ids i on i.rowid=m.id join names n on n.rowid=m.name
+ join versions v on v.rowid=m.version""")
+ meta = {}
+ for mid, key, val in _q(dst, "select manifest, metadata, value from manifest_metadata"):
+ meta.setdefault(mid, {})[str(key)] = val
+ except Exception as e:
+ return {"error": type(e).__name__}
+ finally:
+ _rmdb(dst)
+ items = []
+ for mid, pid, name, ver in rows:
+ md = meta.get(mid, {})
+ inst = md.get("7")
+ items.append({"id": pid, "name": name, "version": ver, "arch": md.get("8"),
+ "pinned": bool(md.get("9")) if md.get("9") not in (None, "0", 0) else False,
+ "installed": _day(int(inst)) if inst and str(inst).isdigit() else None,
+ "category": _classify(f"{pid} {name}")})
+ return {"bytes": os.path.getsize(src), "items": items}
+ return _memo(h, "winget", build)
+
+
+def _taxonomy(h):
+ def build():
+ apps = {}
+
+ def add(name, pub, cat, date, src, pre=False):
+ n = _norm(name, appx=(src == "appx"))
+ if not n:
+ return
+ if n not in apps:
+ for k in apps:
+ a_, b_ = (n, k) if len(n) <= len(k) else (k, n)
+ if len(a_) >= 4 and b_.startswith(a_):
+ n = k; break
+ a = apps.setdefault(n, {"name": name, "category": cat, "date": None, "sources": set(), "pre": pre})
+ a["sources"].add(src)
+ a["pre"] = a["pre"] and pre
+ if date and (not a["date"] or date < a["date"]):
+ a["date"] = date
+
+ for i in _uninstall(h)["items"]:
+ add(i["name"], i["publisher"], i["category"], i["install_date"] or i["key_lastwrite"], "uninstall")
+ a = _appx(h)
+ for i in (a or {}).get("items", []):
+ add(i["name"], None, i["category"], i["first_seen"], "appx", pre=i["provisioned"])
+ lap = os.path.join(_LA(h), "Programs")
+ for n in _ls(lap) or []:
+ if n.lower() != "common" and _isdir(os.path.join(lap, n)):
+ add(n, None, _classify(n), _ctime(os.path.join(lap, n)), "localappdata_programs")
+ for g in _steam_games(h):
+ add(g, None, "gaming", None, "steam_manifest")
+ w = _winget(h)
+ for i in (w or {}).get("items", []) or []:
+ add(i["name"] or i["id"], None, i["category"], i["installed"], "winget")
+ for root in (os.path.join(_RA(h), r"Microsoft\Windows\Start Menu\Programs"),
+ os.path.join(_PD(), r"Microsoft\Windows\Start Menu\Programs")):
+ for rel, c in _walk_lnk(root, 3) or []:
+ if not rel.lower().endswith(".lnk") or _SM_SKIP_DIR.search(rel):
+ continue
+ nm = os.path.splitext(os.path.basename(rel))[0]
+ if not _SM_SKIP_NAME.search(nm):
+ add(nm, None, _classify(nm), c, "start_menu")
+ for nm in _ls(os.path.join(_U(h), ".local", "bin")) or []:
+ base = os.path.splitext(nm)[0]
+ if base.lower() in ("claude", "codex", "hermes", "ollama", "gemini", "aider", "goose", "opencode"):
+ add(base, None, "ai", None, "local_bin")
+ prof = _ctime(_U(h))
+ for v in apps.values():
+ if prof and v["date"] and v["date"] < prof:
+ v["pre"] = True
+ allv = list(apps.values())
+ user = [v for v in allv if v["category"] in USER_CATS or v["category"] == "other"]
+ return {"profile_created": prof,
+ "image_date": _ctime(os.path.join(_PF(), "Windows NT")),
+ "all": allv, "user": user}
+ return _memo(h, "taxonomy", build)
+
+
+@probe(id="apps.taxonomy", level="L2", family=APPS, tier="T0", collect="core", gate="apps.uninstall")
+def apps_taxonomy(h, facts):
+ """Merged app inventory (uninstall + appx + LAD Programs + Steam + winget + Start menu) by category."""
+ t = _taxonomy(h)
+ cats = USER_CATS + ["other"]
+ all_counts = collections.Counter(v["category"] for v in t["all"])
+ user_counts = {c: sum(1 for v in t["user"] if v["category"] == c) for c in cats}
+ names = {c: sorted(v["name"] for v in t["user"] if v["category"] == c)[:60] for c in cats}
+ return {"present": True, "unique_all": len(t["all"]), "unique_user_facing": len(t["user"]),
+ "counts_all": dict(all_counts.most_common()), "counts_user_facing": user_counts, "names": names}
+
+
+@probe(id="apps.taxonomy_user_added", level="L2", family=APPS, tier="T0", collect="core", gate="apps.uninstall")
+def apps_taxonomy_user_added(h, facts):
+ """Category counts of apps the user added (not provisioned, not dated before the profile existed)."""
+ t = _taxonomy(h)
+ cats = USER_CATS + ["other"]
+ added = [v for v in t["user"] if not v["pre"]]
+ months = collections.Counter(v["date"][:7] for v in added if v["date"])
+ return {"present": True, "profile_created": t["profile_created"], "image_date": t["image_date"],
+ "user_added_total": len(added), "preinstalled_total": len(t["user"]) - len(added),
+ "counts": {c: sum(1 for v in added if v["category"] == c) for c in cats},
+ "by_month": dict(sorted(months.items())), "undated": sum(1 for v in added if not v["date"])}
+
+
+@probe(id="apps.vendor_software", level="L2", family=APPS, tier="T0", collect="core", gate="apps.uninstall")
+def apps_vendor_software(h, facts):
+ """Hardware-vendor utilities (ASUS, NVIDIA, MSI, Realtek, Logitech...) from the uninstall inventory."""
+ items = [i for i in _uninstall(h)["items"] if i["category"] == "hardware_vendor"]
+ a = _appx(h)
+ appx = [i["name"] for i in (a or {}).get("items", []) if i["category"] == "hardware_vendor"]
+ pubs = collections.Counter((i["publisher"] or "?").split(",")[0].strip() for i in items)
+ return {"present": bool(items or appx), "uninstall_count": len(items), "appx_count": len(appx),
+ "publishers": dict(pubs.most_common(10)),
+ "names": sorted({i["name"] for i in items})[:80], "appx_names": sorted(appx)[:40]}
+
+
+@probe(id="oem.ai_preloads", level="L1", family=APPS, tier="T0", collect="core")
+def oem_ai_preloads(h, facts):
+ """OEM-shipped AI apps (ASUS AI Image Agent, AI framework services...). Must not count toward AI-user score."""
+ rx = r"AI Image Agent|Translate Agent|AIFramework|AI ?Creator|StoryCube|Virtual Assistant|AI Noise|Dell Optimizer|HP AI|Lenovo AI|Galaxy AI|MyASUS AI"
+ items = [{"name": i["name"], "version": i["version"], "install_date": i["install_date"]}
+ for i in _uninst_match(h, rx)]
+ dirs = [p for p in (os.path.join(_PF(), "ASUS", "AICreator_n1x"),) if _isdir(p)]
+ return {"present": bool(items or dirs), "items": items, "asus_aicreator_dir": bool(dirs)}
+
+
+_PROC_INTEREST = re.compile(r"claude|codex|hermes|ollama|lm ?studio|^lms|cursor|windsurf|copilot|gemini|opencode|aider|cua|agent-browser|chatgpt|nvidia app|broadcast|docker|discord|onedrive|steam|slack|teams|code\.exe|brave|chrome|msedge|firefox|tailscale|obs|spotify", re.I)
+
+
+@probe(id="proc.snapshot", level="L1", family=APPS, tier="T1", collect="core")
+def proc_snapshot(h, facts):
+ """Toolhelp32 process snapshot: total count, top process names, running agents and apps."""
+ p = _procs(h)
+ if not p:
+ return None
+ interest = {k: v for k, v in p.items() if _PROC_INTEREST.search(k)}
+ return {"present": True, "total": sum(p.values()), "distinct": len(p),
+ "top": dict(p.most_common(20)), "interesting": dict(sorted(interest.items()))}
+
+
+@probe(id="apps.services_nonms", level="L2", family=APPS, tier="T0", collect="extended", gate="apps.uninstall",
+ timeout_ms=4000)
+def apps_services_nonms(h, facts):
+ """Non-Microsoft Win32 services (ImagePath CompanyName), per-user instances skipped."""
+ k = _open(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services")
+ if k is None:
+ return None
+ windir = os.environ.get("SystemRoot", r"C:\Windows").lower()
+ start_map = {0: "boot", 1: "system", 2: "auto", 3: "manual", 4: "disabled"}
+ total, items = 0, []
+ for sk in _subkeys(k, 3000):
+ try:
+ s = winreg.OpenKey(k, sk)
+ except OSError:
+ continue
+ with s:
+ typ = _rv(s, "Type") or 0
+ if not (typ & 0x30) or typ & 0x80 or re.search(r"_[0-9a-f]{4,}$", sk, re.I):
+ continue
+ total += 1
+ exe = _exe_from_cmd(_rv(s, "ImagePath"))
+ if not exe:
+ continue
+ comp = _company(exe)
+ if exe.lower().startswith(windir) and (comp is None or "microsoft" in comp.lower()):
+ continue
+ dn = _rv(s, "DisplayName") or sk
+ if isinstance(dn, str) and dn.startswith("@"):
+ dn = sk
+ items.append({"name": sk, "display": dn, "company": comp, "start": start_map.get(_rv(s, "Start")),
+ "ms_outside_windir": bool(comp and "microsoft" in comp.lower()),
+ "category": _classify(f"{sk} {dn} {comp or ''}")})
+ by_co = collections.Counter((i["company"] or "?") for i in items)
+ return {"present": True, "win32_services": total, "non_ms": len(items),
+ "auto": sum(1 for i in items if i["start"] == "auto"), "by_company": dict(by_co.most_common(15)),
+ "items": items}
+
+
+@probe(id="apps.winget_db", level="L2", family=APPS, tier="T0", collect="extended", gate="apps.uninstall")
+def apps_winget_db(h, facts):
+ """winget installed.db (copied): packages winget installed, with install date and arch."""
+ w = _winget(h)
+ if not w or "items" not in w:
+ return w
+ items = w["items"]
+ return {"present": True, "count": len(items),
+ "by_day": dict(collections.Counter(i["installed"] for i in items if i["installed"]).most_common(10)),
+ "by_arch": dict(collections.Counter(i["arch"] or "?" for i in items)),
+ "pinned": sum(1 for i in items if i["pinned"]),
+ "items": [{k: i[k] for k in ("id", "version", "arch", "installed", "category")} for i in items]}
+
+
+@probe(id="tasks.nonms", level="L2", family=APPS, tier="T2", collect="extended", gate="apps.uninstall",
+ needs_admin=True, timeout_ms=4000)
+def tasks_nonms(h, facts):
+ """Scheduled task XML outside \\Microsoft (admin); operator-lab tasks counted but excluded."""
+ import xml.etree.ElementTree as ET
+ root = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "Tasks")
+ if not os.access(root, os.R_OK):
+ return None
+ ns = "{http://schemas.microsoft.com/windows/2004/02/mit/task}"
+ total = ms = op = errors = 0
+ items = []
+ for dp, dns, fns in os.walk(root):
+ rel = os.path.relpath(dp, root)
+ if rel.count(os.sep) >= 4:
+ dns[:] = []
+ is_ms = rel.lower().startswith("microsoft")
+ for f in fns:
+ total += 1
+ if total > 3000:
+ break
+ if is_ms:
+ ms += 1; continue
+ if OPERATOR_TASK_RE.match(f):
+ op += 1; continue
+ p = os.path.join(dp, f)
+ try:
+ with open(p, "rb") as fh:
+ raw = fh.read(200_000)
+ enc = "utf-16" if raw[:2] in (b"\xff\xfe", b"\xfe\xff") else "utf-8"
+ x = ET.fromstring(raw.decode(enc, "replace").lstrip("\ufeff").encode("utf-8")
+ .replace(b'encoding="UTF-16"', b""))
+ except Exception:
+ errors += 1; continue
+ ri = x.find(ns + "RegistrationInfo")
+ author = ri.findtext(ns + "Author") if ri is not None else None
+ en = x.find(f"{ns}Settings/{ns}Enabled")
+ enabled = (en.text.strip().lower() == "true") if en is not None and en.text else True
+ cmds = [e.findtext(ns + "Command") for e in x.iter(ns + "Exec")]
+ exe = _exe_from_cmd(cmds[0]) if cmds and cmds[0] else None
+ trig = x.find(ns + "Triggers")
+ name = f if rel == "." else os.path.join(rel, f)
+ items.append({"task": name, "enabled": enabled, "exe": os.path.basename(exe) if exe else None,
+ "company": _company(exe), "author_is_account": bool(author and "\\" in author),
+ "triggers": sorted({t.tag.replace(ns, "") for t in trig}) if trig is not None else [],
+ "category": _classify(f"{name} {exe or ''}")})
+ return {"present": True, "total_task_files": total, "microsoft_folder": ms, "operator_lab_excluded": op,
+ "non_ms": len(items), "parse_errors": errors, "items": items}
+
+
+@probe(id="apps.winget_cli", level="L2", family=APPS, tier="T0", collect="deep", gate="apps.uninstall",
+ timeout_ms=30000)
+def apps_winget_cli(h, facts):
+ """`winget list` row counts by source (2-18 s; deep only)."""
+ exe = _which("winget")
+ if not exe:
+ return None
+ rc, txt, ms = _spawn([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:
+ return {"present": False, "rc": rc}
+ col = lines[hdr].find("Source")
+ by = collections.Counter()
+ for l in lines[hdr + 2:]:
+ s = l[col:].strip() if col > 0 and len(l) > col else ""
+ by[s or "(none)"] += 1
+ return {"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/browser_files.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/browser_files.py
new file mode 100644
index 00000000000..01e07562d63
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/browser_files.py
@@ -0,0 +1,2126 @@
+"""Browser, comms/work and files probes (families: browser, comms_work, files).
+
+Ids follow reports/14-triage.json. Sources are the user's own browser profiles, Explorer registry keys
+and known folders. Output is counts, histograms and category totals; content-derived values (search
+terms, named domains, repo names, work hostnames, profile-root dir names) are tier T2. Cookies,
+Login Data, Web Data and token stores are only stat'ed (h.meta), never opened.
+
+Several probes share one expensive read (History copies, the known-folder walk). The first probe that
+needs it computes it under a lock and caches it on the HostAccess object; the others read the cache.
+"""
+from __future__ import annotations
+
+import collections
+import configparser
+import datetime as dt
+import glob
+import json
+import os
+import re
+import shutil
+import sqlite3
+import statistics
+import threading
+import time
+import urllib.parse
+
+from userscan.registry import REGISTRY, probe
+
+WEBKIT_OFFSET = 11644473600
+FT_OFFSET = 116444736000000000
+
+# Operator (lab) noise. ROOT applies to names directly under the profile root (side homes, scratch dirs);
+# DEEP applies at any depth and only lists names that are never the user's own.
+OPERATOR_RX = re.compile(r"^(hn-e2e|ns960|ns923.*|lhm|shots|user-insights-lab|userscan.*|\.?hermes-.*)$", re.I)
+OPERATOR_DEEP_RX = re.compile(r"(hn-e2e|ns960|ns923|user-insights-lab|userscan-)", re.I)
+
+HKCU_EXPLORER = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer"
+
+
+def _probe(id, **kw):
+ """Register unless another spec module already owns the id (first registration wins)."""
+ if id in REGISTRY:
+ return lambda fn: fn
+ return probe(id, **kw)
+
+
+# ---------------------------------------------------------------- shared helpers
+
+_GUARD = threading.Lock()
+
+
+def _cached(h, key, fn):
+ with _GUARD:
+ cache = h.__dict__.setdefault("_bf_cache", {})
+ locks = h.__dict__.setdefault("_bf_locks", {})
+ lock = locks.setdefault(key, threading.Lock())
+ with lock:
+ if key not in cache:
+ t = time.perf_counter()
+ try:
+ cache[key] = fn(h)
+ except Exception as e: # cache the failure so every dependent probe reports it once
+ cache[key] = {"__error__": f"{type(e).__name__}: {e}"}
+ cache.setdefault("_ms", {})[key] = round((time.perf_counter() - t) * 1000, 2)
+ v = cache[key]
+ if isinstance(v, dict) and "__error__" in v:
+ raise RuntimeError(v["__error__"])
+ return v
+
+
+def _cache_ms(h, key):
+ return h.__dict__.get("_bf_cache", {}).get("_ms", {}).get(key)
+
+
+def _env(name):
+ return os.environ.get(name, "")
+
+
+def _home():
+ return os.path.expanduser("~")
+
+
+def _redact(p):
+ if not p:
+ return p
+ home = _home()
+ if p.lower().startswith(home.lower()):
+ return "%USERPROFILE%" + p[len(home):]
+ return p
+
+
+def _isdir(p):
+ try:
+ return os.path.isdir(p)
+ except OSError:
+ return False
+
+
+def _load_json(p, max_bytes=16_000_000):
+ try:
+ if os.path.getsize(p) > max_bytes:
+ return None
+ with open(p, "r", encoding="utf-8", errors="replace") as f:
+ return json.load(f)
+ except Exception:
+ return None
+
+
+def _iso(ts):
+ try:
+ return dt.datetime.fromtimestamp(ts).isoformat(timespec="seconds") if ts else None
+ except (OSError, ValueError, OverflowError):
+ return None
+
+
+def _webkit_iso(v):
+ try:
+ v = int(v)
+ return _iso(v / 1e6 - WEBKIT_OFFSET) if v > 0 else None
+ except (TypeError, ValueError):
+ return None
+
+
+def _ft_iso(ft):
+ try:
+ ft = int(ft)
+ if FT_OFFSET < ft < 150000000000000000:
+ return _iso((ft - FT_OFFSET) / 1e7)
+ except (TypeError, ValueError):
+ pass
+ return None
+
+
+def _winreg():
+ import winreg
+ return winreg
+
+
+_ROOTS = {"HKLM": "HKEY_LOCAL_MACHINE", "HKCU": "HKEY_CURRENT_USER", "HKU": "HKEY_USERS"}
+
+
+def _reg_key(path):
+ wr = _winreg()
+ hive, _, sub = path.partition("\\")
+ return wr.OpenKey(getattr(wr, _ROOTS[hive]), sub, 0, wr.KEY_READ)
+
+
+def _reg_values(path, limit=2000):
+ """{name: value} for a key, or None if the key is missing."""
+ try:
+ k = _reg_key(path)
+ except OSError:
+ return None
+ out = {}
+ wr = _winreg()
+ with k:
+ for i in range(limit):
+ try:
+ n, v, _t = wr.EnumValue(k, i)
+ except OSError:
+ break
+ out[n] = v
+ return out
+
+
+def _reg_lastwrite(path):
+ try:
+ with _reg_key(path) as k:
+ return _ft_iso(_winreg().QueryInfoKey(k)[2])
+ except OSError:
+ return None
+
+
+def _age_bucket(age_s):
+ d = age_s / 86400
+ for lim, name in ((1, "lt_1d"), (7, "lt_7d"), (30, "lt_30d"), (90, "lt_90d"), (365, "lt_1y"), (730, "lt_2y")):
+ if d < lim:
+ return name
+ return "ge_2y"
+
+
+AGE_KEYS = ["lt_1d", "lt_7d", "lt_30d", "lt_90d", "lt_1y", "lt_2y", "ge_2y"]
+
+FILE_ATTRIBUTE_REPARSE_POINT = 0x400
+CLOUD_ATTRS = 0x400000 | 0x40000 | 0x1000 # RECALL_ON_DATA_ACCESS | RECALL_ON_OPEN | OFFLINE
+PLACEHOLDER_REPARSE_OK = 0x400000 | 0x40000 | 0x100000 | 0x80000
+
+
+def _walk(root, max_depth=6, max_entries=100000, budget_s=5.0, on_file=None, skip_dir=None):
+ """Bounded iterative walk: depth, entry and time caps. Skips non-cloud reparse points (junction loops)."""
+ t0 = time.perf_counter()
+ deadline = t0 + budget_s
+ st = {"files": 0, "dirs": 0, "bytes": 0, "entries": 0, "truncated": None, "depth": max_depth,
+ "cloud_placeholders": 0, "reparse_skipped": 0, "errors": 0}
+ if not _isdir(root):
+ st["root_exists"] = False
+ return st
+ stack = [(root, 0)]
+ while stack:
+ path, depth = stack.pop()
+ try:
+ it = os.scandir(path)
+ except OSError:
+ st["errors"] += 1
+ continue
+ with it:
+ for e in it:
+ st["entries"] += 1
+ if st["entries"] > max_entries:
+ st["truncated"] = "entries"
+ stack.clear()
+ break
+ if (st["entries"] & 511) == 0 and time.perf_counter() > deadline:
+ st["truncated"] = "time"
+ stack.clear()
+ break
+ try:
+ s = e.stat(follow_symlinks=False)
+ except OSError:
+ st["errors"] += 1
+ continue
+ attrs = getattr(s, "st_file_attributes", 0)
+ if attrs & FILE_ATTRIBUTE_REPARSE_POINT and not attrs & PLACEHOLDER_REPARSE_OK:
+ st["reparse_skipped"] += 1
+ continue
+ if e.is_dir(follow_symlinks=False):
+ if skip_dir and skip_dir(e.name, e.path):
+ continue
+ st["dirs"] += 1
+ if depth + 1 < max_depth:
+ stack.append((e.path, depth + 1))
+ else:
+ st["files"] += 1
+ st["bytes"] += s.st_size
+ if attrs & CLOUD_ATTRS:
+ st["cloud_placeholders"] += 1
+ if on_file:
+ on_file(e, s, depth)
+ st["ms"] = round((time.perf_counter() - t0) * 1000, 1)
+ return st
+
+
+# ---------------------------------------------------------------- browser catalog
+
+def _catalog_paths():
+ L, R, H = _env("LOCALAPPDATA"), _env("APPDATA"), _home()
+ chromium = [
+ ("brave", rf"{L}\BraveSoftware\Brave-Browser\User Data"),
+ ("edge", rf"{L}\Microsoft\Edge\User Data"),
+ ("chrome", rf"{L}\Google\Chrome\User Data"),
+ ("chrome_beta", rf"{L}\Google\Chrome Beta\User Data"),
+ ("chrome_dev", rf"{L}\Google\Chrome Dev\User Data"),
+ ("chrome_canary", rf"{L}\Google\Chrome SxS\User Data"),
+ ("chromium", rf"{L}\Chromium\User Data"),
+ ("edge_beta", rf"{L}\Microsoft\Edge Beta\User Data"),
+ ("edge_dev", rf"{L}\Microsoft\Edge Dev\User Data"),
+ ("edge_canary", rf"{L}\Microsoft\Edge SxS\User Data"),
+ ("brave_beta", rf"{L}\BraveSoftware\Brave-Browser-Beta\User Data"),
+ ("brave_nightly", rf"{L}\BraveSoftware\Brave-Browser-Nightly\User Data"),
+ ("vivaldi", rf"{L}\Vivaldi\User Data"),
+ ("opera", rf"{R}\Opera Software\Opera Stable"),
+ ("opera_gx", rf"{R}\Opera Software\Opera GX Stable"),
+ ("opera_air", rf"{R}\Opera Software\Opera Air Stable"),
+ ("arc", rf"{L}\Packages\TheBrowserCompany.Arc_*\LocalCache\Local\Arc\User Data"),
+ ("comet", rf"{L}\Perplexity\Comet\User Data"),
+ ("dia", rf"{L}\Dia\User Data"),
+ ("atlas", rf"{L}\OpenAI\Atlas\User Data"),
+ ("thorium", rf"{L}\Thorium\User Data"),
+ ("supermium", rf"{L}\Supermium\User Data"),
+ ("yandex", rf"{L}\Yandex\YandexBrowser\User Data"),
+ ("cent", rf"{L}\CentBrowser\User Data"),
+ ("epic", rf"{L}\Epic Privacy Browser\User Data"),
+ ("sidekick", rf"{L}\Sidekick\User Data"),
+ ("wavebox", rf"{L}\WaveboxApp\User Data"),
+ ]
+ gecko = [
+ ("firefox", rf"{R}\Mozilla\Firefox"),
+ ("zen", rf"{R}\zen"),
+ ("floorp", rf"{R}\Floorp"),
+ ("librewolf", rf"{R}\librewolf"),
+ ("waterfox", rf"{R}\Waterfox"),
+ ("tor", rf"{H}\Desktop\Tor Browser"),
+ ]
+ return chromium, gecko
+
+
+def _catalog(h):
+ chromium, gecko = _catalog_paths()
+ found_c, found_g = {}, {}
+ for bid, ud in chromium:
+ hits = glob.glob(ud) if "*" in ud else ([ud] if _isdir(ud) else [])
+ if hits:
+ found_c[bid] = hits[0]
+ for bid, root in gecko:
+ 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": len(chromium) + len(gecko)}
+
+
+def _profiles(h):
+ """[(browser_id, user_data, profile_dir, info_cache_entry)] for every chromium profile on disk."""
+ cat = _cached(h, "catalog", _catalog)
+ out = []
+ for bid, ud in cat["chromium"].items():
+ ls = _cached(h, "ls:" + bid, lambda _h, ud=ud: _load_json(os.path.join(ud, "Local State")) or {})
+ cache = ((ls.get("profile") or {}).get("info_cache") or {}) if isinstance(ls, dict) else {}
+ dirs = set(cache)
+ try:
+ for d in os.listdir(ud):
+ if (d == "Default" or d.startswith("Profile ")) and os.path.isfile(os.path.join(ud, d, "Preferences")):
+ dirs.add(d)
+ except OSError:
+ pass
+ if bid.startswith("opera"):
+ dirs = {""}
+ for d in sorted(dirs):
+ if d and not _isdir(os.path.join(ud, d)):
+ continue
+ out.append((bid, ud, d, cache.get(d, {}) if d else {}))
+ return out
+
+
+def _pkey(bid, pdir):
+ return f"{bid}:{pdir or 'root'}"
+
+
+# ---------------------------------------------------------------- domain categories
+
+DOMAIN_CATS = {
+ "ai": ["chatgpt.com", "openai.com", "claude.ai", "anthropic.com", "gemini.google.com", "perplexity.ai",
+ "huggingface.co", "nousresearch.com", "openrouter.ai", "grok.com", "x.ai", "mistral.ai", "deepseek.com",
+ "aistudio.google.com", "ollama.com", "replicate.com", "civitai.com", "lmarena.ai", "together.ai",
+ "groq.com", "fal.ai", "cursor.com", "copilot.microsoft.com", "notebooklm.google.com", "chat.qwen.ai",
+ "kimi.com", "z.ai", "moonshot.ai", "cerebras.ai", "entelligence.ai", "deepmind.google", "wisprflow.ai"],
+ "dev": ["github.com", "gitlab.com", "stackoverflow.com", "stackexchange.com", "npmjs.com", "pypi.org",
+ "docs.python.org", "developer.mozilla.org", "learn.microsoft.com", "vercel.com", "netlify.com",
+ "readthedocs.io", "docs.rs", "crates.io", "githubusercontent.com", "github.io", "go.dev",
+ "rust-lang.org", "nodejs.org", "docker.com", "cloudflare.com", "supabase.com", "railway.app", "fly.io",
+ "render.com", "linear.app", "sentry.io", "betterstack.com", "astral.sh", "nvidia.com", "tailscale.com",
+ "digitalocean.com", "aws.amazon.com", "console.cloud.google.com", "portal.azure.com", "localhost",
+ "127.0.0.1", "codeberg.org", "sourceforge.net", "jsdelivr.com", "unpkg.com", "regex101.com"],
+ "search": ["google.com", "bing.com", "duckduckgo.com", "search.brave.com", "kagi.com", "yandex.com",
+ "ecosia.org", "startpage.com"],
+ "social": ["x.com", "twitter.com", "reddit.com", "linkedin.com", "facebook.com", "instagram.com", "threads.net",
+ "bsky.app", "mastodon.social", "discord.com", "tiktok.com", "news.ycombinator.com", "t.co",
+ "whatsapp.com", "telegram.org", "quora.com"],
+ "video": ["youtube.com", "youtu.be", "twitch.tv", "netflix.com", "primevideo.com", "hotstar.com", "spotify.com",
+ "vimeo.com", "crunchyroll.com", "soundcloud.com", "music.youtube.com", "jiocinema.com",
+ "disneyplus.com", "kick.com"],
+ "gaming": ["steampowered.com", "steamcommunity.com", "epicgames.com", "nexusmods.com", "ign.com", "gamespot.com",
+ "pcgamingwiki.com", "protondb.com", "gog.com", "riotgames.com", "playvalorant.com",
+ "leagueoflegends.com", "fandom.com", "ea.com", "xbox.com", "playstation.com", "battle.net",
+ "howlongtobeat.com", "speedrun.com", "rockstargames.com", "curseforge.com", "modrinth.com",
+ "gta5-mods.com"],
+ "hardware": ["techpowerup.com", "tomshardware.com", "anandtech.com", "rtings.com", "pcpartpicker.com",
+ "asus.com", "msi.com", "intel.com", "amd.com", "geforce.com", "nvidia.in", "guru3d.com",
+ "overclock.net", "hwinfo.com", "testufo.com", "blurbusters.com", "displayspecifications.com"],
+ "shopping": ["amazon.in", "amazon.com", "flipkart.com", "ebay.com", "aliexpress.com", "myntra.com",
+ "bigbasket.com", "swiggy.com", "zomato.com", "blinkit.com", "zeptonow.com", "etsy.com",
+ "bestbuy.com", "newegg.com", "croma.com", "reliancedigital.in", "ajio.com", "nykaa.com"],
+ "productivity": ["mail.google.com", "gmail.com", "docs.google.com", "drive.google.com", "calendar.google.com",
+ "outlook.live.com", "outlook.office.com", "notion.so", "notion.site", "office.com",
+ "microsoft365.com", "onedrive.live.com", "dropbox.com", "figma.com", "slack.com", "zoom.us",
+ "meet.google.com", "teams.microsoft.com", "trello.com", "airtable.com", "miro.com", "canva.com",
+ "sheets.google.com", "box.com", "accounts.google.com", "myaccount.google.com"],
+ "news_reading": ["medium.com", "substack.com", "nytimes.com", "theverge.com", "arstechnica.com", "bbc.com",
+ "bbc.co.uk", "theguardian.com", "wikipedia.org", "arxiv.org", "techcrunch.com", "bloomberg.com",
+ "reuters.com", "thehindu.com", "indiatimes.com", "ndtv.com", "wired.com", "moneycontrol.com",
+ "livemint.com"],
+ "finance": ["zerodha.com", "groww.in", "paypal.com", "stripe.com", "hdfcbank.com", "icicibank.com", "sbi.co.in",
+ "coinbase.com", "binance.com", "tradingview.com", "wise.com", "paytm.com", "phonepe.com",
+ "razorpay.com", "incometax.gov.in"],
+ "travel": ["booking.com", "airbnb.com", "makemytrip.com", "goibibo.com", "expedia.com", "skyscanner.com",
+ "cleartrip.com", "irctc.co.in", "uber.com", "olacabs.com", "tripadvisor.com", "maps.google.com",
+ "agoda.com", "ixigo.com"],
+ "password_manager": ["bitwarden.com", "1password.com", "lastpass.com", "keepersecurity.com", "proton.me"],
+ "media_unofficial": ["1337x.to", "rarbgdump.com", "fmhy.net", "animepahe.pw", "animepahe.ru",
+ "fitgirl-repacks.site", "subtitlecat.com", "my-subs.co", "opensubtitles.org",
+ "thepiratebay.org", "nyaa.si", "yts.mx", "yts-official.biz", "pixeldrain.com"],
+}
+_SUFFIX = {d: c for c, ds in DOMAIN_CATS.items() for d in ds}
+# Hosts that are never named in any output (torrent, unofficial streaming, adult).
+SENSITIVE_RX = re.compile(r"(torrent|1337x|piratebay|yts|nyaa|rarbg|fitgirl|animepahe|anime|hentai|porn|xxx|xvideos|"
+ r"xnxx|onlyfans|nsfw|subtitle|my-subs|pixeldrain|\bsex)", re.I)
+SENSITIVE_CATS = {"media_unofficial", "adult"}
+
+
+def _categorize(host):
+ if not host:
+ return "other"
+ if "://" in host or host.endswith(":"):
+ return "local_file" if host.startswith("file") else "browser_internal"
+ if SENSITIVE_RX.search(host) and _SUFFIX.get(host) is None:
+ return "adult" if re.search(r"porn|xxx|xvideos|xnxx|onlyfans|hentai|nsfw|\bsex", host) else "media_unofficial"
+ parts = host.split(".")
+ for i in range(len(parts)):
+ c = _SUFFIX.get(".".join(parts[i:]))
+ if c:
+ return c
+ if host.endswith((".local", ".ts.net")) or re.match(r"^(10|192\.168|172\.(1[6-9]|2\d|3[01]))\.", host):
+ return "dev"
+ return "other"
+
+
+def _host_of(url):
+ try:
+ p = urllib.parse.urlsplit(url)
+ except ValueError:
+ return "?", None
+ if p.scheme in ("http", "https"):
+ hn = (p.hostname or "").lower()
+ return (hn[4:] if hn.startswith("www.") else hn), p
+ if p.scheme == "file":
+ return "file://", p
+ return (p.scheme + "://" + (p.hostname or "")) if p.scheme else "?", p
+
+
+SERVICES = {
+ "discord": r"(^|\.)discord\.com$", "slack": r"(^|\.)slack\.com$", "teams_work": r"^teams\.(microsoft|cloud\.microsoft)(\.com)?$",
+ "teams_personal": r"^teams\.live\.com$", "zoom": r"(^|\.)zoom\.us$", "google_meet": r"^meet\.google\.com$",
+ "whatsapp_web": r"^web\.whatsapp\.com$", "telegram_web": r"^web\.telegram\.org$", "gmail": r"^mail\.google\.com$",
+ "google_calendar": r"^calendar\.google\.com$", "outlook_personal": r"^outlook\.live\.com$",
+ "outlook_work": r"^outlook\.(office|office365|cloud\.microsoft)(\.com)?$", "proton_mail": r"^mail\.proton\.me$",
+ "notion": r"(^|\.)notion\.(so|site|com)$", "google_docs": r"^(docs|drive|sheets)\.google\.com$",
+ "office_web": r"(^|\.)(office\.com|microsoft365\.com|sharepoint\.com)$", "linear": r"^linear\.app$",
+ "github": r"^github\.com$", "figma": r"(^|\.)figma\.com$", "nousresearch": r"(^|\.)nousresearch\.com$",
+}
+_SVC_RX = [(k, re.compile(v)) for k, v in SERVICES.items()]
+WORK_HOST_SVCS = ("slack", "nousresearch", "discord", "notion", "linear")
+
+TERM_THEMES = {
+ "dev": ["error", "exception", "failed", "traceback", "npm", "pip", "python", "rust", "typescript", "javascript",
+ "node", "docker", "git", "github", "powershell", "wsl", "api", "sdk", "cli", "linux", "ssh", "regex",
+ "json", "sql", "cuda", "react", "electron", "vite", "compile", "build", "repo:"],
+ "ai": ["gpt", "claude", "llm", "openai", "anthropic", "gemini", "ollama", "hermes", "model", "agent", "llama",
+ "qwen", "deepseek", "mcp", "prompt", "diffusion", "comfyui", "lora", "nous", " ai "],
+ "gaming": ["game", "steam", "mod", "walkthrough", "boss", "elden", "cyberpunk", "witcher", "valorant", "forza",
+ "death stranding", "helldivers", "gta", "fps", "patch notes", "trophy", "achievement", "control",
+ "expedition 33", "arc raiders"],
+ "hardware": ["rtx", "gpu", "nvidia", "cpu", "ram", "ssd", "motherboard", "bios", "driver", "monitor",
+ "overclock", "undervolt", "psu", "5090", "14700k", "z790", "laptop", "arm64", "snapdragon", "switch"],
+ "shopping": ["buy", "price", "review", " vs ", "best ", "deal", "cheap", "discount", "amazon", "flipkart"],
+ "howto": ["how to", "how do", "what is", "why ", "tutorial", "guide", "example"],
+ "media": ["movie", "series", "episode", "season", "song", "lyrics", "trailer", "anime", "netflix", "youtube",
+ "watch", "cast", "ranked"],
+}
+SAFE_TERM = re.compile(r"^[\w\s\-\.\+#:'/?&,()]{2,60}$", re.UNICODE)
+
+
+def _themes(term):
+ t = " " + term.lower() + " "
+ return [k for k, ws in TERM_THEMES.items() if any(w in t for w in ws)] or ["other"]
+
+
+def _safe_term(term):
+ if not SAFE_TERM.match(term) or "@" in term or re.search(r"\d{6,}|[A-Za-z0-9_\-]{24,}", term):
+ return False
+ if re.search(r"(password|passwd|token|secret|api[_ ]?key|otp|login|aadhaar|pan card)", term, re.I):
+ return False
+ if SENSITIVE_RX.search(term) or re.search(r"\b(fuck\w*|shit\w*|nude\w*)\b", term, re.I):
+ return False
+ return True
+
+
+# Skill SQL (browser-insights/references/sql-queries.md): pages per day and site buckets, on the urls table.
+SQL_PAGES_PER_DAY = ("SELECT ROUND(CAST(COUNT(*) AS FLOAT) / COUNT(DISTINCT date(datetime((last_visit_time/1000000)"
+ "-11644473600, 'unixepoch', 'localtime'))), 1) FROM urls")
+SQL_SITE_BUCKETS = """SELECT CASE
+ WHEN url LIKE '%github.com%' THEN 'GitHub'
+ WHEN url LIKE '%google.com%' THEN 'Google'
+ WHEN url LIKE '%youtube.com%' THEN 'YouTube'
+ WHEN url LIKE '%twitter.com%' OR url LIKE '%x.com%' THEN 'Twitter/X'
+ WHEN url LIKE '%reddit.com%' THEN 'Reddit'
+ WHEN url LIKE '%linkedin.com%' THEN 'LinkedIn'
+ WHEN url LIKE '%stackoverflow.com%' THEN 'StackOverflow'
+ WHEN url LIKE '%chatgpt.com%' OR url LIKE '%openai.com%' THEN 'OpenAI/ChatGPT'
+ WHEN url LIKE '%claude.ai%' OR url LIKE '%anthropic.com%' THEN 'Claude/Anthropic'
+ WHEN url LIKE '%localhost%' OR url LIKE '%127.0.0.1%' THEN 'Localhost Dev'
+ WHEN url LIKE '%netflix.com%' THEN 'Netflix'
+ WHEN url LIKE '%spotify.com%' THEN 'Spotify'
+ WHEN url LIKE '%amazon.%' THEN 'Amazon'
+ ELSE 'Other' END AS site, COUNT(*) FROM urls GROUP BY site ORDER BY 2 DESC"""
+LT = f"datetime((visit_time/1000000)-{WEBKIT_OFFSET}, 'unixepoch', 'localtime')"
+MAX_VISIT_ROWS = 300000
+
+
+def _copy_db(h, src, tag):
+ """Copy a live SQLite DB plus -wal/-journal into h.scratch() under a unique name. (path, via, ms)."""
+ t = time.perf_counter()
+ dst = os.path.join(h.scratch(), re.sub(r"[^A-Za-z0-9_.-]", "_", tag))
+ via = "copy"
+ try:
+ shutil.copyfile(src, dst)
+ except OSError:
+ got, rung = h.copy_locked(src, os.path.basename(dst))
+ if not got:
+ return None, "failed", round((time.perf_counter() - t) * 1000, 2)
+ via = rung
+ for suf in ("-wal", "-journal"):
+ if os.path.exists(src + suf):
+ try:
+ shutil.copyfile(src + suf, dst + suf)
+ except OSError:
+ via += "+wal_locked"
+ return dst, via, round((time.perf_counter() - t) * 1000, 2)
+
+
+def _drop_db(dst):
+ for suf in ("", "-wal", "-journal", "-shm"):
+ try:
+ os.remove(dst + suf)
+ except OSError:
+ pass
+
+
+def _query_history(db):
+ """All aggregates for one Chromium History copy. Raw domain/term counters stay in memory only."""
+ con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
+ try:
+ cur = con.cursor()
+ tables = {r[0] for r in cur.execute("select name from sqlite_master where type='table'")}
+ r = {"urls": cur.execute("select count(*) from urls").fetchone()[0],
+ "visits": cur.execute("select count(*) from visits").fetchone()[0]}
+ mn, mx = cur.execute("select min(visit_time), max(visit_time) from visits").fetchone()
+ r["first_visit"], r["last_visit"] = _webkit_iso(mn), _webkit_iso(mx)
+ r["active_days"] = cur.execute(f"select count(distinct date({LT})) from visits").fetchone()[0]
+ r["visits_per_active_day"] = round(r["visits"] / r["active_days"], 1) if r["active_days"] else 0
+ try:
+ r["pages_per_day_urls"] = cur.execute(SQL_PAGES_PER_DAY).fetchone()[0]
+ except sqlite3.Error:
+ r["pages_per_day_urls"] = None
+ r["typed_urls"] = cur.execute("select count(*) from urls where typed_count>0").fetchone()[0]
+ hours = [0] * 24
+ for hr, c in cur.execute(f"select cast(strftime('%H',{LT}) as int), count(*) from visits group by 1"):
+ if hr is not None:
+ hours[int(hr)] = c
+ wd = [0] * 7
+ for d, c in cur.execute(f"select cast(strftime('%w',{LT}) as int), count(*) from visits group by 1"):
+ if d is not None:
+ wd[int(d)] = c
+ r["hours"], r["weekdays_sun0"] = hours, wd
+ r["months"] = {m: c for m, c in cur.execute(f"select strftime('%Y-%m',{LT}), count(*) from visits group by 1")}
+ b = cur.execute(f"select date({LT}) d, count(*) c from visits group by d order by c desc limit 1").fetchone()
+ r["busiest_day"] = {"date": b[0], "visits": b[1]} if b else None
+ try:
+ r["site_buckets"] = {s: c for s, c in cur.execute(SQL_SITE_BUCKETS)}
+ except sqlite3.Error:
+ r["site_buckets"] = {}
+ dom, cats = collections.Counter(), collections.Counter()
+ gh, ports = collections.Counter(), collections.Counter()
+ svc = {}
+ ids = {"discord_guilds": set(), "slack_workspaces": set(), "gmail_slots": set(), "linear_workspaces": set()}
+ work_hosts = {}
+ now = time.time()
+ for url, vt in cur.execute(f"select u.url, v.visit_time from visits v join urls u on u.id=v.url "
+ f"limit {MAX_VISIT_ROWS}"):
+ host, sp = _host_of(url or "")
+ dom[host] += 1
+ cats[_categorize(host)] += 1
+ if sp is None:
+ continue
+ if host == "github.com":
+ parts = sp.path.strip("/").split("/")
+ if len(parts) >= 2 and parts[0] not in ("settings", "notifications", "orgs", "search", "login",
+ "sessions", "marketplace", "features", "topics", "apps"):
+ gh[parts[0] + "/" + parts[1]] += 1
+ elif host in ("localhost", "127.0.0.1"):
+ try:
+ ports[sp.port or 80] += 1
+ except ValueError:
+ pass
+ for k, rx in _SVC_RX:
+ if rx.search(host):
+ t = (vt or 0) / 1e6 - WEBKIT_OFFSET
+ a = svc.setdefault(k, {"visits": 0, "days": set(), "last": 0, "visits_30d": 0})
+ a["visits"] += 1
+ a["days"].add(time.strftime("%Y-%m-%d", time.localtime(max(t, 0))))
+ a["last"] = max(a["last"], t)
+ if now - t < 30 * 86400:
+ a["visits_30d"] += 1
+ if k in WORK_HOST_SVCS:
+ work_hosts.setdefault(k, collections.Counter())[host] += 1
+ path = sp.path
+ m = k == "discord" and re.match(r"/channels/(\d{15,21})/", path)
+ if m:
+ ids["discord_guilds"].add(m.group(1))
+ m = k == "slack" and re.match(r"/client/(T[A-Z0-9]+)", path)
+ if m:
+ ids["slack_workspaces"].add(m.group(1))
+ m = k == "gmail" and re.match(r"/mail/u/(\d+)", path)
+ if m:
+ ids["gmail_slots"].add(m.group(1))
+ m = k == "linear" and re.match(r"/([a-z0-9-]+)/", path)
+ if m and m.group(1) not in ("login", "join", "settings", "invite"):
+ ids["linear_workspaces"].add(m.group(1))
+ break
+ r["_domains"], r["_categories"] = dom, cats
+ r["_github"], r["_ports"] = gh, ports
+ r["_services"] = {k: {"visits": v["visits"], "active_days": len(v["days"]), "visits_30d": v["visits_30d"],
+ "last": _iso(v["last"])} for k, v in svc.items()}
+ r["_ids"] = {k: len(v) for k, v in ids.items()}
+ r["_work_hosts"] = work_hosts
+ if "downloads" in tables:
+ exts = collections.Counter()
+ n = 0
+ for (tp,) in cur.execute("select target_path from downloads limit 50000"):
+ n += 1
+ e = os.path.splitext(tp or "")[1].lower()
+ exts[e if re.fullmatch(r"\.[a-z0-9]{1,6}", e or "") else "(other)"] += 1
+ r["downloads"] = {"count": n, "by_ext": dict(exts.most_common(10))}
+ if "keyword_search_terms" in tables:
+ terms, engines = collections.Counter(), collections.Counter()
+ for term, url in cur.execute("select k.term, u.url from keyword_search_terms k "
+ "left join urls u on u.id=k.url_id limit 50000"):
+ if term:
+ terms[term] += 1
+ engines[_host_of(url or "")[0]] += 1
+ r["_terms"], r["_engines"] = terms, engines
+ return r
+ finally:
+ con.close()
+
+
+def _history(h):
+ """{profile_key: aggregates} over every chromium profile History, plus per-profile copy timings."""
+ out = {}
+ for bid, ud, pdir, _info in _profiles(h):
+ src = os.path.join(ud, pdir, "History") if pdir else os.path.join(ud, "History")
+ if not os.path.isfile(src):
+ continue
+ key = _pkey(bid, pdir)
+ db, via, cms = _copy_db(h, src, f"hist_{key}")
+ row = {"browser": bid, "profile_dir": pdir or ".", "is_default_profile": pdir in ("Default", ""),
+ "bytes": os.path.getsize(src), "via": via, "copy_ms": cms}
+ if db:
+ t = time.perf_counter()
+ try:
+ row.update(_query_history(db))
+ except sqlite3.Error as e:
+ row["error"] = f"sqlite: {e}"
+ finally:
+ _drop_db(db)
+ row["query_ms"] = round((time.perf_counter() - t) * 1000, 2)
+ out[key] = row
+ return out
+
+
+def _gecko_history(h):
+ out = {}
+ cat = _cached(h, "catalog", _catalog)
+ for bid, root in cat["gecko"].items():
+ ini = os.path.join(root, "profiles.ini")
+ cp = configparser.ConfigParser()
+ try:
+ cp.read(ini, encoding="utf-8")
+ except (configparser.Error, OSError):
+ continue
+ for sec in cp.sections():
+ if not sec.startswith("Profile") or "Path" not in cp[sec]:
+ continue
+ p = cp[sec]["Path"]
+ pdir = os.path.join(root, p) if cp[sec].get("IsRelative", "1") == "1" else p
+ src = os.path.join(pdir, "places.sqlite")
+ if not os.path.isfile(src):
+ continue
+ key = f"{bid}:{sec}"
+ db, via, cms = _copy_db(h, src, f"places_{key}")
+ row = {"browser": bid, "via": via, "copy_ms": cms, "bytes": os.path.getsize(src)}
+ if db:
+ try:
+ con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
+ lt = "datetime(visit_date/1000000, 'unixepoch', 'localtime')"
+ row["visits"] = con.execute("select count(*) from moz_historyvisits").fetchone()[0]
+ row["urls"] = con.execute("select count(*) from moz_places").fetchone()[0]
+ mn, mx = con.execute("select min(visit_date), max(visit_date) from moz_historyvisits").fetchone()
+ row["first_visit"] = _iso((mn or 0) / 1e6)
+ row["last_visit"] = _iso((mx or 0) / 1e6)
+ row["active_days"] = con.execute(f"select count(distinct date({lt})) from moz_historyvisits").fetchone()[0]
+ hours = [0] * 24
+ for hr, c in con.execute(f"select cast(strftime('%H',{lt}) as int), count(*) from moz_historyvisits group by 1"):
+ if hr is not None:
+ hours[int(hr)] = c
+ row["hours"] = hours
+ cats = collections.Counter()
+ for (url,) in con.execute("select p.url from moz_historyvisits v join moz_places p on p.id=v.place_id "
+ f"limit {MAX_VISIT_ROWS}"):
+ cats[_categorize(_host_of(url or "")[0])] += 1
+ row["category_visits"] = dict(cats.most_common())
+ con.close()
+ except sqlite3.Error as e:
+ row["error"] = f"sqlite: {e}"
+ finally:
+ _drop_db(db)
+ out[key] = row
+ return out
+
+
+def _hist_rows(h):
+ return [r for r in _cached(h, "history", _history).values() if "visits" in r]
+
+
+def _public(r, keys):
+ return {k: r.get(k) for k in keys if k in r}
+
+
+# ================================================================ family: browser — L1
+
+@_probe(id="browser.brave.present", level="L1", family="browser", tier="T0", collect="core")
+def brave_present(h, facts):
+ """Brave user-data dir exists."""
+ m = h.meta(r"%LOCALAPPDATA%\BraveSoftware\Brave-Browser\User Data\Local State")
+ return {"present": _isdir(h.expand(r"%LOCALAPPDATA%\BraveSoftware\Brave-Browser\User Data")),
+ "local_state_mtime": _iso(m.get("mtime"))}
+
+
+@_probe(id="browser.edge.present", level="L1", family="browser", tier="T0", collect="core")
+def edge_present(h, facts):
+ """Edge user-data dir exists (Edge is preinstalled; presence is not use)."""
+ m = h.meta(r"%LOCALAPPDATA%\Microsoft\Edge\User Data\Local State")
+ return {"present": _isdir(h.expand(r"%LOCALAPPDATA%\Microsoft\Edge\User Data")),
+ "local_state_mtime": _iso(m.get("mtime"))}
+
+
+@_probe(id="browser.catalog", level="L1", family="browser", tier="T0", collect="core")
+def browser_catalog(h, facts):
+ """Which catalogued Chromium/Gecko browsers have a user-data root (33 path stats)."""
+ c = _cached(h, "catalog", _catalog)
+ return {"present": bool(c["chromium"] or c["gecko"]), "chromium": sorted(c["chromium"]),
+ "gecko": sorted(c["gecko"]), "checked": c["checked"]}
+
+
+PROGID_MAP = {"bravehtml": "brave", "bravepdf": "brave", "msedgehtm": "edge", "msedgepdf": "edge",
+ "chromehtml": "chrome", "firefoxurl": "firefox", "firefoxhtml": "firefox", "vivaldihtm": "vivaldi",
+ "operastable": "opera", "operagxstable": "opera_gx", "thoriumhtm": "thorium", "comethtml": "comet",
+ "zenhtml": "zen", "ie.http": "iexplore", "appxq0fevzme2pys62n3e0fbqa7peapykr8v": "edge_legacy"}
+
+
+def _progid(kind, name):
+ base = (rf"{HKCU_EXPLORER}\FileExts\{name}" if kind == "ext" else
+ rf"HKCU\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\{name}")
+ for sub in ("UserChoiceLatest", "UserChoice"):
+ v = _reg_values(base + "\\" + sub)
+ if v and v.get("ProgId"):
+ return v["ProgId"]
+ return None
+
+
+def _resolve_progid(pid):
+ p = (pid or "").lower()
+ hit = next((v for k, v in PROGID_MAP.items() if p.startswith(k)), None)
+ if hit:
+ return hit
+ if p.startswith("appx"):
+ v = _reg_values(rf"HKCU\Software\Classes\{pid}\Application") or {}
+ aumid = v.get("AppUserModelId") or v.get("AppUserModelID")
+ if not aumid:
+ try:
+ wr = _winreg()
+ with wr.OpenKey(wr.HKEY_CLASSES_ROOT, pid + r"\Application") as k:
+ aumid = wr.QueryValueEx(k, "AppUserModelID")[0]
+ except OSError:
+ aumid = None
+ if aumid:
+ return aumid.split("_")[0].split("!")[0]
+ return pid
+
+
+@_probe(id="browser.default", level="L1", family="browser", tier="T0", collect="core")
+def browser_default(h, facts):
+ """Default browser from UserChoice ProgId (http/https/.html/.pdf) and when it was set."""
+ got = {k: _progid(kind, n) for k, kind, n in (("http", "url", "http"), ("https", "url", "https"),
+ (".html", "ext", ".html"), (".pdf", "ext", ".pdf"))}
+ pid = got.get("https") or got.get("http")
+ if not pid:
+ return {"present": False}
+ set_at = _reg_lastwrite(r"HKCU\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice")
+ return {"present": True, "browser": _resolve_progid(pid), "prog_id": pid,
+ "handlers": {k: _resolve_progid(v) for k, v in got.items() if v}, "userchoice_set": set_at}
+
+
+@_probe(id="browser.registered", level="L1", family="browser", tier="T0", collect="core")
+def browser_registered(h, facts):
+ """Browsers registered with Windows (StartMenuInternet + App Paths)."""
+ names = set()
+ for p in (r"HKLM\SOFTWARE\Clients\StartMenuInternet", r"HKCU\SOFTWARE\Clients\StartMenuInternet",
+ r"HKLM\SOFTWARE\WOW6432Node\Clients\StartMenuInternet"):
+ names.update(h.reg(p) or [])
+ rx = re.compile(r"^(chrome|msedge|brave|firefox|vivaldi|opera|launcher|comet|dia|thorium|zen|floorp|librewolf|"
+ r"waterfox|arc)\.exe$", re.I)
+ app_paths = sorted(k.lower() for k in (h.reg(r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths") or [])
+ if rx.match(k))
+ return {"present": bool(names or app_paths), "start_menu_internet": sorted(names), "app_paths": app_paths}
+
+
+@_probe(id="defaults.mailto_pdf_media", level="L1", family="browser", tier="T0", collect="core")
+def defaults_mailto_pdf_media(h, facts):
+ """Default handlers for mailto, PDF, video, audio and images."""
+ got = {"mailto": _progid("url", "mailto")}
+ for ext in (".pdf", ".mp4", ".mkv", ".mp3", ".jpg", ".png", ".txt", ".md", ".py"):
+ got[ext] = _progid("ext", ext)
+ got = {k: _resolve_progid(v) for k, v in got.items() if v}
+ return {"present": bool(got), "handlers": got}
+
+
+T3_FILES = ("Network\\Cookies", "Cookies", "Login Data", "Login Data For Account", "Web Data", "Account Web Data")
+
+
+@_probe(id="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."""
+ rows = {}
+ for bid, ud, pdir, _i in _profiles(h):
+ base = os.path.join(ud, pdir) if pdir else ud
+ sizes = {}
+ for f in T3_FILES:
+ m = h.meta(os.path.join(base, f))
+ if m.get("present"):
+ sizes[f.replace("Network\\", "")] = m["bytes"]
+ if sizes:
+ rows[_pkey(bid, pdir)] = sizes
+ return {"present": bool(rows), "profiles": rows}
+
+
+@_probe(id="browser.generic_sweep", level="L1", family="browser", tier="T0", collect="extended")
+def browser_generic_sweep(h, facts):
+ """Glob for Chromium forks not in the catalog (User Data dirs with Local State + Default)."""
+ known = {os.path.normcase(p) for p in _cached(h, "catalog", _catalog)["chromium"].values()}
+ L, R = _env("LOCALAPPDATA"), _env("APPDATA")
+ unknown = []
+ for pat in (rf"{L}\*\User Data\Local State", rf"{L}\*\*\User Data\Local State", rf"{R}\*\User Data\Local State"):
+ for p in glob.glob(pat)[:200]:
+ d = os.path.dirname(p)
+ if os.path.normcase(d) not in known and _isdir(os.path.join(d, "Default")) and not OPERATOR_DEEP_RX.search(d):
+ unknown.append(_redact(d))
+ return {"present": True, "unknown_forks": len(unknown), "roots": unknown[:10]}
+
+
+# ================================================================ family: browser — L2
+
+def _vkey(s):
+ return tuple(int(x) for x in s.split(".") if x.isdigit())
+
+
+def _installed_version(ud):
+ """Highest version dir under the browser's Application folder(s); 'Last Version' lags until next launch."""
+ rel = os.path.relpath(os.path.dirname(ud), _env("LOCALAPPDATA")) if ud.lower().startswith(
+ _env("LOCALAPPDATA").lower()) else None
+ if not rel or rel.startswith(".."):
+ return None
+ vers = []
+ for base in (_env("LOCALAPPDATA"), _env("ProgramFiles"), _env("ProgramFiles(x86)")):
+ app = os.path.join(base, rel, "Application")
+ try:
+ vers += [d for d in os.listdir(app) if re.fullmatch(r"\d+(\.\d+){2,3}", d)]
+ except OSError:
+ continue
+ return max(vers, key=_vkey) if vers else None
+
+
+@_probe(id="browser.local_state", level="L2", family="browser", tier="T0", collect="core", gate="browser.catalog")
+def browser_local_state(h, facts):
+ """Per-browser Local State: version, profile count, install date, last live, launch count."""
+ out = {}
+ for bid, ud in _cached(h, "catalog", _catalog)["chromium"].items():
+ ls = _cached(h, "ls:" + bid, lambda _h, ud=ud: _load_json(os.path.join(ud, "Local State")) or {})
+ if not isinstance(ls, dict):
+ continue
+ cache = (ls.get("profile") or {}).get("info_cache") or {}
+ un = ls.get("uninstall_metrics") or {}
+ stab = (ls.get("user_experience_metrics") or {}).get("stability") or {}
+ try:
+ with open(os.path.join(ud, "Last Version"), encoding="utf-8") as f:
+ lv = f.read().strip()[:40]
+ except OSError:
+ lv = None
+ inst = un.get("installation_date2")
+ out[bid] = {"version": lv, "installed_version": _installed_version(ud), "profiles": len(cache),
+ "custom_named_profiles": sum(1 for v in cache.values() if not v.get("is_using_default_name", True)),
+ "installation_date": _iso(int(inst)) if str(inst or "").isdigit() else None,
+ "launch_count": un.get("launch_count"),
+ "browser_last_live": _webkit_iso(stab.get("browser_last_live_timestamp"))}
+ return {"present": bool(out), "browsers": out}
+
+
+@_probe(id="browser.tab_stats", level="L2", family="browser", tier="T1", collect="core", gate="browser.catalog")
+def browser_tab_stats(h, facts):
+ """Max tabs per window, max windows (Local State tab_stats)."""
+ out = {}
+ for bid, ud in _cached(h, "catalog", _catalog)["chromium"].items():
+ ls = _cached(h, "ls:" + bid, lambda _h, ud=ud: _load_json(os.path.join(ud, "Local State")) or {})
+ ts = (ls.get("tab_stats") or {}) if isinstance(ls, dict) else {}
+ vals = {k: v for k, v in ts.items() if isinstance(v, (int, float)) and not isinstance(v, bool)
+ and k in ("max_tabs_per_window", "total_tab_count_max", "window_count_max")}
+ if vals:
+ out[bid] = vals
+ return {"present": bool(out), "browsers": out}
+
+
+@_probe(id="browser.profile_prefs", level="L2", family="browser", tier="T0", collect="core", gate="browser.catalog")
+def browser_profile_prefs(h, facts):
+ """Per profile: creation time, created-by version, exit type, signed-in, sync requested, search provider."""
+ rows, signed = {}, 0
+ for bid, ud, pdir, info in _profiles(h):
+ p = os.path.join(ud, pdir, "Preferences") if pdir else os.path.join(ud, "Preferences")
+ pr = _load_json(p)
+ if not isinstance(pr, dict):
+ continue
+ prof = pr.get("profile") or {}
+ acct = len(pr.get("account_info") or [])
+ is_signed = bool(acct or info.get("gaia_id") or info.get("user_name"))
+ signed += is_signed
+ dsp = ((pr.get("default_search_provider_data") or {}).get("template_url_data") or {}).get("short_name")
+ rows[_pkey(bid, pdir)] = {
+ "default_profile": pdir in ("Default", ""),
+ "custom_name": info.get("is_using_default_name") is False,
+ "creation_time": _webkit_iso(prof.get("creation_time")),
+ "created_by_version": prof.get("created_by_version"),
+ "exit_type": prof.get("exit_type"),
+ "signed_in": is_signed,
+ "sync_requested": (pr.get("sync") or {}).get("requested"),
+ "default_search_provider": dsp,
+ }
+ return {"present": bool(rows), "profiles": len(rows), "signed_in_profiles": signed, "by_profile": rows}
+
+
+@_probe(id="browser.extensions", level="L2", family="browser", tier="T0", collect="core", gate="browser.catalog")
+def browser_extensions(h, facts):
+ """Extension counts per profile; names only for user-installed ones (location 1 webstore / 4 unpacked)."""
+ rows, user_names = {}, []
+ for bid, ud, pdir, _i in _profiles(h):
+ base = os.path.join(ud, pdir) if pdir else ud
+ settings = {}
+ for src in ("Secure Preferences", "Preferences"):
+ j = _load_json(os.path.join(base, src))
+ if isinstance(j, dict):
+ settings.update(((j.get("extensions") or {}).get("settings")) or {})
+ on_disk = [e for e in h.list_dir(os.path.join(base, "Extensions"), 300) if e != "Temp"]
+ user = [k for k, v in settings.items() if isinstance(v, dict) and v.get("location") in (1, 4)]
+ for eid in user[:30]:
+ name = None
+ vers = sorted(h.list_dir(os.path.join(base, "Extensions", eid), 20))
+ if vers:
+ man = _load_json(os.path.join(base, "Extensions", eid, vers[-1], "manifest.json")) or {}
+ name = man.get("name") if isinstance(man, dict) else None
+ if isinstance(name, str) and name.startswith("__MSG_"):
+ key = name[6:-2].lower()
+ for loc in ((man.get("default_locale") or "en"), "en", "en_US"):
+ msgs = _load_json(os.path.join(base, "Extensions", eid, vers[-1], "_locales", loc,
+ "messages.json")) or {}
+ hit = next((v.get("message") for k, v in msgs.items()
+ if k.lower() == key and isinstance(v, dict)), None) if isinstance(msgs, dict) else None
+ if hit:
+ name = hit
+ break
+ user_names.append(name or (settings[eid].get("manifest") or {}).get("name") or eid)
+ rows[_pkey(bid, pdir)] = {"on_disk": len(on_disk), "settings_entries": len(settings), "user_installed": len(user)}
+ return {"present": bool(rows), "user_installed": len(user_names), "user_installed_names": sorted(set(user_names)),
+ "by_profile": rows}
+
+
+@_probe(id="browser.bookmarks", level="L2", family="browser", tier="T1", collect="core", gate="browser.catalog")
+def browser_bookmarks(h, facts):
+ """Bookmark counts per profile and by URL category (no titles or URLs)."""
+ rows, total, cats = {}, 0, collections.Counter()
+ for bid, ud, pdir, _i in _profiles(h):
+ bm = _load_json(os.path.join(ud, pdir, "Bookmarks") if pdir else os.path.join(ud, "Bookmarks"))
+ if not isinstance(bm, dict) or "roots" not in bm:
+ continue
+ cnt = {"urls": 0, "folders": 0}
+ stack = [(v, 0) for v in bm["roots"].values() if isinstance(v, dict)]
+ seen = 0
+ while stack and seen < 50000:
+ n, depth = stack.pop()
+ seen += 1
+ if n.get("type") == "url":
+ cnt["urls"] += 1
+ cats[_categorize(_host_of(n.get("url", ""))[0])] += 1
+ elif n.get("type") == "folder" and depth < 30:
+ if depth > 0:
+ cnt["folders"] += 1
+ stack.extend((c, depth + 1) for c in n.get("children", []) if isinstance(c, dict))
+ rows[_pkey(bid, pdir)] = cnt
+ total += cnt["urls"]
+ return {"present": True, "total": total, "by_profile": rows,
+ "by_category": {k: v for k, v in cats.items() if k not in SENSITIVE_CATS} |
+ ({"sensitive": sum(cats[c] for c in SENSITIVE_CATS)} if any(cats[c] for c in SENSITIVE_CATS) else {})}
+
+
+@_probe(id="browser.history.copy", level="L2", family="browser", tier="T1", collect="extended", gate="browser.catalog")
+def history_copy(h, facts):
+ """History DB copies (with -wal/-journal) per profile: size, copy rung, copy/query ms."""
+ hist = _cached(h, "history", _history)
+ rows = {k: _public(v, ("bytes", "via", "copy_ms", "query_ms", "error")) for k, v in hist.items()}
+ return {"present": bool(rows), "profiles": rows, "shared_block_ms": _cache_ms(h, "history")}
+
+
+@_probe(id="browser.history.stats", level="L2", family="browser", tier="T1", collect="extended", gate="browser.catalog")
+def history_stats(h, facts):
+ """Visits, URLs, first/last visit, active days, visits and pages per active day, per profile and total."""
+ rows = _hist_rows(h)
+ if not rows:
+ return {"present": False}
+ per = {}
+ by_browser = collections.Counter()
+ for r in rows:
+ k = _pkey(r["browser"], r["profile_dir"] if r["profile_dir"] != "." else "")
+ per[k] = _public(r, ("visits", "urls", "first_visit", "last_visit", "active_days", "visits_per_active_day",
+ "pages_per_day_urls", "typed_urls", "busiest_day"))
+ per[k]["default_profile"] = r["is_default_profile"]
+ eng = r.get("_engines")
+ if eng is not None:
+ terms = r.get("_terms") or {}
+ per[k]["searches"] = sum(terms.values())
+ per[k]["search_engines"] = dict(eng.most_common(3))
+ by_browser[r["browser"]] += r["visits"]
+ return {"present": True, "visits_total": sum(by_browser.values()), "by_browser": dict(by_browser.most_common()),
+ "by_profile": per}
+
+
+@_probe(id="browser.history.hour_weekday", level="L2", family="browser", tier="T1", collect="extended",
+ gate="browser.catalog")
+def history_hour_weekday(h, facts):
+ """Local-time hour (24) and weekday (Sun=0) visit histograms over all profiles, plus months."""
+ rows = _hist_rows(h) + list(_cached(h, "gecko_history", _gecko_history).values())
+ rows = [r for r in rows if r.get("hours")]
+ if not rows:
+ return {"present": False}
+ hours = [sum(r["hours"][i] for r in rows) for i in range(24)]
+ wd = [sum((r.get("weekdays_sun0") or [0] * 7)[i] for r in rows) for i in range(7)]
+ months = collections.Counter()
+ for r in rows:
+ months.update(r.get("months") or {})
+ tot = sum(hours) or 1
+ return {"present": True, "hours": hours, "weekdays_sun0": wd, "months": dict(sorted(months.items())),
+ "night_share_00_05": round(sum(hours[0:5]) / tot, 3),
+ "weekend_share": round((wd[0] + wd[6]) / (sum(wd) or 1), 3)}
+
+
+def _category_totals(h):
+ cats = collections.Counter()
+ for r in _hist_rows(h):
+ cats.update(r.get("_categories") or {})
+ for r in _cached(h, "gecko_history", _gecko_history).values():
+ cats.update(r.get("category_visits") or {})
+ return cats
+
+
+@_probe(id="browser.history.top_domains", level="L2", family="browser", tier="T1", collect="extended",
+ gate="browser.catalog")
+def history_top_domains(h, facts):
+ """Visit totals by site category (named domains are in browser.history.top_domains_named, T2)."""
+ cats = _category_totals(h)
+ if not cats:
+ return {"present": False}
+ sensitive = sum(cats.pop(c, 0) for c in list(SENSITIVE_CATS))
+ distinct = set()
+ for r in _hist_rows(h):
+ distinct.update((r.get("_domains") or {}).keys())
+ out = dict(cats.most_common())
+ if sensitive:
+ out["sensitive"] = sensitive
+ return {"present": True, "category_visits": out, "distinct_domains": len(distinct)}
+
+
+@_probe(id="browser.history.top_domains_named", level="L2", family="browser", tier="T2", collect="extended",
+ gate="browser.catalog")
+def history_top_domains_named(h, facts):
+ """Top domains (default profiles only, sensitive hosts never named), skill site buckets, comms services."""
+ rows = _hist_rows(h)
+ if not rows:
+ return {"present": False}
+ dom, buckets, svc = collections.Counter(), collections.Counter(), {}
+ for r in rows:
+ buckets.update(r.get("site_buckets") or {})
+ if not r["is_default_profile"]:
+ continue
+ for d, c in (r.get("_domains") or {}).items():
+ dom["(sensitive)" if _categorize(d) in SENSITIVE_CATS else d] += c
+ for k, v in (r.get("_services") or {}).items():
+ a = svc.setdefault(k, {"visits": 0, "active_days": 0, "visits_30d": 0, "last": None})
+ a["visits"] += v["visits"]
+ a["active_days"] += v["active_days"]
+ a["visits_30d"] += v["visits_30d"]
+ a["last"] = max(filter(None, (a["last"], v["last"])), default=None)
+ return {"present": True,
+ "top_domains": [{"domain": d, "visits": c, "category": _categorize(d)} for d, c in dom.most_common(15)],
+ "skill_site_buckets_urls": dict(buckets.most_common()),
+ "comms_services": dict(sorted(svc.items(), key=lambda x: -x[1]["visits"]))}
+
+
+@_probe(id="browser.history.localhost", level="L2", family="browser", tier="T1", collect="extended",
+ gate="browser.catalog")
+def history_localhost(h, facts):
+ """Visits to localhost/127.0.0.1 by port (dev servers, OAuth callbacks)."""
+ ports = collections.Counter()
+ for r in _hist_rows(h):
+ ports.update(r.get("_ports") or {})
+ if not ports:
+ return {"present": False}
+ return {"present": True, "visits": sum(ports.values()), "ports": {str(k): v for k, v in ports.most_common(10)}}
+
+
+@_probe(id="browser.history.downloads", level="L2", family="browser", tier="T1", collect="extended",
+ gate="browser.catalog")
+def history_downloads(h, facts):
+ """Browser download count by file extension."""
+ n, exts = 0, collections.Counter()
+ for r in _hist_rows(h):
+ d = r.get("downloads")
+ if d:
+ n += d["count"]
+ exts.update(d["by_ext"])
+ if not n:
+ return {"present": False}
+ return {"present": True, "count": n, "by_ext": dict(exts.most_common(10))}
+
+
+@_probe(id="browser.history.search_terms", level="L2", family="browser", tier="T2", collect="extended",
+ gate="browser.catalog")
+def history_search_terms(h, facts):
+ """Search count, engines, mean words, themes by distinct term, <= 5 filtered examples (default profiles)."""
+ terms, engines = collections.Counter(), collections.Counter()
+ rows_all = 0
+ for r in _hist_rows(h):
+ if r.get("_terms") is None:
+ continue
+ rows_all += sum(r["_terms"].values())
+ if r["is_default_profile"]:
+ terms.update(r["_terms"])
+ for e, c in (r.get("_engines") or {}).items():
+ engines["(sensitive)" if _categorize(e) in SENSITIVE_CATS else e] += c
+ if not rows_all:
+ return {"present": False}
+ themes = collections.Counter(t for term in terms for t in _themes(term))
+ return {"present": True, "rows": sum(terms.values()), "rows_all_profiles": rows_all, "distinct_terms": len(terms),
+ "engines": dict(engines.most_common(5)),
+ "avg_words": round(sum(len(t.split()) for t in terms) / len(terms), 2) if terms else 0,
+ "themes_distinct_terms": dict(themes.most_common()),
+ "examples": [t for t, _ in terms.most_common(80) if _safe_term(t)][:5]}
+
+
+@_probe(id="browser.history.github_repos", level="L2", family="browser", tier="T2", collect="extended",
+ gate="browser.catalog")
+def history_github_repos(h, facts):
+ """Distinct github.com owner/repo paths visited; top 5 names."""
+ gh = collections.Counter()
+ for r in _hist_rows(h):
+ gh.update(r.get("_github") or {})
+ if not gh:
+ return {"present": False}
+ return {"present": True, "distinct": len(gh), "top": [k for k, _ in gh.most_common(5)]}
+
+
+@_probe(id="browser.firefox.history", level="L2", family="browser", tier="T1", collect="extended",
+ gate="browser.catalog")
+def firefox_history(h, facts):
+ """Gecko (Firefox/Zen/Floorp/LibreWolf/Waterfox) places.sqlite visit stats and category totals."""
+ rows = _cached(h, "gecko_history", _gecko_history)
+ if not rows:
+ return {"present": False}
+ return {"present": True, "profiles": {k: {kk: vv for kk, vv in v.items() if kk != "hours"}
+ for k, v in rows.items()}}
+
+
+# L3-level browser rollups. derive.py reads these ids from facts, so they are probes over the shared cache.
+
+@_probe(id="l3.browser_category_share", level="L2", family="browser", tier="T1", collect="extended",
+ gate="browser.catalog")
+def l3_browser_category_share(h, facts):
+ """Share of visits per category (0..1), sensitive categories folded into one bucket."""
+ cats = _category_totals(h)
+ tot = sum(cats.values())
+ if not tot:
+ return {"present": False}
+ sens = sum(cats.pop(c, 0) for c in list(SENSITIVE_CATS))
+ if sens:
+ cats["sensitive"] = sens
+ return {"present": True, "visits": tot, "shares": {k: round(v / tot, 3) for k, v in cats.most_common()},
+ "password_manager_visits": cats.get("password_manager", 0)}
+
+
+@_probe(id="l3.primary_browser", level="L2", family="browser", tier="T1", collect="extended", gate="browser.catalog")
+def l3_primary_browser(h, facts):
+ """Browser with the most history visits; falls back to the default browser."""
+ by = collections.Counter()
+ for r in _hist_rows(h):
+ by[r["browser"]] += r["visits"]
+ for r in _cached(h, "gecko_history", _gecko_history).values():
+ by[r["browser"]] += r.get("visits", 0)
+ d = facts.get("browser.default") or {}
+ d = d.get("value") or {} if "value" in d else d
+ dflt = d.get("browser") if isinstance(d, dict) else None
+ if not by and not dflt:
+ return {"present": False}
+ primary = by.most_common(1)[0][0] if by and by.most_common(1)[0][1] > 0 else dflt
+ return {"present": True, "primary": primary, "visits_by_browser": dict(by.most_common()),
+ "matches_default": primary == dflt if dflt else None}
+
+
+@_probe(id="l3.browser_rhythm", level="L2", family="browser", tier="T1", collect="extended", gate="browser.catalog")
+def l3_browser_rhythm(h, facts):
+ """Night share (00-05), weekend share and top-3 peak hours from history visits."""
+ rows = [r for r in _hist_rows(h) if r.get("hours")]
+ if not rows:
+ return {"present": False}
+ hours = [sum(r["hours"][i] for r in rows) for i in range(24)]
+ wd = [sum(r["weekdays_sun0"][i] for r in rows) for i in range(7)]
+ tot = sum(hours) or 1
+ return {"present": True, "night_share_00_05": round(sum(hours[0:5]) / tot, 3),
+ "weekend_share": round((wd[0] + wd[6]) / (sum(wd) or 1), 3),
+ "peak_hours": sorted(range(24), key=lambda i: -hours[i])[:3]}
+
+
+@_probe(id="l3.browser_persona_hints", level="L2", family="browser", tier="T1", collect="extended",
+ gate="browser.catalog")
+def l3_browser_persona_hints(h, facts):
+ """Developer (dev+ai >= 20% of visits) and gamer (gaming >= 5%) hints from category shares."""
+ cats = _category_totals(h)
+ tot = sum(cats.values())
+ if not tot:
+ return {"present": False}
+ dev = (cats["dev"] + cats["ai"]) / tot
+ gam = cats["gaming"] / tot
+ 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/darwin_apps.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps.py
new file mode 100644
index 00000000000..f1e7c37cede
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_apps.py
@@ -0,0 +1,2594 @@
+"""macOS user-level probes: apps, ai_agents, dev, browser, comms_work, files, gaming, media.
+
+Registration only at import time. Signal ids match the Windows modules wherever macOS has a source, so derive.py
+rules fire unchanged. Where a Windows extractor is path-agnostic (Claude/Codex JSONL scans, Chromium History SQL,
+Steam VDF parsing, known-folder composition) this module primes the shared cache of that extractor with macOS
+paths and calls it, the same way linux_apps.py does.
+
+Scope is the invoking user's home plus world-readable system inventories (/Applications, Homebrew prefixes,
+/Library/LaunchAgents). Stores behind Transparency Consent and Control (Safari History.db, Messages chat.db, Notes
+NoteStore.sqlite, ~/.Trash, recent-document lists) need Full Disk Access for the process running the collector;
+without it the probe returns {"present": false, "needs_fda": true}. Credential files (cookies, Login Data,
+auth.json, .env, ~/.ssh keys) are stat'ed only.
+"""
+from __future__ import annotations
+
+import collections
+import ctypes
+import ctypes.util
+import datetime as dt
+import glob
+import json
+import os
+import plistlib
+import re
+import shutil
+import sqlite3
+import subprocess
+import 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
+
+MAC = "darwin"
+APPS, AI, DEV, BROWSER, COMMS, FILES, GAMING, MEDIA = (
+ "apps", "ai_agents", "dev", "browser", "comms_work", "files", "gaming", "media")
+MAC_EPOCH = 978307200 # 2001-01-01 UTC (Cocoa absolute time)
+
+
+# ------------------------------------------------------------------ registration helpers
+
+def _taken(id):
+ return any(q.id == id and q.os in (MAC, "any") for q in REGISTRY.values())
+
+
+def _mp(id, **kw):
+ """Register a macOS probe unless another module already registered this id for macOS."""
+ kw.setdefault("os", MAC)
+ if _taken(id):
+ return lambda fn: fn
+ return probe(id, **kw)
+
+
+def _win_meta(id):
+ return next((q for q in REGISTRY.values() if q.id == id and q.os == "windows"), None)
+
+
+def _mirror(id, fn, prime=None, **override):
+ """Register a macOS probe that primes a shared cache with macOS paths, then runs the Windows extractor fn."""
+ w = _win_meta(id)
+ meta = {"level": w.level, "family": w.family, "tier": w.tier, "collect": w.collect, "gate": w.gate,
+ "timeout_ms": w.timeout_ms} if w else {}
+ meta.update(override)
+
+ def run(h, facts):
+ if prime:
+ prime(h)
+ return fn(h, facts)
+ run.__name__ = getattr(fn, "__name__", id.replace(".", "_"))
+ run.__doc__ = (fn.__doc__ or "").strip() + " [macOS: shared extractor over macOS paths]"
+ _mp(id, **meta)(run)
+
+
+# ------------------------------------------------------------------ paths and small helpers
+
+def _U(h):
+ return ad._U(h) if h is not None else os.path.expanduser("~")
+
+
+def _AS(h, *p):
+ return os.path.join(_U(h), "Library", "Application Support", *p)
+
+
+def _LIB(h, *p):
+ return os.path.join(_U(h), "Library", *p)
+
+
+def _cfg(h, *p):
+ return os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.join(_U(h), ".config"), *p)
+
+
+def _data(h, *p):
+ return os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(_U(h), ".local", "share"), *p)
+
+
+def _cachedir(h, *p):
+ return os.path.join(_U(h), ".cache", *p)
+
+
+_isdir, _ls, _mtime, _iso, _read_json = ad._isdir, ad._ls, ad._mtime, ad._iso, ad._read_json
+
+
+def _ex(*paths):
+ return any(p and os.path.exists(p) for p in paths)
+
+
+def _first(*paths):
+ return next((p for p in paths if p and os.path.exists(p)), None)
+
+
+def _newest_mtime(paths):
+ best = 0
+ for p in paths:
+ try:
+ best = max(best, os.stat(p).st_mtime)
+ except OSError:
+ continue
+ return best or None
+
+
+def _day(ts):
+ try:
+ return dt.datetime.fromtimestamp(float(ts)).strftime("%Y-%m-%d") if ts else None
+ except (OSError, ValueError, OverflowError, TypeError):
+ return None
+
+
+def _birth(p):
+ try:
+ st = os.stat(p)
+ return getattr(st, "st_birthtime", None) or st.st_ctime
+ except OSError:
+ return None
+
+
+def _memo(h, name, fn):
+ return ad._memo(h, "mac:" + name, fn)
+
+
+def _fact(facts, id):
+ f = facts.get(id)
+ if isinstance(f, dict) and "status" in f and "value" in f:
+ return f["value"] if f.get("status") == "ok" else None
+ return f
+
+
+def _plist(p, maxb=20_000_000):
+ try:
+ if os.path.getsize(p) > maxb:
+ return None
+ with open(p, "rb") as f:
+ return plistlib.load(f)
+ except Exception:
+ return None
+
+
+def _readable(p):
+ try:
+ fd = os.open(p, os.O_RDONLY)
+ os.close(fd)
+ return True
+ except OSError:
+ return False
+
+
+def _fda_meta(p):
+ """presence + size + readable, contents never read. readable=false on an existing file means TCC (FDA)."""
+ try:
+ st = os.stat(p)
+ except OSError:
+ return {"present": False}
+ ok = _readable(p)
+ return {"present": True, "bytes": st.st_size, "mtime": _day(st.st_mtime), "readable": ok, "needs_fda": not ok}
+
+
+def _dir_readable(p):
+ try:
+ with os.scandir(p) as it:
+ next(it, None)
+ return True
+ except OSError:
+ return False
+
+
+def _extra_bins(h):
+ U = _U(h) if h is not None else os.path.expanduser("~")
+ return ["/opt/homebrew/bin", "/opt/homebrew/sbin", "/usr/local/bin", os.path.join(U, ".local", "bin"),
+ os.path.join(U, "bin"), os.path.join(U, ".bun", "bin"), os.path.join(U, ".cargo", "bin"),
+ os.path.join(U, "go", "bin"), os.path.join(U, ".deno", "bin"), os.path.join(U, ".npm-global", "bin"),
+ os.path.join(U, "Library", "pnpm"), os.path.join(U, ".volta", "bin"), os.path.join(U, ".hermes", "bin"),
+ os.path.join(U, ".nix-profile", "bin"), "/nix/var/nix/profiles/default/bin", os.path.join(U, ".lmstudio", "bin"),
+ os.path.join(U, ".rye", "shims"), os.path.join(U, ".pyenv", "shims"),
+ "/Applications/Docker.app/Contents/Resources/bin", os.path.join(U, ".orbstack", "bin")]
+
+
+def _which(h, name):
+ p = shutil.which(name)
+ if p:
+ return p
+ for d in _extra_bins(h):
+ c = os.path.join(d, name)
+ if os.path.isfile(c) and os.access(c, os.X_OK):
+ return c
+ return None
+
+
+def _spawn(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))
+ 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"))
+ 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)
+
+
+def _open_text(p, maxb=30_000_000):
+ try:
+ if os.path.getsize(p) > maxb:
+ return None
+ with open(p, encoding="utf-8", errors="replace") as f:
+ return f.read()
+ except OSError:
+ return None
+
+
+def _ro(path, sql, args=(), timeout=2.0):
+ """Read-only query on a live SQLite file (mode=ro). Used for large WAL databases where a copy costs seconds."""
+ con = sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=timeout)
+ try:
+ return con.execute(sql, args).fetchall()
+ finally:
+ con.close()
+
+
+_OP_TOP = re.compile(r"^(hn-e2e|ns960|ns923.*|lhm|shots|uil|user-insights-lab|userscan.*|\.?hermes-(?!agent$).+)$", re.I)
+_OP_DEEP = re.compile(r"(^|/)(user-insights-lab|userscan[^/]*|hn-e2e|ns960|ns923[^/]*)(/|$)", re.I)
+
+
+def _is_op(h, path):
+ """Operator (lab) noise: side homes and lab dirs directly under home, or lab dir names at any depth."""
+ U = _U(h).rstrip("/") + "/"
+ p = os.path.abspath(path)
+ if _OP_DEEP.search(p):
+ return True
+ if p.startswith(U):
+ first = p[len(U):].split("/", 1)[0]
+ return bool(first and _OP_TOP.match(first))
+ return False
+
+
+# ------------------------------------------------------------------ own-user process table
+
+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)
+ me = os.getuid()
+ names, total = collections.Counter(), 0
+ for line in txt.splitlines():
+ parts = line.strip().split(None, 1)
+ if len(parts) != 2 or not parts[0].isdigit():
+ continue
+ total += 1
+ if int(parts[0]) != me:
+ continue
+ comm = parts[1]
+ if comm.startswith("<defunct"):
+ continue
+ app = re.search(r"/([^/]+)\.app/Contents/MacOS/", comm)
+ n = app.group(1) if app else os.path.basename(comm).lstrip("-")
+ names[n[:40]] += 1
+ return {"names": names, "total_all_users": total}
+ return _memo(h, "procs", build)
+
+
+def _running(h, pattern):
+ rx = re.compile(pattern, re.I)
+ return {k: v for k, v in _procs(h)["names"].items() if rx.search(k)}
+
+
+# ================================================================== apps
+
+_LS_CAT = [("gaming", r"games"), ("dev", r"developer-tools"), ("creative", r"graphics-design|photography|video|music"),
+ ("comms", r"social-networking"), ("productivity", r"productivity|business|education|reference|finance"),
+ ("utilities", r"utilities")]
+
+
+def _cls(name, bundle_id="", ls_cat=""):
+ c = ad._classify(name, bundle_id, "")
+ if c != "other":
+ return c
+ for cat, rx in _LS_CAT:
+ if re.search(rx, ls_cat or ""):
+ return cat
+ return "other"
+
+
+def _app_roots(h):
+ return [("applications", "/Applications", 2), ("user_applications", os.path.join(_U(h), "Applications"), 2),
+ ("system", "/System/Applications", 2)]
+
+
+def _bundles(h):
+ """Every .app bundle under /Applications (depth 2), ~/Applications (depth 2) and /System/Applications:
+ Info.plist name, bundle id, version, category, Mac App Store receipt, and bundle birth time (install date)."""
+ def build():
+ out, seen = [], set()
+ for loc, root, depth in _app_roots(h):
+ stack = [(root, 0)]
+ while stack:
+ d, dep = stack.pop()
+ for n in _ls(d, 3000) or []:
+ p = os.path.join(d, n)
+ if n.endswith(".app"):
+ rp = os.path.realpath(p)
+ if rp in seen:
+ continue
+ seen.add(rp)
+ info = _plist(os.path.join(p, "Contents", "Info.plist"), 5_000_000) or {}
+ bid = str(info.get("CFBundleIdentifier") or "")
+ name = str(info.get("CFBundleDisplayName") or info.get("CFBundleName") or n[:-4])
+ b = _birth(p)
+ out.append({"name": n[:-4], "display": name, "bundle_id": bid,
+ "version": str(info.get("CFBundleShortVersionString") or info.get("CFBundleVersion") or "")[:30] or None,
+ "ls_category": str(info.get("LSApplicationCategoryType") or ""),
+ "mas": os.path.exists(os.path.join(p, "Contents", "_MASReceipt")),
+ "location": loc, "install_ts": b, "install_date": _day(b),
+ "apple": bid.startswith("com.apple."),
+ "arch_arm64": None, "path": p})
+ elif dep + 1 < depth and not n.startswith(".") and _isdir(p) and loc != "system":
+ stack.append((p, dep + 1))
+ for a in out:
+ a["category"] = _cls(a["name"], a["bundle_id"], a["ls_category"])
+ return out
+ return _memo(h, "bundles", build)
+
+
+def _brew_prefix():
+ for p in ("/opt/homebrew", "/usr/local"):
+ if os.path.isdir(os.path.join(p, "Cellar")) or os.path.isdir(os.path.join(p, "Caskroom")):
+ return p
+ return None
+
+
+def _brew(h):
+ """Homebrew formulae (Cellar + INSTALL_RECEIPT.json: install time, installed_on_request) and casks (Caskroom
+ dir birth time). Equals `brew list --formula` / `brew list --cask` without the ~1 s Ruby spawn."""
+ def build():
+ pre = _brew_prefix()
+ if not pre:
+ return None
+ formulae = []
+ cellar = os.path.join(pre, "Cellar")
+ for n in _ls(cellar, 3000) or []:
+ vers = sorted(_ls(os.path.join(cellar, n), 50) or [])
+ if not vers:
+ continue
+ rec = _read_json(os.path.join(cellar, n, vers[-1], "INSTALL_RECEIPT.json"), maxb=1_000_000) or {}
+ t = rec.get("time") if isinstance(rec, dict) else None
+ formulae.append({"name": n, "version": vers[-1], "on_request": bool(rec.get("installed_on_request")) if isinstance(rec, dict) else None,
+ "time": t if isinstance(t, (int, float)) else _birth(os.path.join(cellar, n))})
+ casks = []
+ room = os.path.join(pre, "Caskroom")
+ for n in _ls(room, 2000) or []:
+ if n.startswith("."):
+ continue
+ vers = [v for v in (_ls(os.path.join(room, n), 50) or []) if not v.startswith(".")]
+ casks.append({"name": n, "version": sorted(vers)[-1] if vers else None, "time": _birth(os.path.join(room, n))})
+ taps = glob.glob(os.path.join(pre, "Library", "Taps", "*", "*"))
+ return {"prefix": pre, "formulae": formulae, "casks": casks, "taps": len(taps)}
+ return _memo(h, "brew", build)
+
+
+def _taxonomy(h):
+ """User-facing inventory: app bundles (Apple and /System bundles = preinstalled), brew casks and on-request
+ formulae, ~/.local/bin AI CLIs."""
+ def build():
+ apps = {}
+
+ def add(name, cat, date, src, pre):
+ n = ad._norm(name)
+ if not n:
+ return
+ a = apps.setdefault(n, {"name": name, "category": cat, "date": None, "sources": set(), "pre": pre})
+ a["sources"].add(src)
+ a["pre"] = a["pre"] and pre
+ if cat != "other" and a["category"] == "other":
+ a["category"] = cat
+ if date and (not a["date"] or date < a["date"]):
+ a["date"] = date
+ for b in _bundles(h):
+ pre = b["location"] == "system" or (b["apple"] and not b["mas"])
+ add(b["name"], b["category"], None if pre else b["install_date"], "bundle_" + b["location"], pre)
+ br = _brew(h) or {"formulae": [], "casks": []}
+ for c in br["casks"]:
+ add(c["name"], _cls(c["name"]), _day(c["time"]), "brew_cask", False)
+ for f in br["formulae"]:
+ if f["on_request"]:
+ add(f["name"], _cls(f["name"]), _day(f["time"]), "brew_formula", False)
+ for nm in _ls(os.path.join(_U(h), ".local", "bin")) or []:
+ if nm.lower() in ("claude", "codex", "hermes", "ollama", "gemini", "aider", "goose", "opencode", "cua-driver",
+ "agent-browser", "copilot"):
+ add(nm, "ai", _day(_newest_mtime([os.path.join(_U(h), ".local", "bin", nm)])), "local_bin", False)
+ allv = list(apps.values())
+ user = [v for v in allv if v["category"] in ad.USER_CATS or v["category"] == "other"]
+ inst = _birth("/var/db/.AppleSetupDone")
+ return {"os_install": _day(inst), "all": allv, "user": user}
+ return _memo(h, "taxonomy", build)
+
+
+@_mp("apps.uninstall", level="L1", family=APPS, tier="T0", collect="core")
+def apps_uninstall(h, facts):
+ """App inventory: .app bundles in /Applications, ~/Applications, /System/Applications with bundle version,
+ install date (bundle birth time) and Mac App Store receipt. The macOS counterpart of the Uninstall keys."""
+ b = _bundles(h)
+ if not b:
+ return None
+ by_loc = collections.Counter(x["location"] for x in b)
+ return {"present": True, "listed": len(b), "by_location": dict(by_loc),
+ "with_install_date": sum(1 for x in b if x["install_date"]), "mas": sum(1 for x in b if x["mas"]),
+ "apple": sum(1 for x in b if x["apple"]),
+ "items": [{"name": x["name"], "publisher": x["bundle_id"], "version": x["version"],
+ "install_date": x["install_date"], "category": x["category"]}
+ for x in sorted(b, key=lambda x: x["name"].lower()) if x["location"] != "system"]}
+
+
+@_mp("apps.packages", level="L2", family=APPS, tier="T0", collect="core", gate="apps.uninstall")
+def apps_packages(h, facts):
+ """Homebrew: formula/cask counts, formulae installed on request, cask names, install events by month."""
+ br = _brew(h)
+ if not br:
+ return {"present": False}
+ req = sorted(f["name"] for f in br["formulae"] if f["on_request"])
+ months = collections.Counter(_day(x["time"])[:7] for x in br["formulae"] + br["casks"] if _day(x["time"]))
+ return {"present": True, "manager": "homebrew", "prefix": br["prefix"], "count": len(br["formulae"]),
+ "user_requested": len(req), "user_requested_names": req[:80], "casks": len(br["casks"]),
+ "cask_names": sorted(c["name"] for c in br["casks"])[:80], "taps": br["taps"],
+ "install_events_by_month": dict(sorted(months.items()))}
+
+
+@_mp("apps.taxonomy", level="L2", family=APPS, tier="T0", collect="core", gate="apps.uninstall")
+def apps_taxonomy(h, facts):
+ """Merged user-facing inventory (bundles + brew casks + on-request formulae + ~/.local/bin AI CLIs) by category."""
+ t = _taxonomy(h)
+ cats = ad.USER_CATS + ["other"]
+ return {"present": True, "unique_all": len(t["all"]), "unique_user_facing": len(t["user"]),
+ "counts_all": dict(collections.Counter(v["category"] for v in t["all"]).most_common()),
+ "counts_user_facing": {c: sum(1 for v in t["user"] if v["category"] == c) for c in cats},
+ "names": {c: sorted(v["name"] for v in t["user"] if v["category"] == c)[:60] for c in cats}}
+
+
+@_mp("apps.taxonomy_user_added", level="L2", family=APPS, tier="T0", collect="core", gate="apps.uninstall")
+def apps_taxonomy_user_added(h, facts):
+ """Category counts of apps the user added (not Apple-bundled, not in /System)."""
+ t = _taxonomy(h)
+ cats = ad.USER_CATS + ["other"]
+ added = [v for v in t["user"] if not v["pre"]]
+ months = collections.Counter(v["date"][:7] for v in added if v["date"])
+ return {"present": True, "profile_created": _day(_birth(_U(h))), "image_date": t["os_install"],
+ "user_added_total": len(added), "preinstalled_total": len(t["user"]) - len(added),
+ "counts": {c: sum(1 for v in added if v["category"] == c) for c in cats},
+ "by_month": dict(sorted(months.items())), "undated": sum(1 for v in added if not v["date"])}
+
+
+@_mp("apps.install_timeline", level="L2", family=APPS, tier="T0", collect="core", gate="apps.uninstall")
+def apps_install_timeline(h, facts):
+ """Month spread of user installs (bundle birth times, brew casks and on-request formulae)."""
+ t = _taxonomy(h)
+ months = collections.Counter(v["date"][:7] for v in t["user"] if not v["pre"] and v["date"])
+ before = sum(1 for v in t["user"] if not v["pre"] and v["date"] and t["os_install"] and v["date"] < t["os_install"])
+ return {"present": bool(months), "distinct_months": len(months), "by_month": dict(sorted(months.items())),
+ "first": min(months) if months else None, "last": max(months) if months else None,
+ "dated_before_os_install": before, "os_install": t["os_install"]}
+
+
+def _launchd_dir(p):
+ rows = []
+ for n in _ls(p, 1000) or []:
+ if n.endswith(".plist"):
+ rows.append(n[:-6])
+ return rows
+
+
+@_mp("apps.autostart", level="L1", family=APPS, tier="T0", collect="core")
+def apps_autostart(h, facts):
+ """launchd jobs: ~/Library/LaunchAgents, /Library/LaunchAgents, /Library/LaunchDaemons labels (file names only).
+ Login Items (BackgroundItems-v*.btm) are root-only and not read."""
+ user = _launchd_dir(_LIB(h, "LaunchAgents"))
+ op_rx = re.compile(r"hermes-|user-insights|userscan", re.I)
+ la = _launchd_dir("/Library/LaunchAgents")
+ ld = _launchd_dir("/Library/LaunchDaemons")
+ vendors = collections.Counter(".".join(x.split(".")[:2]) for x in la + ld + user if not op_rx.search(x))
+ return {"present": True, "user_agents": sorted(x for x in user if not op_rx.search(x))[:40],
+ "user_agents_operator": sum(1 for x in user if op_rx.search(x)),
+ "system_agents": len(la), "system_daemons": len(ld), "vendors_top": dict(vendors.most_common(12))}
+
+
+_PROC_INTEREST = re.compile(r"claude|codex|hermes|ollama|lm ?studio|cursor|windsurf|copilot|gemini|opencode|aider|cua|"
+ r"agent-browser|docker|orbstack|discord|steam|slack|teams|^code$|electron|brave|chrome|firefox|"
+ r"safari|dia|arc|tailscale|obs|spotify|tmux|zellij|node|bun|python|signal|telegram|zoom|"
+ r"whatsapp|zed|ghostty|cmux|warp|iterm|raycast", re.I)
+
+
+@_mp("tasks.nonms", level="L2", family=APPS, tier="T2", collect="extended", gate="apps.uninstall", timeout_ms=3000)
+def tasks_nonms(h, facts):
+ """This user's scheduled jobs: `crontab -l` entry count and command names, user LaunchAgents with a
+ StartInterval/StartCalendarInterval; lab jobs counted separately."""
+ rc, txt, _ms = _spawn(["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(), 0
+ for j in jobs:
+ parts = j.split()
+ cmd = parts[5] if not j.startswith("@") and len(parts) > 5 else (parts[1] if len(parts) > 1 else "")
+ if _OP_DEEP.search(j) or re.search(r"hermes-|user-insights|uil/", j):
+ op += 1
+ continue
+ names[os.path.basename(cmd)[:40]] += 1
+ timed = []
+ for n in _launchd_dir(_LIB(h, "LaunchAgents")):
+ d = _plist(_LIB(h, "LaunchAgents", n + ".plist"), 200_000) or {}
+ if isinstance(d, dict) and ("StartInterval" in d or "StartCalendarInterval" in d):
+ if re.search(r"hermes-|user-insights|userscan", n):
+ op += 1
+ else:
+ timed.append(n)
+ if not jobs and not timed:
+ return {"present": False}
+ return {"present": True, "count": len(jobs) - op + len(timed), "cron_jobs": len(jobs),
+ "cron_commands": dict(names.most_common(10)), "timed_launch_agents": sorted(timed)[:20], "operator_lab_jobs": op}
+
+
+@_mp("proc.snapshot", level="L1", family=APPS, tier="T1", collect="core")
+def proc_snapshot(h, facts):
+ """`ps -axo uid=,comm=` for the invoking uid only: count, top executable names, running agents/apps."""
+ p = _procs(h)
+ n = p["names"]
+ if not n:
+ return None
+ return {"present": True, "total": sum(n.values()), "distinct": len(n), "top": dict(n.most_common(20)),
+ "interesting": dict(sorted((k, v) for k, v in n.items() if _PROC_INTEREST.search(k))),
+ "all_users_total": p["total_all_users"]}
+
+
+# ================================================================== ai_agents
+
+def _app(h, *names):
+ """First /Applications or ~/Applications bundle whose name matches one of names (case-insensitive)."""
+ want = [n.lower() for n in names]
+ for b in _bundles(h):
+ if b["name"].lower() in want:
+ return b
+ return None
+
+
+@_mp("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 have or lack (Cursor, Windsurf, Gemini CLI, opencode, LM Studio, ...)."""
+ U = _U(h)
+ cat = {
+ "cursor": [os.path.join(U, ".cursor"), _AS(h, "Cursor"), "/Applications/Cursor.app"],
+ "windsurf": [os.path.join(U, ".codeium"), os.path.join(U, ".windsurf"), _AS(h, "Windsurf"), "/Applications/Windsurf.app"],
+ "gemini_cli": [os.path.join(U, ".gemini")],
+ "opencode": [_data(h, "opencode"), _cfg(h, "opencode"), _AS(h, "ai.opencode.desktop")],
+ "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")],
+ "goose": [_cfg(h, "goose"), _AS(h, "Goose")], "amp": [_cfg(h, "amp")],
+ "chatgpt_desktop": ["/Applications/ChatGPT.app", _AS(h, "com.openai.chat")],
+ "chatgpt_atlas": ["/Applications/ChatGPT Atlas.app", _AS(h, "com.openai.atlas")],
+ "perplexity": ["/Applications/Perplexity.app", "/Applications/Comet.app"],
+ "lm_studio": [os.path.join(U, ".lmstudio"), _AS(h, "LM Studio"), "/Applications/LM Studio.app"],
+ "jan": [_AS(h, "Jan"), os.path.join(U, "jan")], "gpt4all": [_AS(h, "nomic.ai")],
+ "msty": [_AS(h, "Msty")], "anythingllm": [_AS(h, "anythingllm-desktop")],
+ "hf_hub": [_cachedir(h, "huggingface", "hub")], "llama_cpp": [_cachedir(h, "llama.cpp")],
+ "comfyui": [os.path.join(U, "ComfyUI"), _AS(h, "ComfyUI")], "llm_cli": [_AS(h, "io.datasette.llm")],
+ "repoprompt": [_AS(h, "RepoPrompt"), _AS(h, "com.pvncher.repoprompt")], "conductor": [_AS(h, "com.conductor.app")],
+ "wispr_flow": [_AS(h, "Wispr Flow")], "granola": [_AS(h, "Granola")], "grok": [_AS(h, "Grok Bot")],
+ "mini_swe_agent": [_AS(h, "mini-swe-agent")], "t3code": [_AS(h, "t3code")],
+ "apple_intelligence_models": ["/System/Library/AssetsV2/com_apple_MobileAsset_UAF_FM_GenerativeModels"],
+ }
+ found = {k: _ex(*v) for k, v in cat.items()}
+ hf_models = sum(1 for n in (_ls(_cachedir(h, "huggingface", "hub")) 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}
+
+
+def _npm_roots(h):
+ U = _U(h)
+ roots = [os.path.join(U, ".npm-global", "lib", "node_modules"), os.path.join(U, ".local", "lib", "node_modules"),
+ "/opt/homebrew/lib/node_modules", "/usr/local/lib/node_modules"]
+ roots += [os.path.join(d, "aliases", "default", "lib", "node_modules")
+ for d in (_data(h, "fnm"), _AS(h, "fnm"), os.path.join(U, ".fnm"))]
+ roots += glob.glob(_AS(h, "fnm", "node-versions", "*", "installation", "lib", "node_modules"))[:10]
+ roots += glob.glob(_data(h, "fnm", "node-versions", "*", "installation", "lib", "node_modules"))[:10]
+ roots += glob.glob(os.path.join(U, ".nvm", "versions", "node", "*", "lib", "node_modules"))[:10]
+ roots += glob.glob(os.path.join(U, ".volta", "tools", "image", "packages", "*", "lib", "node_modules"))[:20]
+ return [r for r in roots if _isdir(r)]
+
+
+def _npm_pkg(h, name):
+ for r in _npm_roots(h):
+ pj = _read_json(os.path.join(r, name, "package.json"))
+ if isinstance(pj, dict):
+ return {"root": "user" if r.startswith(_U(h)) else "system", "version": pj.get("version")}
+ return None
+
+
+@_mp("browser.automation", level="L1", family=AI, tier="T0", collect="core")
+def browser_automation(h, facts):
+ """Browser-automation runtimes on disk: Playwright, puppeteer, camoufox, agent-browser (npm or binary)."""
+ U = _U(h)
+ out = {}
+ for label, p in (("playwright_cache", _LIB(h, "Caches", "ms-playwright")), ("puppeteer", _cachedir(h, "puppeteer")),
+ ("camoufox", _LIB(h, "Caches", "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)}
+ ab = []
+ npm = _npm_pkg(h, "agent-browser")
+ if npm:
+ ab.append({"where": "npm_" + npm["root"], "version": npm["version"]})
+ exe = _which(h, "agent-browser")
+ if exe:
+ ab.append({"where": "binary", "path_kind": "user" if exe.startswith(U) else "system"})
+ if _isdir(os.path.join(U, ".agent-browser")):
+ out["agent_browser_home"] = {"mtime": _mtime(os.path.join(U, ".agent-browser"))}
+ if ab:
+ out["agent_browser"] = ab
+ return {"present": bool(out), **out}
+
+
+_mirror("browser_harness.present", ad.browser_harness_present)
+
+
+@_mp("claude_code.present", level="L1", family=AI, tier="T0", collect="core")
+def claude_code_present(h, facts):
+ """Claude Code CLI: ~/.claude home, native install (~/.local/bin/claude -> ~/.local/share/claude/versions),
+ npm global, Homebrew cask."""
+ U = _U(h)
+ home = os.path.join(U, ".claude")
+ link = os.path.join(U, ".local", "bin", "claude")
+ npm = _npm_pkg(h, "@anthropic-ai/claude-code")
+ cask = _isdir(os.path.join(_brew_prefix() or "/opt/homebrew", "Caskroom", "claude-code"))
+ if not (_isdir(home) or os.path.lexists(link) or npm or cask):
+ return None
+ ver = None
+ try:
+ ver = os.path.basename(os.readlink(link))
+ except OSError:
+ pass
+ vers = _ls(_data(h, "claude", "versions")) or []
+ return {"present": True, "home": _isdir(home), "native_exe": os.path.exists(link), "exe_version": ver,
+ "npm_install": bool(npm), "npm_version": (npm or {}).get("version"), "brew_cask": cask,
+ "installed_versions": len(vers), "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)
+
+
+@_mp("claude_desktop.present", level="L1", family=AI, tier="T0", collect="core")
+def claude_desktop_present(h, facts):
+ """Claude desktop app: bundle version, ~/Library/Application Support/Claude, MCP server names from its config."""
+ d = _AS(h, "Claude")
+ b = _app(h, "Claude")
+ if not (b or _isdir(d)):
+ return None
+ cfg = _read_json(os.path.join(d, "claude_desktop_config.json"))
+ return {"present": True, "installed": bool(b), "version": (b or {}).get("version"),
+ "install_date": (b or {}).get("install_date"), "data_mtime": _mtime(d),
+ "mcp_servers": sorted((cfg.get("mcpServers") or {}).keys()) if isinstance(cfg, dict) else [],
+ "claude_3p_dir": _isdir(_AS(h, "Claude-3p")), "running": sum(_running(h, r"^Claude$").values())}
+
+
+@_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)
+ npm = _npm_pkg(h, "@openai/codex")
+ exe = _which(h, "codex")
+ b = _app(h, "Codex")
+ if not (_isdir(home) or npm or exe or b):
+ return None
+ return {"present": True, "home": _isdir(home), "desktop_app": bool(b), "desktop_version": (b or {}).get("version"),
+ "npm_cli": bool(npm), "npm_version": (npm or {}).get("version"), "binary": bool(exe),
+ "home_mtime": _mtime(home)}
+
+
+@_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"))
+
+
+_mirror("codex.config", ad.codex_config)
+_TURN_MODEL = re.compile(rb'"model":"([^"]{1,60})"')
+_TURN_EFFORT = re.compile(rb'"(?:reasoning_)?effort":"([^"]{1,20})"')
+
+
+@_mp("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 from file names; turn models from a byte-level scan, newest files
+ first, 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)
+ 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, scanned, scanned_b = [], 0, 0, 0, 0
+ sized = []
+ for f in files:
+ try:
+ s = os.path.getsize(f)
+ except OSError:
+ continue
+ b += s
+ 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))
+ sized.append((m.group(1) if m else "", f, s))
+ deadline = time.perf_counter() + 2.5
+ for _d, f, s in sorted(sized, reverse=True):
+ if time.perf_counter() > deadline:
+ break
+ if s > 80_000_000:
+ continue
+ try:
+ with open(f, "rb") as fh:
+ for i, line in enumerate(fh):
+ head = line[:120]
+ if i == 0 and b'"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 b'"turn_context"' in head:
+ turns += 1
+ mm = _TURN_MODEL.search(line, 0, 4000)
+ me = _TURN_EFFORT.search(line, 0, 4000)
+ models[mm.group(1).decode() if mm else None] += 1
+ efforts[me.group(1).decode() if me else None] += 1
+ except OSError:
+ continue
+ scanned += 1
+ scanned_b += s
+ 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": ad._top(models),
+ "efforts": ad._top(efforts), "originators": ad._top(orig), "cli_versions": ad._top(clis, 5)},
+ "content_scan": {"files": scanned, "bytes": scanned_b, "complete": scanned == len(sized)}}
+ 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:
+ q = lambda sql: _ro(sdb[-1], sql)
+ try:
+ cs = {r[1] for r in q("pragma table_info(threads)")}
+ by_src = collections.Counter()
+ for (s,) in q("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("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("select model_provider, count(*) from threads group by 1")) if "model_provider" in cs else None,
+ "by_model": dict(q("select model, count(*) from threads group by 1")) if "model" in cs else None,
+ "tokens_used_total": q("select sum(tokens_used) from threads")[0][0] if "tokens_used" in cs else None}
+ try:
+ out["threads"]["subagent_edges"] = q("select count(*) from thread_spawn_edges")[0][0]
+ except sqlite3.Error:
+ pass
+ except sqlite3.Error as e:
+ out["threads"] = {"error": type(e).__name__}
+ th = sorted(glob.glob(os.path.join(home, "thread_history_*.sqlite")))
+ if th:
+ try:
+ out["turns"] = {"count": _ro(th[-1], "select count(*) from thread_turns")[0][0],
+ "agent_minutes": round((_ro(th[-1], "select sum(duration_ms) from thread_turns")[0][0] or 0) / 60000, 1),
+ "items": _ro(th[-1], "select count(*) from thread_items")[0][0]}
+ except sqlite3.Error as e:
+ 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)
+
+
+@_mp("cua_driver.present", level="L1", family=AI, tier="T0", collect="core")
+def cua_driver_present(h, facts):
+ """cua-driver (computer-use): ~/.cua-driver release dirs, binary on PATH, running."""
+ home = os.path.join(_U(h), ".cua-driver")
+ exe = _which(h, "cua-driver")
+ if not (_isdir(home) or exe):
+ 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, "binary": bool(exe), "releases": rel[-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"))}
+
+
+def _hermes_homes_mac(h):
+ env = h.l0.get("hermes_home") or os.environ.get("HERMES_HOME") or ""
+ U = _U(h)
+ cands = []
+ for role, p in (("HERMES_HOME", env), ("dot_hermes", os.path.join(U, ".hermes"))):
+ if p and _isdir(p) and all(os.path.realpath(p) != os.path.realpath(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) \
+ or (cands[0] if cands else None)
+ side = [p for p in glob.glob(os.path.join(U, ".hermes-*")) + glob.glob(os.path.join(U, "hermes-*")) if _isdir(p)][:50]
+ return {"env_set": bool(env), "cands": cands, "primary": primary, "side": side}
+
+
+def _prime_hermes(h):
+ ad._memo(h, "hermes_homes", lambda: _hermes_homes_mac(h))
+
+
+@_mp("hermes.present", level="L1", family=AI, tier="T0", collect="core")
+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)
+ 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 ad.tomllib and os.path.exists(pp):
+ try:
+ with open(pp, "rb") as f:
+ ver = ad.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")),
+ "profiles": len(_ls(os.path.join(p, "profiles")) or []), "cron_jobs": len(_ls(os.path.join(p, "cron")) or [])})
+ agents = sorted(n for n in _launchd_dir(_LIB(h, "LaunchAgents")) if "hermes" in n.lower() and not re.search(r"hermes-", n))
+ desktop = _app(h, "Hermes")
+ if not (homes or hh["side"] or agents or desktop or _which(h, "hermes")):
+ 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"]), "cli_on_path": bool(_which(h, "hermes")),
+ "launch_agents": agents, "desktop_app": bool(desktop), "desktop_version": (desktop or {}).get("version"),
+ "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)
+
+
+def _hermes_summary(path, titles=False):
+ """Aggregates from state.db opened read-only in place (mode=ro, no copy: the file can be several GB)."""
+ st = os.path.join(path, "state.db")
+ if not os.path.exists(st):
+ return None
+ q = lambda sql, args=(): _ro(st, sql, args, timeout=3.0)
+ cs = {r[1] for r in q("pragma table_info(sessions)")}
+ if titles:
+ if "title" not in cs:
+ return {"titles": []}
+ rows = q("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": [ad._redact(t) for (t,) in rows]}
+ a, z = q("select min(started_at), max(coalesce(ended_at, started_at)) from sessions")[0]
+ r = {"sessions": q("select count(*) from sessions")[0][0], "messages": q("select count(*) from messages")[0][0],
+ "first": _iso(a), "last": _iso(z),
+ "by_source": dict(q("select coalesce(source,'?'), count(*) from sessions group by 1")),
+ "by_month": dict(q("select strftime('%Y-%m', started_at, 'unixepoch'), count(*) from sessions group by 1")),
+ "by_model": dict(q("select coalesce(model,'?'), count(*) from sessions group by 1 order by 2 desc limit 10"))}
+ r["sessions_30d"] = q("select count(*) from sessions where started_at >= ?", (time.time() - 30 * 86400,))[0][0]
+ if "parent_session_id" in cs:
+ r["subagent_sessions"] = q("select count(*) from sessions where parent_session_id is not null")[0][0]
+ if "tool_call_count" in cs:
+ r["tool_calls"] = q("select sum(tool_call_count) from sessions")[0][0]
+ if "estimated_cost_usd" in cs:
+ r["est_cost_usd"] = q("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("select model, billing_provider, sum(api_call_count) from session_model_usage "
+ "group by 1,2 order by 3 desc limit 10")]
+ except sqlite3.Error:
+ pass
+ return r
+
+
+@_mp("hermes.usage", level="L2", family=AI, tier="T1", collect="extended", gate="hermes.present", timeout_ms=6000)
+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)
+ p = hh["primary"]
+ if not p:
+ return None
+ try:
+ r = _hermes_summary(p["path"])
+ except sqlite3.Error as e:
+ return {"present": True, "error": f"sqlite: {e}"}
+ if r is None:
+ return None
+ prof = []
+ for db in glob.glob(os.path.join(p["path"], "profiles", "*", "state.db"))[:20]:
+ try:
+ s = _hermes_summary(os.path.dirname(db)) or {}
+ except sqlite3.Error:
+ s = {}
+ prof.append({"sessions": s.get("sessions"), "first": s.get("first"), "last": s.get("last")})
+ return {"present": True, "home_role": p["role"], "via": "live_ro", **r, "profiles": prof,
+ "side_homes_excluded": len(hh["side"])}
+
+
+@_mp("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."""
+ _prime_hermes(h)
+ p = ad._hermes_homes(h)["primary"]
+ if not p:
+ return None
+ try:
+ r = _hermes_summary(p["path"], titles=True)
+ except sqlite3.Error:
+ return None
+ if not r or not r.get("titles"):
+ return None
+ return {"present": True, "recent": r["titles"]}
+
+
+@_mp("l3.mcp_inventory", level="L2", family=AI, tier="T0", collect="core", gate="ai.catalog_absent_checks")
+def l3_mcp_inventory(h, facts):
+ """Union of MCP server names across agents (Claude Code, Claude desktop, Codex, Hermes, VS Code, Cursor, ...)."""
+ _prime_hermes(h)
+ U = _U(h)
+ by = {}
+ cj = ad._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")
+ if ad.tomllib and os.path.exists(cp):
+ try:
+ with open(cp, "rb") as f:
+ by["codex"] = sorted((ad.tomllib.load(f).get("mcp_servers") or {}).keys())
+ except Exception:
+ pass
+ for label, path, keys in [("vscode", _AS(h, "Code", "User", "mcp.json"), ("servers", "mcpServers")),
+ ("claude_desktop", _AS(h, "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",)),
+ ("zed", _cfg(h, "zed", "settings.json"), ("context_servers",))]:
+ 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 = ad._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"]
+ except OSError:
+ pass
+ user = sorted({n for v in by.values() for n in v if n not in ad.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})}
+
+
+@_mp("ollama.present", level="L1", family=AI, tier="T0", collect="core")
+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)
+ if not (exe or b or _isdir(os.path.join(_U(h), ".ollama"))):
+ return None
+ return {"present": True, "app": bool(b), "version": (b or {}).get("version"), "install_date": (b or {}).get("install_date"),
+ "binary": bool(exe), "models_dir": _isdir(mroot), "OLLAMA_MODELS_set": bool(os.environ.get("OLLAMA_MODELS")),
+ "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))}
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.py
new file mode 100644
index 00000000000..665da85702d
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/darwin_system.py
@@ -0,0 +1,1501 @@
+"""macOS system-level probes (families: host, identity, install_age, locale, shell_prefs, security, network,
+hardware, health, usage).
+
+Ids match the Windows modules where macOS has a source for the same signal, so derive.py rules fire here too.
+Where macOS has no source the id is left unregistered (see tests/darwin-verify.md, UNIMPLEMENTED).
+
+Sources are plists read with plistlib, sysctl via ctypes (no spawn), and a few short spawns (system_profiler,
+fdesetup, csrutil, spctl, socketfilterfw, networksetup, tailscale, pmset, last, dscl, bioutil). Stores behind
+Transparency Consent and Control (TCC.db, knowledgeC.db) need Full Disk Access for the process that runs the
+collector; without it the detector reports readable=false and the extractor returns absent.
+"""
+from __future__ import annotations
+
+import collections
+import ctypes
+import ctypes.util
+import datetime as dt
+import glob
+import json
+import os
+import platform
+import plistlib
+import re
+import sqlite3
+import threading
+import time
+
+from userscan.registry import probe
+
+OS = "darwin"
+MAC_EPOCH = 978307200 # 2001-01-01 UTC, Core Data / Cocoa absolute time
+
+# ---------------------------------------------------------------- shared helpers
+
+_LOCK = threading.Lock()
+_CACHE: dict = {}
+_KEYLOCKS: dict = {}
+
+
+def memo(h, name, fn):
+ """Compute fn() once per run, shared by every probe that needs it."""
+ key = (h.l0.get("run_id"), name)
+ with _LOCK:
+ if key in _CACHE:
+ return _CACHE[key]
+ lk = _KEYLOCKS.setdefault(key, threading.Lock())
+ with lk:
+ if key not in _CACHE:
+ try:
+ _CACHE[key] = fn()
+ except Exception as e:
+ _CACHE[key] = {"__error__": f"{type(e).__name__}: {e}"}
+ v = _CACHE[key]
+ if isinstance(v, dict) and "__error__" in v:
+ raise RuntimeError(v["__error__"])
+ return v
+
+
+def home():
+ return os.path.expanduser("~")
+
+
+def H(*parts):
+ return os.path.join(home(), *parts)
+
+
+def isdir(p):
+ try:
+ return os.path.isdir(p)
+ except OSError:
+ return False
+
+
+def ls(p, cap=2000):
+ try:
+ with os.scandir(p) as it:
+ return [e.name for _, e in zip(range(cap), it)]
+ except OSError:
+ return None
+
+
+def iso(ts):
+ try:
+ return dt.datetime.fromtimestamp(float(ts)).astimezone().isoformat(timespec="minutes") if ts else None
+ except (OverflowError, OSError, ValueError, TypeError):
+ return None
+
+
+def day(ts):
+ try:
+ return dt.datetime.fromtimestamp(float(ts)).strftime("%Y-%m-%d") if ts else None
+ except (OverflowError, OSError, ValueError, TypeError):
+ return None
+
+
+def birth(p):
+ try:
+ st = os.stat(p)
+ return getattr(st, "st_birthtime", None) or st.st_ctime
+ except OSError:
+ return None
+
+
+def mtime(p):
+ try:
+ return os.stat(p).st_mtime
+ except OSError:
+ return None
+
+
+def plist(p, maxb=20_000_000):
+ """plistlib load (binary or XML). None when missing, unreadable (TCC) or malformed."""
+ try:
+ if os.path.getsize(p) > maxb:
+ return None
+ with open(p, "rb") as f:
+ return plistlib.load(f)
+ except Exception:
+ return None
+
+
+def readable(p):
+ """True if the file can be opened for reading. PermissionError here on a user file means TCC (FDA)."""
+ try:
+ fd = os.open(p, os.O_RDONLY)
+ os.close(fd)
+ return True
+ except OSError:
+ return False
+
+
+def fmeta(p):
+ """presence + size + readability, never reads contents. For TCC-protected and T3 files."""
+ try:
+ st = os.stat(p)
+ except OSError:
+ return {"present": False}
+ ok = readable(p)
+ return {"present": True, "bytes": st.st_size, "mtime": day(st.st_mtime), "readable": ok, "needs_fda": not ok}
+
+
+def run(h, args, timeout_ms=5000):
+ return h.run(args, timeout_ms=timeout_ms) or ""
+
+
+def sp_json(h, *types, timeout_ms=8000):
+ """system_profiler -json for one or more data types (one spawn)."""
+ txt = run(h, ["system_profiler", "-json", "-detailLevel", "mini", *types], timeout_ms)
+ try:
+ return json.loads(txt) if txt.strip() else {}
+ except ValueError:
+ return {}
+
+
+def sqlite_ro(path, sql, args=(), timeout=2.0):
+ """Read-only query on the live file (no copy). Used for large WAL databases (Hermes state.db)
+ where a copy would cost seconds; a mode=ro reader never writes the main file."""
+ con = sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=timeout)
+ try:
+ return con.execute(sql, args).fetchall()
+ finally:
+ con.close()
+
+
+_libc = None
+
+
+def _lib():
+ global _libc
+ if _libc is None:
+ _libc = ctypes.CDLL(ctypes.util.find_library("c"))
+ return _libc
+
+
+def sysctl_str(name):
+ try:
+ lib = _lib()
+ size = ctypes.c_size_t(0)
+ if lib.sysctlbyname(name.encode(), None, ctypes.byref(size), None, 0) != 0:
+ return None
+ buf = ctypes.create_string_buffer(size.value)
+ if lib.sysctlbyname(name.encode(), buf, ctypes.byref(size), None, 0) != 0:
+ return None
+ return buf.value.decode("utf-8", "replace")
+ except Exception:
+ return None
+
+
+def sysctl_int(name, ctype=ctypes.c_int64):
+ try:
+ v = ctype()
+ size = ctypes.c_size_t(ctypes.sizeof(v))
+ if _lib().sysctlbyname(name.encode(), ctypes.byref(v), ctypes.byref(size), None, 0) != 0:
+ return None
+ return int(v.value)
+ except Exception:
+ return None
+
+
+def boottime():
+ class _TV(ctypes.Structure):
+ _fields_ = [("sec", ctypes.c_long), ("usec", ctypes.c_int)]
+ try:
+ t = _TV()
+ size = ctypes.c_size_t(ctypes.sizeof(t))
+ if _lib().sysctlbyname(b"kern.boottime", ctypes.byref(t), ctypes.byref(size), None, 0) == 0:
+ return float(t.sec)
+ except Exception:
+ pass
+ return None
+
+
+def app_paths():
+ """{lowercased bundle name without .app: path} for /Applications (depth 2), ~/Applications, /System/Applications."""
+ def build():
+ out = {}
+ for root in ("/Applications", H("Applications"), "/System/Applications", "/System/Applications/Utilities"):
+ for n in ls(root, 3000) or []:
+ p = os.path.join(root, n)
+ if n.endswith(".app"):
+ out.setdefault(n[:-4].lower(), p)
+ elif root == "/Applications" and isdir(p) and not n.startswith("."):
+ for m in ls(p, 200) or []:
+ if m.endswith(".app"):
+ out.setdefault(m[:-4].lower(), os.path.join(p, m))
+ return out
+ return _shared_memo("app_paths", build)
+
+
+def has_app(*names):
+ """First matching installed app name (case-insensitive, exact bundle name or prefix match)."""
+ ap = app_paths()
+ for n in names:
+ k = n.lower()
+ if k in ap:
+ return n
+ for n in names:
+ k = n.lower()
+ if any(a.startswith(k) for a in ap):
+ return n
+ return None
+
+
+_SHARED: dict = {}
+
+
+def _shared_memo(name, fn):
+ """Process-level memo for pure filesystem inventories that do not depend on the run."""
+ with _LOCK:
+ if name in _SHARED:
+ return _SHARED[name]
+ v = fn()
+ with _LOCK:
+ _SHARED[name] = v
+ return v
+
+
+GLOBAL_PREFS = lambda: plist(H("Library", "Preferences", ".GlobalPreferences.plist")) or {}
+SYSCFG = "/Library/Preferences/SystemConfiguration/preferences.plist"
+DISABLED = "/var/db/com.apple.xpc.launchd/disabled.plist"
+
+
+def gprefs(h):
+ return memo(h, "gprefs", GLOBAL_PREFS)
+
+
+def syscfg(h):
+ return memo(h, "syscfg", lambda: plist(SYSCFG) or {})
+
+
+# ================================================================ host
+
+@probe(id="os.build", level="L1", family="host", tier="T0", collect="core", os=OS)
+def os_build(h, facts):
+ """macOS product version and build (SystemVersion.plist, same data as sw_vers)."""
+ sv = plist("/System/Library/CoreServices/SystemVersion.plist") or {}
+ ver = sv.get("ProductVersion") or platform.mac_ver()[0]
+ if not ver:
+ return None
+ return {"present": True, "product": sv.get("ProductName", "macOS"), "version": ver,
+ "build": sv.get("ProductBuildVersion") or sysctl_str("kern.osversion"),
+ "kernel": platform.release(), "major": int(ver.split(".")[0])}
+
+
+_NAMES = {"11": "Big Sur", "12": "Monterey", "13": "Ventura", "14": "Sonoma", "15": "Sequoia", "26": "Tahoe"}
+
+
+@probe(id="os.edition", level="L1", family="host", tier="T0", collect="core", os=OS)
+def os_edition(h, facts):
+ """macOS marketing name (Sequoia, Tahoe...). macOS has no editions; the name stands in for one."""
+ ver = platform.mac_ver()[0]
+ if not ver:
+ return None
+ return {"present": True, "edition": "macOS " + _NAMES.get(ver.split(".")[0], ver.split(".")[0]), "version": ver}
+
+
+@probe(id="os.insider", level="L1", family="host", tier="T0", collect="core", os=OS)
+def os_insider(h, facts):
+ """Beta/seed enrollment: SoftwareUpdate CatalogURL or seed program key (AppleSeed / developer beta)."""
+ su = plist("/Library/Preferences/com.apple.SoftwareUpdate.plist") or {}
+ seed = plist("/Library/Preferences/com.apple.seeding.plist") or {}
+ cat = str(su.get("CatalogURL") or "")
+ beta = "seed" in cat.lower() or bool(seed.get("SeedProgram") or seed.get("ProgramID"))
+ return {"present": True, "beta": beta, "catalog_custom": bool(cat),
+ "auto_install_macos_updates": su.get("AutomaticallyInstallMacOSUpdates"),
+ "auto_download": su.get("AutomaticDownload"),
+ "recommended_major_upgrade": su.get("LastRecommendedMajorOSBundleIdentifier")}
+
+
+@probe(id="host.native_arch", level="L1", family="host", tier="T0", collect="core", os=OS)
+def host_native_arch(h, facts):
+ """Native CPU arch (hw.optional.arm64) vs interpreter arch."""
+ arm = sysctl_int("hw.optional.arm64", ctypes.c_int) == 1
+ return {"present": True, "arch": "arm64" if arm else "x86_64", "python_machine": platform.machine(),
+ "apple_silicon": arm}
+
+
+@probe(id="host.python_emulated", level="L1", family="host", tier="T0", collect="core", os=OS)
+def host_python_emulated(h, facts):
+ """Collector running under Rosetta 2 (sysctl.proc_translated=1): timings are then unreliable."""
+ tr = sysctl_int("sysctl.proc_translated", ctypes.c_int)
+ return {"present": True, "emulated": tr == 1, "proc_translated": tr}
+
+
+FDA_SOURCES = {
+ "tcc_user": ("Library", "Application Support", "com.apple.TCC", "TCC.db"),
+ "knowledgec": ("Library", "Application Support", "Knowledge", "knowledgeC.db"),
+ "safari_history": ("Library", "Safari", "History.db"),
+ "messages_chat": ("Library", "Messages", "chat.db"),
+ "notes_store": ("Library", "Group Containers", "group.com.apple.notes", "NoteStore.sqlite"),
+ "mail_dir": ("Library", "Mail"),
+ "shared_file_list": ("Library", "Application Support", "com.apple.sharedfilelist"),
+}
+
+
+def fda_state(h):
+ def build():
+ out = {}
+ for k, parts in FDA_SOURCES.items():
+ p = H(*parts)
+ if not os.path.exists(p):
+ out[k] = "absent"
+ elif os.path.isdir(p):
+ out[k] = "readable" if ls(p, 1) is not None else "blocked"
+ else:
+ out[k] = "readable" if readable(p) else "blocked"
+ out["tcc_system"] = "readable" if readable("/Library/Application Support/com.apple.TCC/TCC.db") else "blocked"
+ return out
+ return memo(h, "fda", build)
+
+
+@probe(id="host.fda", level="L1", family="host", tier="T0", collect="core", os=OS)
+def host_fda(h, facts):
+ """Whether this process has Full Disk Access: open() on TCC-protected stores (TCC.db, knowledgeC, Safari...)."""
+ st = fda_state(h)
+ blocked = sorted(k for k, v in st.items() if v == "blocked")
+ return {"present": True, "full_disk_access": not blocked, "blocked": blocked,
+ "readable": sorted(k for k, v in st.items() if v == "readable"),
+ "absent": sorted(k for k, v in st.items() if v == "absent")}
+
+
+# ================================================================ identity
+
+_DEFAULT_HOST = re.compile(r"^.+['’]s (MacBook( Pro| Air)?|iMac|Mac( mini| Studio| Pro)?)( \(\d+\))?$", re.I)
+
+
+@probe(id="host.name", level="L1", family="identity", tier="T0", collect="core", os=OS)
+def host_name(h, facts):
+ """ComputerName / LocalHostName with the owner's first name redacted (it is the account name)."""
+ s = (syscfg(h).get("System") or {})
+ cn = ((s.get("System") or {}).get("ComputerName")) or platform.node()
+ lhn = ((s.get("Network") or {}).get("HostNames") or {}).get("LocalHostName")
+ red = re.sub(r"^.+?(['’]s )", r"<user>\1", cn or "")
+ return {"present": bool(cn), "name": red, "local_host_name_set": bool(lhn),
+ "default_pattern": bool(_DEFAULT_HOST.match(cn or ""))}
+
+
+@probe(id="host.name_default", level="L1", family="identity", tier="T0", collect="core", os=OS)
+def host_name_default(h, facts):
+ """ComputerName still the Setup Assistant default ("<first name>'s MacBook Pro")."""
+ s = (syscfg(h).get("System") or {}).get("System") or {}
+ cn = s.get("ComputerName") or ""
+ return {"present": True, "default": bool(_DEFAULT_HOST.match(cn))}
+
+
+@probe(id="acct.account_type", level="L1", family="identity", tier="T0", collect="core", os=OS)
+def acct_account_type(h, facts):
+ """Current user admin (member of gid 80) or standard."""
+ try:
+ admin = 80 in os.getgroups()
+ except OSError:
+ admin = None
+ return {"present": True, "admin": admin, "type": "admin" if admin else "standard", "uid": os.getuid()}
+
+
+@probe(id="profile.count", level="L1", family="identity", tier="T0", collect="core", os=OS)
+def profile_count(h, facts):
+ """Home directories under /Users (names not emitted)."""
+ names = [n for n in (ls("/Users") or []) if not n.startswith(".") and n not in ("Shared", "Guest")]
+ return {"present": bool(names), "count": len(names)}
+
+
+@probe(id="acct.local_users", level="L2", family="identity", tier="T1", collect="extended", gate="profile.count",
+ os=OS)
+def acct_local_users(h, facts):
+ """Local accounts with uid >= 500 (dscl), count only; names never emitted."""
+ txt = run(h, ["dscl", ".", "-list", "/Users", "UniqueID"], 4000)
+ n = 0
+ for line in txt.splitlines():
+ parts = line.split()
+ if len(parts) == 2 and parts[1].isdigit() and int(parts[1]) >= 500 and not parts[0].startswith("_"):
+ n += 1
+ lw = plist("/Library/Preferences/com.apple.loginwindow.plist") or {}
+ return {"present": n > 0, "count": n, "guest_enabled": lw.get("GuestEnabled"),
+ "recent_users": len(lw.get("RecentUsers") or [])}
+
+
+# ================================================================ install_age
+
+def install_history(h):
+ return memo(h, "install_history", lambda: plist("/Library/Receipts/InstallHistory.plist") or [])
+
+
+def _hist_date(e):
+ d = e.get("date")
+ if isinstance(d, dt.datetime):
+ return d.replace(tzinfo=dt.timezone.utc).timestamp()
+ return None
+
+
+@probe(id="os.install_date", level="L1", family="install_age", tier="T0", collect="core", os=OS)
+def os_install_date(h, facts):
+ """OS install date: .AppleSetupDone birth time and the first InstallHistory.plist record."""
+ sd = birth("/var/db/.AppleSetupDone")
+ hist = [t for t in (_hist_date(e) for e in install_history(h)) if t]
+ first = min(hist) if hist else None
+ cands = [t for t in (sd, first) if t]
+ if not cands:
+ return None
+ return {"present": True, "install_date": iso(min(cands)), "setup_done_birth": iso(sd),
+ "install_history_first": iso(first), "install_log_birth": iso(birth("/var/log/install.log"))}
+
+
+@probe(id="setup.oobe_done", level="L1", family="install_age", tier="T0", collect="core", os=OS)
+def setup_oobe_done(h, facts):
+ """Setup Assistant completion: /var/db/.AppleSetupDone birth time (stat only; the file is root-only)."""
+ b = birth("/var/db/.AppleSetupDone")
+ if not b:
+ return None
+ return {"present": True, "date": iso(b), "mtime": iso(mtime("/var/db/.AppleSetupDone"))}
+
+
+@probe(id="profile.created", level="L1", family="install_age", tier="T0", collect="core", os=OS)
+def profile_created(h, facts):
+ """Home directory birth time. Older than the OS install means the home was migrated or restored."""
+ b = birth(home())
+ if not b:
+ return None
+ sd = birth("/var/db/.AppleSetupDone")
+ pre = round((sd - b) / 86400) if sd and b < sd else 0
+ return {"present": True, "created": iso(b), "predates_os_install_days": pre,
+ "migrated_home": pre > 30}
+
+
+@probe(id="setup.source_os_lineage", level="L1", family="install_age", tier="T0", collect="core", os=OS)
+def setup_source_os_lineage(h, facts):
+ """macOS versions installed on this volume (InstallHistory). count = major-version upgrades only."""
+ rows = []
+ for e in install_history(h):
+ n = str(e.get("displayName") or "")
+ if n.startswith("macOS") and e.get("processName") in ("softwareupdated", "macOS Installer", "Setup Assistant",
+ "installer", "Installer", "bootinstalld"):
+ rows.append((_hist_date(e), str(e.get("displayVersion") or n.split()[-1])))
+ rows = sorted(r for r in rows if r[0])
+ majors = []
+ for _, v in rows:
+ m = v.split(".")[0]
+ if not majors or majors[-1] != m:
+ majors.append(m)
+ return {"present": bool(rows), "count": max(0, len(majors) - 1), "majors": majors,
+ "updates": [[day(t), v] for t, v in rows][-12:], "oldest": iso(rows[0][0]) if rows else None,
+ "note": "minor updates do not count as an upgrade lineage"}
+
+
+@probe(id="age.footprint_counts", level="L1", family="install_age", tier="T0", collect="core", os=OS)
+def age_footprint_counts(h, facts):
+ """Accumulation counters: Application Support dirs, preference plists, containers, group containers."""
+ lib = H("Library")
+ return {"present": True,
+ "app_support_dirs": len(ls(os.path.join(lib, "Application Support"), 5000) or []),
+ "preference_plists": len([n for n in ls(os.path.join(lib, "Preferences"), 5000) or [] if n.endswith(".plist")]),
+ "containers": len(ls(os.path.join(lib, "Containers"), 5000) or []),
+ "group_containers": len(ls(os.path.join(lib, "Group Containers"), 5000) or []),
+ "launch_agents": len(ls(os.path.join(lib, "LaunchAgents"), 1000) or [])}
+
+
+def _preferred_wifi(h):
+ def build():
+ txt = run(h, ["networksetup", "-listpreferredwirelessnetworks", "en0"], 4000)
+ lines = [l for l in txt.splitlines() if l.startswith("\t") or l.startswith(" ")]
+ return {"count": len(lines), "ok": "Preferred networks" in txt}
+ return memo(h, "pref_wifi", build)
+
+
+@probe(id="net.history", level="L2", family="install_age", tier="T1", collect="extended", gate="os.install_date",
+ os=OS)
+def net_history(h, facts):
+ """Remembered Wi-Fi networks (networksetup preferred list; SSIDs never emitted)."""
+ w = _preferred_wifi(h)
+ if not w["ok"]:
+ return {"present": False}
+ return {"present": True, "wireless": w["count"],
+ "note": "macOS keeps no first-connected date for non-root readers"}
+
+
+# ================================================================ locale
+
+@probe(id="locale.user", level="L1", family="locale", tier="T0", collect="core", os=OS)
+def locale_user(h, facts):
+ """AppleLocale, measurement units, first weekday, 24h clock (GlobalPreferences)."""
+ g = gprefs(h)
+ loc = g.get("AppleLocale")
+ if not loc:
+ return None
+ return {"present": True, "locale": loc, "measurement_units": g.get("AppleMeasurementUnits"),
+ "metric": g.get("AppleMetricUnits"), "temperature": g.get("AppleTemperatureUnit"),
+ "first_weekday": g.get("AppleFirstWeekday"), "force_24h": g.get("AppleICUForce24HourTime"),
+ "custom_date_formats": bool(g.get("AppleICUDateFormatStrings"))}
+
+
+@probe(id="locale.geo", level="L1", family="locale", tier="T0", collect="core", os=OS)
+def locale_geo(h, facts):
+ """Region code from AppleLocale (en_IN -> IN)."""
+ loc = gprefs(h).get("AppleLocale") or ""
+ m = re.search(r"_([A-Z]{2})", loc)
+ return {"present": bool(m), "geo": m.group(1) if m else None}
+
+
+@probe(id="lang.ui", level="L1", family="locale", tier="T0", collect="core", os=OS)
+def lang_ui(h, facts):
+ """Primary UI language (AppleLanguages[0])."""
+ langs = gprefs(h).get("AppleLanguages") or []
+ return {"present": bool(langs), "ui_language": langs[0] if langs else None}
+
+
+@probe(id="lang.user_list", level="L1", family="locale", tier="T0", collect="core", os=OS)
+def lang_user_list(h, facts):
+ """Preferred language list."""
+ langs = gprefs(h).get("AppleLanguages") or []
+ return {"present": bool(langs), "languages": langs[:10], "count": len(langs)}
+
+
+@probe(id="kbd.layouts", level="L1", family="locale", tier="T0", collect="core", os=OS)
+def kbd_layouts(h, facts):
+ """Enabled keyboard layouts and input methods (HIToolbox)."""
+ t = plist(H("Library", "Preferences", "com.apple.HIToolbox.plist")) or {}
+ src = t.get("AppleEnabledInputSources") or []
+ layouts = [s.get("KeyboardLayout Name") for s in src if s.get("InputSourceKind") == "Keyboard Layout"]
+ ims = [s.get("Bundle ID") for s in src if s.get("InputSourceKind") in ("Input Mode", "Keyboard Input Method")]
+ return {"present": bool(src), "layouts": [x for x in layouts if x], "input_methods": [x for x in ims if x],
+ "current": t.get("AppleCurrentKeyboardLayoutInputSourceID")}
+
+
+@probe(id="kbd.scancode_map", level="L1", family="locale", tier="T0", collect="core", os=OS)
+def kbd_scancode_map(h, facts):
+ """Keyboard remapping: per-keyboard modifier mappings (ByHost GlobalPreferences) and Karabiner-Elements."""
+ n = 0
+ for p in glob.glob(H("Library", "Preferences", "ByHost", ".GlobalPreferences.*.plist"))[:5]:
+ d = plist(p) or {}
+ n += sum(1 for k, v in d.items() if k.startswith("com.apple.keyboard.modifiermapping.") and v)
+ kar = isdir(H(".config", "karabiner")) or bool(has_app("Karabiner-Elements"))
+ return {"present": bool(n or kar), "remapped": bool(n or kar), "modifier_remaps": n, "karabiner": kar}
+
+
+@probe(id="tz.zone", level="L1", family="locale", tier="T0", collect="core", os=OS)
+def tz_zone(h, facts):
+ """Time zone from the /etc/localtime link."""
+ try:
+ tgt = os.readlink("/etc/localtime")
+ except OSError:
+ return None
+ m = re.search(r"zoneinfo/(.+)$", tgt)
+ return {"present": bool(m), "zone": m.group(1) if m else tgt, "utc_offset_min": -time.timezone // 60}
+
+
+@probe(id="tz.auto", level="L1", family="locale", tier="T0", collect="core", os=OS)
+def tz_auto(h, facts):
+ """Set time zone automatically (com.apple.timezone.auto Active)."""
+ p = plist("/Library/Preferences/com.apple.timezone.auto.plist")
+ if p is None:
+ return None
+ return {"present": True, "auto": bool(p.get("Active"))}
+
+
+# ================================================================ shell_prefs
+
+@probe(id="theme.dark", level="L1", family="shell_prefs", tier="T0", collect="core", os=OS)
+def theme_dark(h, facts):
+ """Dark mode (AppleInterfaceStyle) and automatic appearance switching."""
+ g = gprefs(h)
+ return {"present": True, "apps_dark": g.get("AppleInterfaceStyle") == "Dark",
+ "auto_switch": bool(g.get("AppleInterfaceStyleSwitchesAutomatically")),
+ "accent_color": g.get("AppleAccentColor"), "reduce_transparency": None}
+
+
+@probe(id="theme.wallpaper", level="L1", family="shell_prefs", tier="T0", collect="core", os=OS)
+def theme_wallpaper(h, facts):
+ """Desktop wallpaper kind: OS default (dynamic/aerial for this release) vs chosen image or colour."""
+ d = plist(H("Library", "Application Support", "com.apple.wallpaper", "Store", "Index.plist")) or {}
+ desk = ((d.get("AllSpacesAndDisplays") or {}).get("Desktop") or {})
+ ch = ((desk.get("Content") or {}).get("Choices") or [{}])[0]
+ prov = str(ch.get("Provider") or "")
+ files = [f.get("relative", "") for f in ch.get("Files") or [] if isinstance(f, dict)]
+ system = any("/System/Library/Desktop%20Pictures" in f or "/System/Library/Desktop Pictures" in f for f in files)
+ kind = ("default" if (not prov or re.search(r"choice\.(sequoia|sonoma|ventura|macintosh|tahoe|dynamic)", prov)
+ and not files) else
+ "system_color" if system and "Solid" in " ".join(files) else
+ "system_picture" if system else "aerial" if "aerial" in prov else "user_image" if files else "other")
+ return {"present": bool(d), "default": kind == "default", "kind": kind, "provider": prov.split(".")[-1] or None,
+ "last_set": iso(desk.get("LastSet").timestamp()) if isinstance(desk.get("LastSet"), dt.datetime) else None}
+
+
+@probe(id="theme.spotlight_suggestions", level="L1", family="shell_prefs", tier="T0", collect="core", os=OS)
+def theme_spotlight_suggestions(h, facts):
+ """Spotlight / Siri suggestions category enabled (com.apple.Spotlight orderedItems)."""
+ s = plist(H("Library", "Preferences", "com.apple.Spotlight.plist")) or {}
+ items = s.get("orderedItems")
+ on = True
+ if isinstance(items, list):
+ for it in items:
+ if isinstance(it, dict) and it.get("name") in ("MENU_SPOTLIGHT_SUGGESTIONS", "MENU_WEBSEARCH"):
+ on = on and bool(it.get("enabled"))
+ return {"present": True, "suggestions_on": on, "customised": isinstance(items, list)}
+
+
+_APPLE_DOCK = {"com.apple.finder", "com.apple.launchpad.launcher", "com.apple.apps.launcher", "com.apple.safari",
+ "com.apple.mail", "com.apple.maps", "com.apple.photos", "com.apple.facetime", "com.apple.ical",
+ "com.apple.addressbook", "com.apple.reminders", "com.apple.notes", "com.apple.freeform", "com.apple.tv",
+ "com.apple.music", "com.apple.news", "com.apple.appstore", "com.apple.systempreferences",
+ "com.apple.mobilesms", "com.apple.iwork.keynote", "com.apple.iwork.numbers", "com.apple.iwork.pages",
+ "com.apple.podcasts", "com.apple.iphonemirroring"}
+
+
+def _dock(h):
+ return memo(h, "dock", lambda: plist(H("Library", "Preferences", "com.apple.dock.plist")) or {})
+
+
+@probe(id="pins.taskbar", level="L1", family="shell_prefs", tier="T0", collect="core", os=OS)
+def pins_taskbar(h, facts):
+ """Dock pinned apps (bundle ids), recents, autohide, position."""
+ d = _dock(h)
+ apps = [((a.get("tile-data") or {}).get("bundle-identifier") or "") for a in d.get("persistent-apps") or []]
+ return {"present": bool(d), "count": len(apps), "pins": [a for a in apps if a][:30],
+ "autohide": d.get("autohide"), "show_recents": d.get("show-recents"), "orientation": d.get("orientation"),
+ "tile_size": d.get("tilesize")}
+
+
+@probe(id="pins.taskband_oem", level="L2", family="shell_prefs", tier="T0", collect="core", gate="pins.taskbar", os=OS)
+def pins_taskband_oem(h, facts):
+ """Apple default Dock apps still pinned. oem_pins is set only when the Dock looks factory (>= 8 defaults)."""
+ d = _dock(h)
+ apps = [((a.get("tile-data") or {}).get("bundle-identifier") or "").lower() for a in d.get("persistent-apps") or []]
+ n = sum(1 for a in apps if a in _APPLE_DOCK)
+ return {"present": True, "default_pins": n, "other_pins": len(apps) - n, "oem_pins": n if n >= 8 else 0}
+
+
+@probe(id="shell.explorer_prefs", level="L1", family="shell_prefs", tier="T0", collect="core", os=OS)
+def shell_explorer_prefs(h, facts):
+ """Finder prefs: show all extensions, hidden files, path/status bar, default view."""
+ g = gprefs(h)
+ f = plist(H("Library", "Preferences", "com.apple.finder.plist")) or {}
+ show_ext = bool(g.get("AppleShowAllExtensions"))
+ return {"present": True, "HideFileExt": 0 if show_ext else 1, "show_extensions": show_ext,
+ "show_hidden": bool(f.get("AppleShowAllFiles")), "path_bar": f.get("ShowPathbar"),
+ "status_bar": f.get("ShowStatusBar"), "view_style": f.get("FXPreferredViewStyle"),
+ "desktop_icons_hidden": f.get("CreateDesktop") is False,
+ "autocorrect_off": g.get("NSAutomaticSpellingCorrectionEnabled") is False,
+ "text_replacements": len(g.get("NSUserDictionaryReplacementItems") or [])}
+
+
+# ================================================================ security
+
+_REMOTE = ["AnyDesk", "TeamViewer", "RustDesk", "Parsec", "Jump Desktop", "Screens 5", "Screens for Mac",
+ "Chrome Remote Desktop Host", "Splashtop Business", "Microsoft Remote Desktop", "Windows App", "NoMachine"]
+
+
+@probe(id="security.remote_tools", level="L1", family="security", tier="T0", collect="core", os=OS)
+def security_remote_tools(h, facts):
+ """Third-party remote-access apps installed. Always present (gates the security subtree)."""
+ return {"present": True, "found": [n for n in _REMOTE if has_app(n)]}
+
+
+def _disabled(h):
+ return memo(h, "launchd_disabled", lambda: plist(DISABLED) or {})
+
+
+@probe(id="security.openssh_server", level="L1", family="security", tier="T3", collect="core", os=OS)
+def security_openssh_server(h, facts):
+ """Remote Login (sshd) enabled: com.openssh.sshd=false in launchd disabled.plist. Keys never read."""
+ d = _disabled(h)
+ on = d.get("com.openssh.sshd") is False
+ return {"present": on, "sshd": on, "sshd_config_bytes": fmeta("/etc/ssh/sshd_config").get("bytes")}
+
+
+@probe(id="security.rdp", level="L1", family="security", tier="T0", collect="core", os=OS)
+def security_rdp(h, facts):
+ """Screen Sharing / Remote Management (ARD) enabled (launchd disabled.plist + ARD launchd flag)."""
+ d = _disabled(h)
+ ss = d.get("com.apple.screensharing") is False
+ ard = os.path.exists("/Library/Application Support/Apple/Remote Desktop/RemoteManagement.launchd")
+ return {"present": True, "rdp_enabled": ss or ard, "screen_sharing": ss, "remote_management": ard}
+
+
+@probe(id="acct.autologon", level="L1", family="security", tier="T0", collect="core", os=OS)
+def acct_autologon(h, facts):
+ """Automatic login configured (loginwindow autoLoginUser present; name not emitted)."""
+ lw = plist("/Library/Preferences/com.apple.loginwindow.plist") or {}
+ return {"present": True, "autologon": bool(lw.get("autoLoginUser")),
+ "kcpassword": os.path.exists("/etc/kcpassword"), "guest_enabled": lw.get("GuestEnabled"),
+ "hide_user_list": lw.get("SHOWFULLNAME")}
+
+
+@probe(id="acct.hello", level="L2", family="security", tier="T0", collect="core", gate="security.remote_tools",
+ os=OS)
+def acct_hello(h, facts):
+ """Touch ID enrolled for this user (bioutil template count)."""
+ txt = run(h, ["bioutil", "-c"], 2000)
+ m = re.search(r"(\d+) biometric template", txt)
+ if not m:
+ return {"present": False}
+ return {"present": True, "touch_id_templates": int(m.group(1)), "fingerprint": int(m.group(1)) > 0,
+ "face": False}
+
+
+@probe(id="security.firewall", level="L2", family="security", tier="T0", collect="core", gate="security.remote_tools",
+ os=OS)
+def security_firewall(h, facts):
+ """Application Firewall global state and stealth mode (socketfilterfw)."""
+ fw = "/usr/libexec/ApplicationFirewall/socketfilterfw"
+ g = run(h, [fw, "--getglobalstate"], 3000)
+ s = run(h, [fw, "--getstealthmode"], 3000)
+ if not g:
+ return None
+ return {"present": True, "enabled": "enabled" in g.lower() and "disabled" not in g.lower(),
+ "stealth": "on" in s.lower() or "enabled" in s.lower()}
+
+
+@probe(id="security.bitlocker", level="L2", family="security", tier="T0", collect="core",
+ gate="security.remote_tools", os=OS)
+def security_bitlocker(h, facts):
+ """Disk encryption: FileVault state (fdesetup status)."""
+ t = run(h, ["fdesetup", "status"], 3000)
+ if not t:
+ return None
+ return {"present": True, "product": "FileVault", "on": "FileVault is On" in t,
+ "encrypting": "Encryption in progress" in t}
+
+
+@probe(id="security.sip", level="L2", family="security", tier="T0", collect="core", gate="security.remote_tools",
+ os=OS)
+def security_sip(h, facts):
+ """System Integrity Protection (csrutil status)."""
+ t = run(h, ["csrutil", "status"], 3000)
+ if not t:
+ return None
+ return {"present": True, "enabled": "enabled" in t.lower() and "disabled" not in t.lower(),
+ "custom": "Custom Configuration" in t}
+
+
+@probe(id="security.smartscreen", level="L2", family="security", tier="T0", collect="core",
+ gate="security.remote_tools", os=OS)
+def security_smartscreen(h, facts):
+ """Gatekeeper assessments (spctl --status), the macOS download-reputation check."""
+ t = run(h, ["spctl", "--status"], 3000)
+ if not t:
+ return None
+ return {"present": True, "product": "Gatekeeper", "enabled": "enabled" in t}
+
+
+_AV = ["Malwarebytes", "Sophos Home", "Avast Security", "AVG AntiVirus", "Bitdefender Antivirus for Mac", "Norton 360",
+ "Intego", "ESET Endpoint Security", "ClamXAV", "KnockKnock", "LuLu", "Little Snitch", "BlockBlock",
+ "CrowdStrike Falcon", "Falcon", "SentinelOne", "Microsoft Defender", "Jamf Protect"]
+
+
+@probe(id="security.av_products", level="L1", family="security", tier="T0", collect="core", os=OS)
+def security_av_products(h, facts):
+ """XProtect definitions version plus third-party AV / network-monitor apps installed."""
+ xp = plist("/Library/Apple/System/Library/CoreServices/XProtect.bundle/Contents/Info.plist") or {}
+ upd = [e for e in install_history(h) if e.get("processName") == "XProtectUpdateService"]
+ last = max((_hist_date(e) or 0 for e in upd), default=0)
+ return {"present": True, "xprotect_version": xp.get("CFBundleShortVersionString"),
+ "xprotect_last_update": day(last) if last else None,
+ "third_party": [n for n in _AV if has_app(n)]}
+
+
+@probe(id="security.telemetry", level="L1", family="security", tier="T0", collect="core", os=OS)
+def security_telemetry(h, facts):
+ """Share Mac Analytics (CrashReporter AutoSubmit) and share with app developers (ThirdPartyDataSubmit)."""
+ d = plist("/Library/Application Support/CrashReporter/DiagnosticMessagesHistory.plist")
+ if d is None:
+ return None
+ auto = bool(d.get("AutoSubmit"))
+ return {"present": True, "analytics_on": auto, "third_party_on": bool(d.get("ThirdPartyDataSubmit")),
+ "reduced": not auto}
+
+
+@probe(id="acct.admins", level="L2", family="security", tier="T0", collect="extended", gate="security.remote_tools",
+ os=OS)
+def acct_admins(h, facts):
+ """Members of the admin group (count only)."""
+ t = run(h, ["dscl", ".", "-read", "/Groups/admin", "GroupMembership"], 3000)
+ m = t.split(":", 1)[1].split() if ":" in t else []
+ return {"present": bool(m), "count": len([x for x in m if x != "root"])}
+
+
+# ---- TCC (camera / microphone / screen recording) and location
+
+TCC_USER = ("Library", "Application Support", "com.apple.TCC", "TCC.db")
+TCC_SYS = "/Library/Application Support/com.apple.TCC/TCC.db"
+LOCATIOND = "/private/var/db/locationd/clients.plist"
+
+
+@probe(id="consent.store", level="L1", family="security", tier="T1", collect="core", os=OS)
+def consent_store(h, facts):
+ """Privacy permission stores: user/system TCC.db (Full Disk Access) and locationd clients.plist."""
+ u, s = fmeta(H(*TCC_USER)), fmeta(TCC_SYS)
+ loc = fmeta(LOCATIOND)
+ return {"present": u["present"] or loc["present"], "tcc_user": u, "tcc_system": s, "locationd": loc}
+
+
+def _tcc(h):
+ def build():
+ out = collections.defaultdict(lambda: {"granted": [], "denied": 0, "when": {}})
+ read = []
+ for label, path in (("user", H(*TCC_USER)), ("system", TCC_SYS)):
+ rows = h.sqlite(path, "select service, client, auth_value, last_modified from access")
+ if rows is None:
+ rows = h.sqlite(path, "select service, client, auth_value, null from access")
+ if rows is None:
+ continue
+ read.append(label)
+ for svc, client, auth, when in rows:
+ slot = out[svc]
+ if auth in (2, 3):
+ slot["granted"].append(client)
+ if when:
+ slot["when"][client] = max(slot["when"].get(client, 0), when)
+ else:
+ slot["denied"] += 1
+ return {"read": read, "svc": dict(out)}
+ return memo(h, "tcc", build)
+
+
+def _tcc_probe(h, service):
+ t = _tcc(h)
+ if not t["read"]:
+ return {"present": False, "needs_fda": True}
+ s = t["svc"].get(service) or {"granted": [], "denied": 0, "when": {}}
+ g = sorted(set(s["granted"]), key=lambda c: -(s["when"].get(c) or 0))
+ return {"present": True, "granted": len(g), "denied": s["denied"],
+ "items": [x.rsplit("/", 1)[-1] for x in g][:15],
+ "granted_on": [[x.rsplit("/", 1)[-1], day(s["when"].get(x))] for x in g][:15],
+ "latest_grant": day(max(s["when"].values())) if s["when"] else None, "stores_read": t["read"]}
+
+
+@probe(id="consent.webcam", level="L2", family="security", tier="T1", collect="core", gate="consent.store", os=OS)
+def consent_webcam(h, facts):
+ """Apps granted camera access (TCC kTCCServiceCamera). Needs Full Disk Access."""
+ return _tcc_probe(h, "kTCCServiceCamera")
+
+
+@probe(id="consent.microphone", level="L2", family="security", tier="T1", collect="core", gate="consent.store", os=OS)
+def consent_microphone(h, facts):
+ """Apps granted microphone access (TCC kTCCServiceMicrophone). Needs Full Disk Access."""
+ return _tcc_probe(h, "kTCCServiceMicrophone")
+
+
+@probe(id="consent.screen_capture", level="L2", family="security", tier="T1", collect="core", gate="consent.store",
+ os=OS)
+def consent_screen_capture(h, facts):
+ """Apps granted Screen Recording (system TCC kTCCServiceScreenCapture). Needs Full Disk Access."""
+ return _tcc_probe(h, "kTCCServiceScreenCapture")
+
+
+@probe(id="consent.accessibility", level="L2", family="security", tier="T1", collect="core", gate="consent.store",
+ os=OS)
+def consent_accessibility(h, facts):
+ """Apps granted Accessibility control (system TCC kTCCServiceAccessibility): automation tools, launchers."""
+ return _tcc_probe(h, "kTCCServiceAccessibility")
+
+
+@probe(id="consent.location", level="L2", family="security", tier="T1", collect="core", gate="consent.store", os=OS)
+def consent_location(h, facts):
+ """Location Services clients: authorized / denied counts and authorized bundle ids (locationd clients.plist)."""
+ d = plist(LOCATIOND)
+ if not isinstance(d, dict):
+ return {"present": False}
+ auth, denied = [], 0
+ for k, v in d.items():
+ if not isinstance(v, dict):
+ continue
+ if v.get("Authorized") is True:
+ bid = v.get("BundleId") or (k.split(":", 2)[1][1:] if k.count(":") >= 2 else k)
+ auth.append(str(bid).rsplit("/", 1)[-1])
+ elif v.get("Authorized") is False:
+ denied += 1
+ return {"present": True, "clients": len(d), "granted": len(auth), "denied": denied, "items": sorted(auth)[:15]}
+
+
+_PM = ["1Password", "1Password 7", "Bitwarden", "KeePassXC", "Strongbox", "Dashlane", "LastPass", "Proton Pass",
+ "Enpass", "NordPass", "Keeper Password Manager", "MacPass"]
+
+
+@probe(id="pm.desktop", level="L1", family="security", tier="T0", collect="core", os=OS)
+def pm_desktop(h, facts):
+ """Password manager apps installed (Apple Passwords is built in and not counted)."""
+ found = [n for n in _PM if has_app(n)]
+ if isdir(H("Library", "Application Support", "Bitwarden CLI")):
+ found.append("Bitwarden CLI")
+ return {"present": bool(found), "managers": found}
+
+
+@probe(id="dev.ssh_dir_presence", level="L1", family="security", tier="T3", collect="core", os=OS)
+def dev_ssh_dir_presence(h, facts):
+ """~/.ssh presence and file count (keys never opened)."""
+ names = ls(H(".ssh"), 500)
+ if names is None:
+ return None
+ return {"present": True, "files": len(names), "has_config": "config" in names,
+ "private_key_like": sum(1 for n in names if n.startswith("id_") and not n.endswith(".pub"))}
+
+
+# ================================================================ network
+
+@probe(id="net.hosts_proxy", level="L1", family="network", tier="T0", collect="core", os=OS)
+def net_hosts_proxy(h, facts):
+ """/etc/hosts custom entry count and proxies configured on any network service."""
+ n = 0
+ try:
+ with open("/etc/hosts", encoding="utf-8", errors="replace") as f:
+ for line in f:
+ s = line.strip()
+ if s and not s.startswith("#") and not re.match(r"^(127\.0\.0\.1|::1|255\.255\.255\.255|fe80::1%lo0)\s+"
+ r"(localhost|broadcasthost)\s*$", s):
+ n += 1
+ except OSError:
+ pass
+ proxies = set()
+ for sv in (syscfg(h).get("NetworkServices") or {}).values():
+ px = sv.get("Proxies") or {}
+ for k in ("HTTPEnable", "HTTPSEnable", "SOCKSEnable", "ProxyAutoConfigEnable", "ProxyAutoDiscoveryEnable"):
+ if px.get(k) == 1:
+ proxies.add(k.replace("Enable", ""))
+ return {"present": True, "hosts_custom_entries": n, "proxies": sorted(proxies)}
+
+
+_VPN = ["Tailscale", "WireGuard", "Windscribe", "Mullvad VPN", "NordVPN", "ProtonVPN", "Proton VPN",
+ "Cloudflare WARP", "OpenVPN Connect", "Tunnelblick", "ExpressVPN", "Surfshark", "ZeroTier One", "Viscosity",
+ "GlobalProtect", "Cisco Secure Client", "FortiClient", "Zscaler"]
+
+
+@probe(id="net.vpn_clients", level="L1", family="network", tier="T0", collect="core", os=OS)
+def net_vpn_clients(h, facts):
+ """VPN / mesh clients installed and VPN network services configured."""
+ apps = [n for n in _VPN if has_app(n)]
+ svcs = collections.Counter()
+ for sv in (syscfg(h).get("NetworkServices") or {}).values():
+ if (sv.get("Interface") or {}).get("Type") == "VPN":
+ svcs[(sv.get("Interface") or {}).get("SubType") or "vpn"] += 1
+ ts = os.path.exists("/usr/local/bin/tailscale") or bool(has_app("Tailscale"))
+ return {"present": bool(apps or svcs or ts), "apps": apps, "vpn_services": dict(svcs), "tailscale_cli": ts}
+
+
+@probe(id="net.wifi_profiles", level="L2", family="network", tier="T0", collect="core", gate="net.hosts_proxy", os=OS)
+def net_wifi_profiles(h, facts):
+ """Preferred (remembered) Wi-Fi network count; SSIDs never emitted."""
+ w = _preferred_wifi(h)
+ if not w["ok"]:
+ return {"present": False}
+ return {"present": True, "count": w["count"]}
+
+
+@probe(id="net.adapters", level="L2", family="network", tier="T0", collect="extended", gate="net.hosts_proxy", os=OS)
+def net_adapters(h, facts):
+ """Configured network services by type (Wi-Fi, Ethernet dongles, Thunderbolt Bridge, VPN, phone tethering)."""
+ kinds = collections.Counter()
+ tether = 0
+ for sv in (syscfg(h).get("NetworkServices") or {}).values():
+ it = sv.get("Interface") or {}
+ hw = it.get("Hardware") or it.get("Type") or "?"
+ kinds["Wi-Fi" if hw == "AirPort" else hw] += 1
+ if re.search(r"iphone|pixel|galaxy|android", str(sv.get("UserDefinedName") or ""), re.I):
+ tether += 1
+ return {"present": bool(kinds), "services": sum(kinds.values()), "by_type": dict(kinds),
+ "phone_tethering_services": tether}
+
+
+@probe(id="net.dns", level="L2", family="network", tier="T0", collect="extended", gate="net.hosts_proxy", os=OS)
+def net_dns(h, facts):
+ """Resolver kinds from scutil --dns (public, local, Tailscale MagicDNS, router); addresses not emitted."""
+ t = run(h, ["scutil", "--dns"], 3000)
+ kinds = collections.Counter()
+ for ip in set(re.findall(r"nameserver\[\d+\]\s*:\s*(\S+)", t)):
+ if ip == "100.100.100.100":
+ kinds["tailscale"] += 1
+ elif ip in ("1.1.1.1", "1.0.0.1", "8.8.8.8", "8.8.4.4", "9.9.9.9", "208.67.222.222"):
+ kinds["public"] += 1
+ elif re.match(r"^(127\.|::1)", ip):
+ kinds["local"] += 1
+ elif re.match(r"^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|fe80)", ip):
+ kinds["lan"] += 1
+ else:
+ kinds["other"] += 1
+ return {"present": bool(kinds), "resolver_kinds": dict(kinds), "resolvers": len(re.findall(r"^resolver #", t, re.M))}
+
+
+@probe(id="net.tailscale", level="L2", family="network", tier="T1", collect="extended", gate="net.vpn_clients", os=OS)
+def net_tailscale(h, facts):
+ """Tailscale backend state and peer counts (tailscale status --json; peer names never emitted)."""
+ exe = next((p for p in ("/usr/local/bin/tailscale", "/opt/homebrew/bin/tailscale",
+ "/Applications/Tailscale.app/Contents/MacOS/Tailscale") if os.path.exists(p)), None)
+ if not exe:
+ return {"present": False}
+ t = run(h, [exe, "status", "--json"], 4000)
+ try:
+ d = json.loads(t)
+ except ValueError:
+ return {"present": False}
+ peers = list((d.get("Peer") or {}).values())
+ oses = collections.Counter(str(p.get("OS") or "?") for p in peers)
+ return {"present": True, "backend": d.get("BackendState"), "peers": len(peers),
+ "online_peers": sum(1 for p in peers if p.get("Online")), "peer_os": dict(oses),
+ "version": str(d.get("Version") or "").split("-")[0]}
+
+
+# ================================================================ hardware
+
+@probe(id="hw.system", level="L1", family="hardware", tier="T0", collect="core", os=OS)
+def hw_system(h, facts):
+ """Model identifier, chip, memory, core counts (sysctl via ctypes, no spawn)."""
+ model = sysctl_str("hw.model")
+ if not model:
+ return None
+ mem = sysctl_int("hw.memsize") or 0
+ return {"present": True, "manufacturer": "Apple", "model": model, "chip": sysctl_str("machdep.cpu.brand_string"),
+ "ram_gb": round(mem / 2 ** 30), "cpus": sysctl_int("hw.ncpu", ctypes.c_int),
+ "laptop": _has_battery(h),
+ "virtual": bool(sysctl_int("kern.hv_vmm_present", ctypes.c_int))}
+
+
+def _has_battery(h):
+ """pmset -g batt lists InternalBattery on laptops (Apple silicon model ids do not say MacBook)."""
+ return memo(h, "has_battery", lambda: "InternalBattery" in run(h, ["pmset", "-g", "batt"], 2000))
+
+
+@probe(id="hw.cpu", level="L2", family="hardware", tier="T0", collect="core", gate="hw.system", os=OS)
+def hw_cpu(h, facts):
+ """Chip and performance/efficiency core split (sysctl perflevels + SPHardwareDataType marketing name)."""
+ sp = (sp_json(h, "SPHardwareDataType").get("SPHardwareDataType") or [{}])[0]
+ return {"present": True, "chip": sp.get("chip_type") or sysctl_str("machdep.cpu.brand_string"),
+ "machine_name": sp.get("machine_name"), "model_number": sp.get("model_number"),
+ "p_cores": sysctl_int("hw.perflevel0.physicalcpu", ctypes.c_int),
+ "e_cores": sysctl_int("hw.perflevel1.physicalcpu", ctypes.c_int),
+ "logical": sysctl_int("hw.logicalcpu", ctypes.c_int), "boot_rom": sp.get("boot_rom_version")}
+
+
+@probe(id="hw.ram", level="L2", family="hardware", tier="T0", collect="core", gate="hw.system", os=OS)
+def hw_ram(h, facts):
+ """Unified memory size (hw.memsize). Apple silicon memory is soldered and shared with the GPU."""
+ b = sysctl_int("hw.memsize") or 0
+ return {"present": b > 0, "total_gb": round(b / 2 ** 30), "unified": sysctl_int("hw.optional.arm64", ctypes.c_int) == 1}
+
+
+@probe(id="hw.gpu", level="L1", family="hardware", tier="T0", collect="core", os=OS)
+def hw_gpu(h, facts):
+ """GPU. On Apple silicon it is integrated with unified memory; vram_gb is the GPU-addressable share
+ (Metal recommendedMaxWorkingSetSize is about 2/3 of RAM up to 36 GB, 3/4 above)."""
+ arm = sysctl_int("hw.optional.arm64", ctypes.c_int) == 1
+ ram = (sysctl_int("hw.memsize") or 0) / 2 ** 30
+ if not arm:
+ return {"present": True, "name": None, "unified_memory": False, "vram_gb": None}
+ share = 0.75 if ram > 36 else 0.67
+ return {"present": True, "name": (sysctl_str("machdep.cpu.brand_string") or "Apple") + " GPU",
+ "unified_memory": True, "vram_gb": round(ram * share, 1), "vram_basis": f"{int(share * 100)}% of unified RAM"}
+
+
+def _displays(h):
+ return memo(h, "sp_displays", lambda: sp_json(h, "SPDisplaysDataType", timeout_ms=8000).get("SPDisplaysDataType") or [])
+
+
+@probe(id="hw.monitors", level="L2", family="hardware", tier="T0", collect="extended", gate="hw.system", os=OS)
+def hw_monitors(h, facts):
+ """Connected displays (resolution, built-in vs external) and GPU core count (SPDisplaysDataType)."""
+ gpus = _displays(h)
+ mons = []
+ cores = None
+ for g in gpus:
+ cores = cores or g.get("sppci_cores")
+ for d in g.get("spdisplays_ndrvs") or []:
+ mons.append({"name": d.get("_name"), "internal": d.get("spdisplays_connection_type") == "spdisplays_internal",
+ "resolution": d.get("_spdisplays_resolution") or d.get("spdisplays_resolution"),
+ "pixels": d.get("_spdisplays_pixels"), "main": d.get("spdisplays_main") == "spdisplays_yes",
+ "retina": "Retina" in str(d.get("spdisplays_display_type") or d.get("_spdisplays_display-type") or "")})
+ return {"present": bool(mons), "count": len(mons), "external": sum(1 for m in mons if not m["internal"]),
+ "monitors": mons, "gpu_cores": int(cores) if str(cores or "").isdigit() else cores}
+
+
+@probe(id="hw.monitor_history", level="L2", family="hardware", tier="T0", collect="extended", gate="hw.system", os=OS)
+def hw_monitor_history(h, facts):
+ """Distinct displays WindowServer has configured on this install (com.apple.windowserver.displays).
+ No first/last dates are stored, so derive's change detector does not use it."""
+ d = plist("/Library/Preferences/com.apple.windowserver.displays.plist") or {}
+ used = ((d.get("DisplayUUIDMappings_v3") or {}).get("UsedUUIDs")) or []
+ cfgs = ((d.get("DisplayAnyUserSets") or {}).get("Configs")) or []
+ return {"present": bool(d), "display_uuids_seen": len(used), "arrangements": len(cfgs)}
+
+
+@probe(id="hw.battery", level="L1", family="hardware", tier="T0", collect="core", os=OS)
+def hw_battery(h, facts):
+ """Internal battery present (laptop)."""
+ if not _has_battery(h):
+ return None
+ return {"present": True, "laptop": True}
+
+
+@probe(id="hw.battery_report", level="L2", family="hardware", tier="T1", collect="extended", gate="hw.battery", os=OS)
+def hw_battery_report(h, facts):
+ """Battery health: cycle count, condition, max capacity %, charge state, power settings, AlDente (SPPowerDataType)."""
+ sp = sp_json(h, "SPPowerDataType").get("SPPowerDataType") or []
+ bat = next((x for x in sp if x.get("_name") == "spbattery_information"), {})
+ pw = next((x for x in sp if x.get("_name") == "sppower_information"), {})
+ hi = bat.get("sppower_battery_health_info") or {}
+ ci = bat.get("sppower_battery_charge_info") or {}
+ cap = str(hi.get("sppower_battery_health_maximum_capacity") or "").rstrip("%")
+ if not hi:
+ return {"present": False}
+ return {"present": True, "cycle_count": hi.get("sppower_battery_cycle_count"),
+ "condition": hi.get("sppower_battery_health"),
+ "max_capacity_pct": int(cap) if cap.isdigit() else None,
+ "charge_pct": ci.get("sppower_battery_state_of_charge"),
+ "charging": ci.get("sppower_battery_is_charging") == "TRUE",
+ "on_ac": (pw.get("AC Power") or {}).get("Current Power Source") == "TRUE",
+ "low_power_mode": {"ac": (pw.get("AC Power") or {}).get("LowPowerMode"),
+ "battery": (pw.get("Battery Power") or {}).get("LowPowerMode")},
+ "charge_limiter": [n for n in ("AlDente", "Battery Toolkit", "Bclm") if has_app(n)]}
+
+
+@probe(id="hw.power_plan", level="L2", family="hardware", tier="T0", collect="core", gate="hw.system", os=OS)
+def hw_power_plan(h, facts):
+ """pmset settings per power source: powermode (low/high), sleep and display sleep, Power Nap, wake-on-LAN."""
+ t = run(h, ["pmset", "-g", "custom"], 3000)
+ out, cur = {}, None
+ for line in t.splitlines():
+ if line.endswith(":") and not line.startswith(" "):
+ cur = {"Battery Power:": "battery", "AC Power:": "ac", "UPS Power:": "ups"}.get(line.strip())
+ if cur:
+ out[cur] = {}
+ continue
+ m = re.match(r"^\s*(powermode|lowpowermode|highpowermode|sleep|displaysleep|powernap|womp|standby|hibernatemode)"
+ r"\s+(\d+)", line)
+ if cur and m:
+ out[cur][m.group(1)] = int(m.group(2))
+ return {"present": bool(out), **out}
+
+
+@probe(id="hw.disks", level="L2", family="hardware", tier="T0", collect="core", gate="hw.system", os=OS)
+def hw_disks(h, facts):
+ """Data volume size and free space (statvfs); external volumes mounted under /Volumes."""
+ vols = []
+ for name, p in (("Data", "/System/Volumes/Data"),):
+ try:
+ s = os.statvfs(p)
+ except OSError:
+ continue
+ size = s.f_blocks * s.f_frsize
+ free = s.f_bavail * s.f_frsize
+ vols.append({"name": name, "size_gb": round(size / 1e9), "free_gb": round(free / 1e9),
+ "free_pct": round(100 * free / size, 1) if size else None})
+ ext = [n for n in ls("/Volumes") or [] if not n.startswith(".") and not os.path.islink(os.path.join("/Volumes", n))]
+ return {"present": bool(vols), "volumes": vols, "external_mounted": len(ext)}
+
+
+@probe(id="hw.bluetooth", level="L2", family="hardware", tier="T1", collect="extended", gate="hw.system", os=OS)
+def hw_bluetooth(h, facts):
+ """Bluetooth power and paired device counts by minor type (names never emitted)."""
+ bt = (sp_json(h, "SPBluetoothDataType").get("SPBluetoothDataType") or [{}])[0]
+ ctl = bt.get("controller_properties") or {}
+ types, conn, total = collections.Counter(), 0, 0
+ for key, connected in (("device_connected", True), ("device_not_connected", False)):
+ for d in bt.get(key) or []:
+ for _n, props in (d.items() if isinstance(d, dict) else []):
+ total += 1
+ conn += connected
+ types[str((props or {}).get("device_minorType") or "?")] += 1
+ return {"present": bool(bt), "power": ctl.get("controller_state"), "paired": total, "connected": conn,
+ "by_type": dict(types)}
+
+
+_PERIPH = ["Logi Options+", "Logi Options", "Logitech G HUB", "lghub", "Razer Synapse", "SteelSeries GG",
+ "iCUE", "Corsair iCUE", "Elgato Control Center", "Elgato Stream Deck", "Stream Deck", "Wooting",
+ "VIA", "QMK Toolbox", "Karabiner-Elements", "Logi Tune"]
+
+
+@probe(id="periph.rgb_suites", level="L2", family="hardware", tier="T0", collect="core", gate="hw.system", os=OS)
+def periph_rgb_suites(h, facts):
+ """Peripheral vendor suites (Logitech, Razer, SteelSeries, Corsair, Elgato, keyboard firmware tools)."""
+ found = sorted({n for n in _PERIPH if has_app(n)})
+ return {"present": bool(found), "suites": found}
+
+
+_TUNE = ["AlDente", "BetterDisplay", "iStat Menus", "Stats", "Macs Fan Control", "TG Pro", "Lunar", "MonitorControl",
+ "Amphetamine", "Hand Mirror", "Rectangle", "Magnet", "Moom", "BetterTouchTool", "Bartender 5", "Ice",
+ "Hammerspoon", "Raycast", "Alfred 5", "Keyboard Maestro"]
+
+
+@probe(id="tuning.mac_utilities", level="L1", family="hardware", tier="T0", collect="core", os=OS)
+def tuning_mac_utilities(h, facts):
+ """Power-user system utilities: battery/display/fan control, window managers, launchers, automation."""
+ found = [n for n in _TUNE if has_app(n)]
+ return {"present": bool(found), "found": found}
+
+
+@probe(id="hw.sleep_study", level="L2", family="hardware", tier="T1", collect="deep", gate="hw.battery", os=OS,
+ timeout_ms=10000)
+def hw_sleep_study(h, facts):
+ """Sleep / wake / dark-wake events per day from pmset -g log (retained about a week; ~2.5 s spawn)."""
+ t = run(h, ["pmset", "-g", "log"], 12000)
+ rx = re.compile(r"^(\d{4}-\d\d-\d\d) (\d\d):\d\d:\d\d [+-]\d{4} (Sleep|Wake|DarkWake)\s{2,}")
+ days = collections.defaultdict(collections.Counter)
+ wake_hours = [0] * 24
+ for line in t.splitlines():
+ m = rx.match(line)
+ if m:
+ days[m.group(1)][m.group(3)] += 1
+ if m.group(3) == "Wake":
+ wake_hours[int(m.group(2))] += 1
+ if not days:
+ return {"present": False}
+ tot = collections.Counter()
+ for c in days.values():
+ tot.update(c)
+ return {"present": True, "days": len(days), "first_day": min(days), "last_day": max(days),
+ "sleeps": tot["Sleep"], "user_wakes": tot["Wake"], "dark_wakes": tot["DarkWake"],
+ "user_wakes_per_day": round(tot["Wake"] / len(days), 1), "wake_hours": wake_hours}
+
+
+# ================================================================ health
+
+_DIAG_DIRS = ("/Library/Logs/DiagnosticReports", "/Library/Logs/DiagnosticReports/Retired",
+ "~/Library/Logs/DiagnosticReports", "~/Library/Logs/DiagnosticReports/Retired")
+_NAME_RX = re.compile(r"^(.+?)[-_](\d{4}-\d\d-\d\d)-(\d{6})")
+
+
+def _diag(h):
+ def build():
+ rows = []
+ for d in _DIAG_DIRS:
+ d = os.path.expanduser(d)
+ for n in ls(d, 5000) or []:
+ p = os.path.join(d, n)
+ ext = n.rsplit(".", 1)[-1] if "." in n else ""
+ if ext not in ("ips", "crash", "panic", "hang", "spin", "diag", "shutdownStall", "cpu_resource"):
+ continue
+ m = _NAME_RX.match(n)
+ app = m.group(1) if m else n.split(".")[0]
+ ts = mtime(p) or 0
+ bug = None
+ if ext == "ips":
+ try:
+ with open(p, "rb") as f:
+ bug = json.loads(f.readline(2000).decode("utf-8", "replace")).get("bug_type")
+ except (OSError, ValueError):
+ bug = None
+ kind = ("panic" if ext == "panic" or bug == "210" else
+ "crash" if ext == "crash" or bug in ("309", "109") else
+ "hang" if ext in ("hang", "spin") or bug in ("298", "228") else
+ "stall" if ext == "shutdownStall" else "resource")
+ rows.append((app, kind, ts))
+ return rows
+ return memo(h, "diag", build)
+
+
+@probe(id="health.dumps", level="L1", family="health", tier="T1", collect="core", os=OS)
+def health_dumps(h, facts):
+ """DiagnosticReports counts by kind. count_30d is kernel panics only (the macOS analogue of a bugcheck dump)."""
+ rows = _diag(h)
+ now = time.time()
+ by = collections.Counter(k for _, k, _ in rows)
+ by30 = collections.Counter(k for _, k, t in rows if now - t <= 30 * 86400)
+ return {"present": True, "reports": len(rows), "by_kind": dict(by), "by_kind_30d": dict(by30),
+ "count_30d": by30.get("panic", 0), "panics_total": by.get("panic", 0),
+ "oldest": day(min((t for _, _, t in rows), default=0))}
+
+
+@probe(id="health.wer", level="L2", family="health", tier="T1", collect="core", gate="health.dumps", os=OS)
+def health_wer(h, facts):
+ """App crashes and hangs by process name (DiagnosticReports file names and .ips bug_type)."""
+ rows = _diag(h)
+ crashes = collections.Counter(a for a, k, _ in rows if k == "crash")
+ hangs = collections.Counter(a for a, k, _ in rows if k == "hang")
+ now = time.time()
+ c30 = collections.Counter(a for a, k, t in rows if k == "crash" and now - t <= 30 * 86400)
+ return {"present": bool(crashes or hangs), "crashes": sum(crashes.values()), "hangs": sum(hangs.values()),
+ "crashes_30d": sum(c30.values()),
+ "crashes_by_app": [[a, n] for a, n in crashes.most_common(8)],
+ "hangs_by_app": [[a, n] for a, n in hangs.most_common(5)],
+ "max_repeat": crashes.most_common(1)[0][1] if crashes else 0}
+
+
+# ================================================================ usage
+
+@probe(id="boot.uptime", level="L1", family="usage", tier="T0", collect="core", os=OS)
+def boot_uptime(h, facts):
+ """Time since boot (CLOCK_MONOTONIC counts sleep) and awake time (CLOCK_UPTIME_RAW excludes it)."""
+ bt = boottime()
+ mono = time.clock_gettime(time.CLOCK_MONOTONIC)
+ awake = time.clock_gettime(time.CLOCK_UPTIME_RAW)
+ return {"present": True, "last_boot": iso(bt), "uptime_h": round(mono / 3600, 1),
+ "awake_h": round(awake / 3600, 1), "awake_share": round(awake / mono, 2) if mono else None}
+
+
+def _wtmp(h):
+ """(reboots, shutdowns, wtmp_begins) epoch lists from one `last reboot` (it prints both kinds)."""
+ def build():
+ t = run(h, ["last", "reboot"], 4000)
+ now = dt.datetime.now()
+ out = {"reboot": [], "shutdown": []}
+ for line in t.splitlines():
+ m = re.match(r"^(reboot|shutdown) time\s+\w{3} (\d+) (\w{3}) (\d\d):(\d\d)", line)
+ if not m:
+ continue
+ try:
+ d = dt.datetime.strptime(f"{m.group(2)} {m.group(3)} {now.year} {m.group(4)}:{m.group(5)}", "%d %b %Y %H:%M")
+ except ValueError:
+ continue
+ if d > now + dt.timedelta(days=1):
+ d = d.replace(year=now.year - 1)
+ out[m.group(1)].append(d.timestamp())
+ m = re.search(r"wtmp begins \w{3} (\w{3}) +(\d+) [\d:]+ \S+ (\d{4})", t)
+ begins = None
+ if m:
+ try:
+ begins = dt.datetime.strptime(" ".join(m.groups()), "%b %d %Y").timestamp()
+ except ValueError:
+ pass
+ return out["reboot"], out["shutdown"], begins
+ return memo(h, "wtmp", build)
+
+
+@probe(id="eventlog.power_history", level="L2", family="usage", tier="T1", collect="extended", gate="boot.uptime", os=OS)
+def eventlog_power_history(h, facts):
+ """Boots and shutdowns (last reboot / last shutdown, wtmp) and sleep / wake counts since boot (pmset -g stats)."""
+ now = time.time()
+ boots, shut, begins = _wtmp(h)
+ st = run(h, ["pmset", "-g", "stats"], 3000)
+ g = lambda k: int(m.group(1)) if (m := re.search(k + r":\s*(\d+)", st)) else None
+ return {"present": bool(boots or st), "boots_30d": sum(1 for t in boots if now - t <= 30 * 86400),
+ "boots": len(boots), "shutdowns_30d": sum(1 for t in shut if now - t <= 30 * 86400),
+ "wtmp_begins": day(begins), "system_log_oldest": day(begins),
+ "sleeps_since_boot": g("Sleep Count"), "wakes": g("User Wake Count"),
+ "dark_wakes_since_boot": g("Dark Wake Count"),
+ "note": "wakes are user wakes since the last boot, not a 30-day window"}
+
+
+@probe(id="l3.power_event_split", level="L2", family="usage", tier="T1", collect="extended", gate="boot.uptime", os=OS)
+def l3_power_event_split(h, facts):
+ """Kernel panics (crash) vs shutdown stalls. macOS records no user-visible hard power-off count without
+ the unified log, so power_removed is not reported."""
+ rows = _diag(h)
+ now = time.time()
+ return {"present": True, "crash": sum(1 for _, k, _ in rows if k == "panic"),
+ "crash_30d": sum(1 for _, k, t in rows if k == "panic" and now - t <= 30 * 86400),
+ "shutdown_stalls": sum(1 for _, k, _ in rows if k == "stall"), "button_held": None}
+
+
+KNOWLEDGE = ("Library", "Application Support", "Knowledge", "knowledgeC.db")
+SCREENTIME = ("Library", "Application Support", "com.apple.remotemanagementd", "RMAdminStore-Local.sqlite")
+
+
+@probe(id="usage.screen_time_store", level="L1", family="usage", tier="T0", collect="core", os=OS)
+def usage_screen_time_store(h, facts):
+ """knowledgeC.db (app focus, display state) and Screen Time store: presence and readability (Full Disk Access)."""
+ k = fmeta(H(*KNOWLEDGE))
+ s = fmeta(H(*SCREENTIME))
+ biome = isdir(H("Library", "Biome", "streams", "restricted", "App.InFocus"))
+ return {"present": k["present"] or s["present"], "knowledgec": k, "screentime": s, "biome_app_infocus": biome}
+
+
+def _kc(h):
+ """App focus and backlight intervals from knowledgeC.db (/app/usage, /display/isBacklit), last 90 days."""
+ def build():
+ p = H(*KNOWLEDGE)
+ cut = time.time() - 90 * 86400 - MAC_EPOCH
+ apps = h.sqlite(p, "select ZVALUESTRING, ZSTARTDATE, ZENDDATE from ZOBJECT where ZSTREAMNAME in "
+ "('/app/usage', '/app/inFocus') and ZSTARTDATE > ? and ZENDDATE > ZSTARTDATE", (cut,),
+ timeout_ms=4000)
+ if apps is None:
+ return None
+ disp = h.sqlite(p, "select ZSTARTDATE, ZENDDATE from ZOBJECT where ZSTREAMNAME='/display/isBacklit' "
+ "and ZVALUEINTEGER=1 and ZSTARTDATE > ? and ZENDDATE > ZSTARTDATE", (cut,), timeout_ms=4000) or []
+ return {"apps": [(a, s + MAC_EPOCH, e + MAC_EPOCH) for a, s, e in apps if a],
+ "display": [(s + MAC_EPOCH, e + MAC_EPOCH) for s, e in disp]}
+ return memo(h, "knowledgec", build)
+
+
+def _app_label(bid):
+ return str(bid).rsplit(".", 1)[-1] if bid else "?"
+
+
+@probe(id="userassist.focus", level="L2", family="usage", tier="T1", collect="extended",
+ gate="usage.screen_time_store", os=OS, timeout_ms=5000)
+def userassist_focus(h, facts):
+ """Per-app foreground hours and sessions over 90 days from knowledgeC /app/usage. Needs Full Disk Access."""
+ kc = _kc(h)
+ if not kc or not kc["apps"]:
+ return {"present": False, "needs_fda": kc is None}
+ hrs, n = collections.Counter(), collections.Counter()
+ now = time.time()
+ h30 = collections.Counter()
+ first = min(s for _, s, _ in kc["apps"])
+ for a, s, e in kc["apps"]:
+ d = min(e - s, 8 * 3600) / 3600
+ hrs[a] += d
+ n[a] += 1
+ if now - s <= 30 * 86400:
+ h30[a] += d
+ return {"present": True, "apps": len(hrs), "total_focus_h": round(sum(hrs.values()), 1),
+ "focus_h_30d": round(sum(h30.values()), 1), "since": day(first),
+ "top": [[a, round(x, 1), n[a]] for a, x in hrs.most_common(15)]}
+
+
+@probe(id="l3.top_apps_by_time", level="L2", family="usage", tier="T1", collect="extended",
+ gate="usage.screen_time_store", os=OS, timeout_ms=5000)
+def l3_top_apps_by_time(h, facts):
+ """Top apps by foreground hours in the last 30 days (knowledgeC). Needs Full Disk Access."""
+ kc = _kc(h)
+ if not kc or not kc["apps"]:
+ return {"present": False, "needs_fda": kc is None}
+ now = time.time()
+ c = collections.Counter()
+ for a, s, e in kc["apps"]:
+ if now - s <= 30 * 86400:
+ c[a] += min(e - s, 8 * 3600) / 3600
+ return {"present": bool(c), "top": [{"app": a, "name": _app_label(a), "hours": round(x, 1)} for a, x in c.most_common(10)]}
+
+
+@probe(id="usage.screen_on", level="L2", family="usage", tier="T1", collect="extended",
+ gate="usage.screen_time_store", os=OS, timeout_ms=5000)
+def usage_screen_on(h, facts):
+ """Display-on hours per day and start-hour histogram (knowledgeC /display/isBacklit). Needs Full Disk Access."""
+ kc = _kc(h)
+ if not kc or not kc["display"]:
+ return {"present": False, "needs_fda": kc is None}
+ per_day = collections.Counter()
+ hours = [0] * 24
+ for s, e in kc["display"]:
+ per_day[day(s)] += min(e - s, 16 * 3600) / 3600
+ hours[dt.datetime.fromtimestamp(s).hour] += 1
+ return {"present": True, "days": len(per_day), "avg_h_per_day": round(sum(per_day.values()) / len(per_day), 1),
+ "max_h_day": round(max(per_day.values()), 1), "hours": hours}
+
+
+def _mdls_apps(h):
+ """kMDItemLastUsedDate / kMDItemUseCount / kMDItemDateAdded for every app bundle, one mdls spawn."""
+ def build():
+ paths = sorted(set(app_paths().values()))
+ paths = [p for p in paths if not p.startswith("/System/")] + [p for p in paths if p.startswith("/System/")]
+ out = {}
+ for i in range(0, len(paths), 150):
+ chunk = paths[i:i + 150]
+ t = run(h, ["mdls", "-name", "kMDItemLastUsedDate", "-name", "kMDItemUseCount", "-name", "kMDItemDateAdded",
+ *chunk], 8000)
+ vals = re.findall(r"^(kMDItem\w+)\s+=\s+(.*)$", t, re.M)
+ for j, p in enumerate(chunk):
+ block = dict(vals[j * 3:(j + 1) * 3]) if len(vals) >= (j + 1) * 3 else {}
+ def pd(v):
+ try:
+ return dt.datetime.strptime(v, "%Y-%m-%d %H:%M:%S %z").timestamp()
+ except (TypeError, ValueError):
+ return None
+ uc = block.get("kMDItemUseCount")
+ out[p] = {"last_used": pd(block.get("kMDItemLastUsedDate")), "use_count": int(uc) if (uc or "").isdigit() else 0,
+ "added": pd(block.get("kMDItemDateAdded"))}
+ return out
+ return memo(h, "mdls_apps", build)
+
+
+@probe(id="bam.last_run", level="L2", family="usage", tier="T1", collect="extended", gate="boot.uptime", os=OS,
+ timeout_ms=8000)
+def bam_last_run(h, facts):
+ """Last-used date and launch count per app from Spotlight metadata (kMDItemLastUsedDate / kMDItemUseCount).
+ No Full Disk Access needed. Launch count is Finder/LaunchServices opens, not focus time."""
+ m = _mdls_apps(h)
+ now = time.time()
+ used = {p: v for p, v in m.items() if v["last_used"]}
+ top = sorted(used.items(), key=lambda kv: -kv[1]["use_count"])[:15]
+ return {"present": bool(used), "apps_indexed": len(m), "apps_ever_used": len(used),
+ "used_7d": sum(1 for v in used.values() if now - v["last_used"] <= 7 * 86400),
+ "used_30d": sum(1 for v in used.values() if now - v["last_used"] <= 30 * 86400),
+ "never_used": len(m) - len(used),
+ "top": [[os.path.basename(p)[:-4], v["use_count"], day(v["last_used"])] for p, v in top]}
diff --git a/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/derive.py b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/derive.py
new file mode 100644
index 00000000000..ed24a05536a
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/derive.py
@@ -0,0 +1,1631 @@
+"""L3 insights: persona derivations (reports/14-triage.md section 3), the fresh-vs-old classifier
+(section 4) and the wave-2 derivations from reports/13-gap-hunt.md.
+
+Every rule is pure: it reads only the facts dict ({probe_id: value} for probes with status ok)
+and returns {"claim", "strength", "value"} or None. Probe value shapes differ between spec modules,
+so the accessors below accept several key spellings and fall back to counting lists.
+"""
+from __future__ import annotations
+
+import json
+import re
+from datetime import datetime, timedelta, timezone
+
+from userscan.registry import insight
+
+OPERATOR_TOKENS = ("hn-e2e", "ns960", "ns923", "\\lhm", "/lhm", "\\shots", "user-insights-lab",
+ "\\hermes-", "/hermes-", ".hermes-test")
+
+GAME_EXE_HINTS = ("steam", "game", "cs2", "cyberpunk", "f1_", "forza", "apex", "valorant", "fortnite",
+ "eldenring", "gta", "rdr2", "arc", "battlenet", "epicgames", "riot")
+
+
+# ---------------------------------------------------------------- accessors
+
+def _txt(v) -> str:
+ try:
+ return json.dumps(v, default=str).lower()
+ except Exception:
+ return str(v).lower()
+
+
+def _get(v, *keys, default=None):
+ """First present key at the top level, then one level down."""
+ if not isinstance(v, dict):
+ return default
+ for k in keys:
+ if k in v and v[k] not in (None, ""):
+ return v[k]
+ for sub in v.values():
+ if isinstance(sub, dict):
+ for k in keys:
+ if k in sub and sub[k] not in (None, ""):
+ return sub[k]
+ return default
+
+
+def _num(x, default=None):
+ if x is None or isinstance(x, bool):
+ return default if x is None else int(x)
+ if isinstance(x, (int, float)):
+ return x
+ if isinstance(x, str):
+ m = re.search(r"-?\d+(?:\.\d+)?", x.replace(",", ""))
+ return float(m.group()) if m else default
+ if isinstance(x, (list, tuple, set)):
+ return len(x)
+ if isinstance(x, dict):
+ for k in ("count", "n", "total", "value", "len"):
+ if k in x and isinstance(x[k], (int, float)) and not isinstance(x[k], bool):
+ return x[k]
+ return len(x)
+ return default
+
+
+def _cnt(v, *keys, default=None):
+ """Numeric value under any of keys (a list counts as its length)."""
+ if v is None:
+ return default
+ if keys:
+ got = _get(v, *keys)
+ if got is not None:
+ n = _num(got)
+ return default if n is None else n
+ return default
+ return _num(v, default)
+
+
+def _truth(v, *keys) -> bool:
+ got = _get(v, *keys)
+ if isinstance(got, str):
+ return got.strip().lower() not in ("", "0", "false", "no", "none", "off", "disabled", "absent")
+ if isinstance(got, (list, dict)):
+ return len(got) > 0
+ return bool(got)
+
+
+def _names(v, *keys) -> list:
+ """Flatten a list of names or dicts with name-like fields into lower-case strings."""
+ src = _get(v, *keys) if keys else v
+ if src is None or isinstance(src, (bool, int, float)):
+ return []
+ if isinstance(src, dict):
+ items = list(src.keys()) if all(not isinstance(x, (dict, list)) for x in src.values()) else list(src.values())
+ elif isinstance(src, (list, tuple)):
+ items = list(src)
+ else:
+ items = [src]
+ out = []
+ for it in items:
+ if isinstance(it, dict):
+ n = it.get("name") or it.get("app") or it.get("DisplayName") or it.get("display_name") or it.get("id") \
+ or it.get("exe") or it.get("path") or it.get("product") or it.get("title")
+ if n:
+ out.append(str(n).lower())
+ elif it is not None:
+ out.append(str(it).lower())
+ return out
+
+
+_EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
+
+
+def _dt(x):
+ """Parse ISO text, /Date(ms)/, MM/DD/YYYY, epoch s/ms, or FILETIME into an aware datetime."""
+ if x is None or isinstance(x, bool):
+ return None
+ if isinstance(x, datetime):
+ return x if x.tzinfo else x.replace(tzinfo=timezone.utc)
+ if isinstance(x, dict):
+ for k in ("DateTime", "value", "date", "iso", "utc"):
+ if k in x:
+ return _dt(x[k])
+ return None
+ if isinstance(x, (int, float)):
+ n = float(x)
+ try:
+ if n > 1e16:
+ return _EPOCH + timedelta(microseconds=(n - 116444736000000000) / 10)
+ if n > 1e11:
+ return _EPOCH + timedelta(milliseconds=n)
+ if n > 1e8:
+ return _EPOCH + timedelta(seconds=n)
+ except (OverflowError, ValueError):
+ return None
+ return None
+ s = str(x).strip()
+ m = re.search(r"/Date\((-?\d+)", s)
+ if m:
+ return _dt(int(m.group(1)))
+ m = re.match(r"(\d{1,2})/(\d{1,2})/(\d{4})", s)
+ if m:
+ try:
+ return datetime(int(m.group(3)), int(m.group(1)), int(m.group(2)), tzinfo=timezone.utc)
+ except ValueError:
+ return None
+ m = re.match(r"(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?", s)
+ if m:
+ try:
+ y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
+ hh, mm, ss = int(m.group(4) or 0), int(m.group(5) or 0), int(m.group(6) or 0)
+ return datetime(y, mo, d, hh, mm, ss, tzinfo=timezone.utc)
+ except ValueError:
+ return None
+ if re.fullmatch(r"\d{8}", s):
+ try:
+ return datetime(int(s[:4]), int(s[4:6]), int(s[6:]), tzinfo=timezone.utc)
+ except ValueError:
+ return None
+ if re.fullmatch(r"\d{9,18}", s):
+ return _dt(int(s))
+ return None
+
+
+def _date_of(v, *keys):
+ if v is None:
+ return None
+ if not isinstance(v, dict):
+ return _dt(v)
+ return _dt(_get(v, *keys))
+
+
+def _now():
+ return datetime.now(timezone.utc)
+
+
+def _days(d):
+ return None if d is None else (_now() - d).total_seconds() / 86400.0
+
+
+def _iso(d):
+ return d.date().isoformat() if d else None
+
+
+def _operator(s: str) -> bool:
+ s = s.lower()
+ return any(t in s for t in OPERATOR_TOKENS)
+
+
+def _sessions(v):
+ return _cnt(v, "sessions", "session_count", "n_sessions", "sessions_total", "total_sessions",
+ "conversations", "threads", "count")
+
+
+def _sessions_30d(v):
+ return _cnt(v, "sessions_30d", "sessions_last_30d", "last_30d", "recent_30d", "n_30d", "sessions_recent")
+
+
+def _share(v, *cats):
+ """Sum of category shares (0..1) from l3.browser_category_share-like values."""
+ if not isinstance(v, dict):
+ return None
+ shares = _get(v, "shares", "share", "category_share", "categories") or v
+ if not isinstance(shares, dict):
+ return None
+ tot = 0.0
+ seen = False
+ for c in cats:
+ x = shares.get(c)
+ if isinstance(x, dict):
+ x = x.get("share", x.get("pct"))
+ n = _num(x)
+ if n is not None:
+ seen = True
+ tot += n / 100.0 if n > 1 else n
+ return tot if seen else None
+
+
+def _res(claim, strength="weak", value=None):
+ return {"claim": claim, "strength": strength, "value": value}
+
+
+_VIRTUAL = ("remote", "basic", "virtual", "indirect", "parsec", "meta")
+
+
+def _hw_changes(f):
+ """(gpu_changes, monitor_changes, image_devices) from PnP first/last dates.
+ change = device first seen > 2 d after the tenure anchor; image device = gone and last seen before the OS install."""
+ a, _ = _tenure_anchor(f)
+ inst = _date_of(f.get("os.install_date"), "install_date", "InstallDate", "date", "value")
+ out = [0, 0, 0]
+ for i, (pid, key, name) in enumerate((("hw.gpu_history", "adapters", "name"), ("hw.monitor_history", "monitors", "pnp"))):
+ v = f.get(pid)
+ rows = _get(v, key) if isinstance(v, dict) else None
+ if not isinstance(rows, list):
+ continue
+ for r in rows:
+ if not isinstance(r, dict) or any(w in str(r.get(name, "")).lower() for w in _VIRTUAL):
+ continue
+ first, last = _dt(r.get("first")), _dt(r.get("last"))
+ if inst and last and not r.get("present") and last < inst - timedelta(days=1):
+ out[2] += 1
+ elif a and first and first > a + timedelta(days=2) and (_days(first) or 0) <= 183:
+ out[i] += 1
+ return tuple(out)
+
+
+# ---------------------------------------------------------------- 1 managed_vs_personal
+
+@insight(id="persona.managed_vs_personal",
+ inputs=["work.join_state", "work.mdm", "work.security_agents", "work.policies", "acct.account_type",
+ "onedrive.accounts", "comms.teams_launched", "work.edition_org"])
+def managed_vs_personal(f):
+ """Employer-managed vs personal machine. Edition alone is not a signal."""
+ if not any(k in f for k in ("work.join_state", "work.mdm", "work.security_agents", "onedrive.accounts")):
+ return None
+ score, why = 0, []
+ js = f.get("work.join_state")
+ if js is not None:
+ t = _txt(js)
+ joined = _truth(js, "domain_joined", "DomainJoined", "azure_ad_joined", "AzureAdJoined", "aad_joined",
+ "entra_joined", "joined")
+ state = str(_get(js, "state", "join_type", "type") or "").lower()
+ if state and any(w in state for w in ("domain", "azuread", "entra", "hybrid")) and "workplace" not in state:
+ joined = True
+ if joined and "workgroup" not in state:
+ score += 3
+ why.append("domain/Entra joined")
+ elif '"workplace' in t:
+ why.append("workplace-registered only (not scored)")
+ mdm = f.get("work.mdm")
+ if mdm is not None:
+ n = _cnt(mdm, "real_mdm", "real_enrollments", "mdm_enrollments", "enrolled_count", "enrollments", "count")
+ if (n or 0) > 0 or _truth(mdm, "mdm_enrolled", "enrolled", "managed"):
+ score += 3
+ why.append("MDM enrolled")
+ ag = f.get("work.security_agents")
+ if ag is not None:
+ names = [n for n in _names(ag, "agents", "found", "products", "names", "items") if "warp" not in n
+ and "tailscale" not in n]
+ n = len(names) if names else (_cnt(ag, "count", "n") or 0)
+ if n > 0:
+ score += 2
+ why.append(f"{int(n)} EDR/ZTNA agent(s)")
+ od = f.get("onedrive.accounts")
+ if od is not None:
+ b = _cnt(od, "business", "business_accounts", "n_business", "tenants")
+ if (b or 0) > 0 or '"business1"' in _txt(od):
+ score += 2
+ why.append("OneDrive work tenant")
+ tm = f.get("comms.teams_launched")
+ if tm is not None and _truth(tm, "work_profile", "work", "work_launched", "tenant"):
+ score += 2
+ why.append("Teams work profile")
+ managed = score >= 3
+ ed = str(_get(f.get("work.edition_org") or {}, "edition", "EditionID") or "")
+ claim = ("Employer-managed machine" if managed else "Personal machine (no join, MDM, work tenant or EDR)")
+ if not managed and "enterprise" in ed.lower():
+ claim += "; Enterprise edition is not treated as management"
+ return _res(claim, "strong", {"managed": managed, "score": score, "reasons": why})
+
+
+# ---------------------------------------------------------------- 2 sophistication
+
+@insight(id="persona.sophistication",
+ inputs=["dev.devmode_sudo_longpaths", "shell.explorer_prefs", "security.openssh_server", "security.rdp",
+ "net.tailscale", "dev.pwsh7", "apps.pkg_managers", "apps.winget_db", "dev.uv_tools",
+ "kbd.scancode_map", "security.telemetry"])
+def sophistication(f):
+ """Additive rubric from report 11 derive(): novice / power-user / expert."""
+ score, why = 0, []
+
+ def add(n, r):
+ nonlocal score
+ score += n
+ why.append(f"+{n} {r}")
+
+ ds = f.get("dev.devmode_sudo_longpaths")
+ if ds is not None:
+ if _truth(ds, "devmode", "developer_mode", "AllowDevelopmentWithoutDevLicense", "dev_mode"):
+ add(2, "Developer Mode on")
+ if _truth(ds, "sudo", "sudo_enabled", "sudo_Enabled"):
+ add(2, "sudo enabled")
+ if _truth(ds, "long_paths", "longpaths", "LongPathsEnabled", "long_paths_enabled"):
+ add(1, "LongPathsEnabled")
+ ex = f.get("shell.explorer_prefs")
+ if ex is not None:
+ hide = _get(ex, "HideFileExt", "hide_file_ext", "hide_extensions")
+ if hide in (0, "0", False) or _truth(ex, "show_extensions", "file_extensions_shown"):
+ add(1, "file extensions shown")
+ ssh = f.get("security.openssh_server")
+ if ssh is not None and (_truth(ssh, "installed", "service", "sshd", "present", "start") or ssh is True):
+ add(2, "OpenSSH server installed")
+ rdp = f.get("security.rdp")
+ if rdp is not None:
+ deny = _get(rdp, "fDenyTSConnections", "deny")
+ if deny in (0, "0") or _truth(rdp, "rdp_on", "enabled", "rdp_enabled", "accepting"):
+ add(1, "RDP enabled")
+ if f.get("net.tailscale") is not None:
+ add(2, "Tailscale")
+ if f.get("dev.pwsh7") is not None:
+ add(1, "PowerShell 7")
+ pm = f.get("apps.pkg_managers")
+ if pm is not None:
+ names = [k for k in ("scoop", "choco", "pipx", "pnpm", "bun") if pm.get(k) is True] if isinstance(pm, dict) else []
+ names += [n for n in _names(pm, "managers", "found", "names") if "winget" not in n]
+ if names:
+ add(1, "non-inbox package manager (" + ", ".join(names[:3]) + ")")
+ wg = f.get("apps.winget_db")
+ if wg is not None and (_cnt(wg, "user_installs", "installs", "packages", "count", "n") or 0) >= 5:
+ add(1, "winget used for installs")
+ if f.get("dev.uv_tools") is not None:
+ add(1, "uv tools")
+ sc = f.get("kbd.scancode_map")
+ if sc is not None and (_truth(sc, "present", "remapped", "mappings", "entries") or sc is True):
+ add(1, "keyboard scancode remap")
+ tel = f.get("security.telemetry")
+ if tel is not None:
+ lvl = _num(_get(tel, "allow_telemetry", "AllowTelemetry", "level"))
+ reduced = _truth(tel, "reduced", "non_default", "tailored_off", "user_changed")
+ if reduced or (lvl is not None and lvl <= 1):
+ add(1, "telemetry reduced by hand")
+ if not why and not any(k in f for k in ("dev.devmode_sudo_longpaths", "shell.explorer_prefs")):
+ return None
+ tier = "expert" if score >= 10 else "power-user" if score >= 5 else "novice"
+ return _res(f"Technical sophistication: {tier} (score {score})", "strong" if len(why) >= 3 else "weak",
+ {"tier": tier, "score": score, "reasons": why})
+
+
+# ---------------------------------------------------------------- 3 developer
+
+def _dev_app_count(f):
+ tx = f.get("apps.taxonomy_user_added")
+ if tx is None:
+ return None
+ c = _get(tx, "counts", "by_category", "categories") or tx
+ if isinstance(c, dict):
+ for k in ("dev", "developer", "development", "dev_tools"):
+ if k in c:
+ return _num(c[k])
+ return None
+
+
+def _own_commit_repos(f):
+ mc = f.get("dev.repos.my_commits")
+ if mc is None:
+ return None
+ return _cnt(mc, "repos_with_own_commits", "user_repos_with_commits", "repos", "n_repos", "count", default=0)
+
+
+@insight(id="persona.developer",
+ inputs=["apps.taxonomy_user_added", "dev.git", "dev.toolchain_presence", "editor.vscode",
+ "l3.browser_category_share", "browser.history.localhost", "dev.repos", "dev.repos.my_commits"])
+def developer(f):
+ """Developer if >= 3 of six conditions hold."""
+ hits = {}
+ if f.get("dev.git") is not None:
+ hits["git"] = True
+ tc = f.get("dev.toolchain_presence")
+ if tc is not None:
+ names = _names(tc, "on_path", "toolchains", "found", "names")
+ n = len(names) if names else _cnt(tc, "count", "n", default=1)
+ if n:
+ hits["toolchain"] = names[:6] or int(n)
+ dn = _dev_app_count(f)
+ if dn is not None and dn >= 5:
+ hits["dev_apps"] = dn
+ sh = _share(f.get("l3.browser_category_share"), "dev", "ai", "developer", "coding")
+ if sh is not None and sh >= 0.20:
+ hits["dev_ai_share"] = round(sh, 3)
+ lh = f.get("browser.history.localhost")
+ if lh is not None and (_cnt(lh, "visits", "count", "n", "localhost_visits", default=1) or 0) > 0:
+ hits["localhost"] = True
+ oc = _own_commit_repos(f)
+ if oc:
+ hits["own_repo"] = oc
+ if not hits:
+ return None
+ dev = len(hits) >= 3
+ return _res(("Developer" if dev else "Not a developer by the >= 3 rule") + f" ({len(hits)}/6: {', '.join(hits)})",
+ "strong" if dev or len(hits) == 0 else "weak", {"developer": dev, "hits": hits})
+
+
+# ---------------------------------------------------------------- 4 primary_dev_machine
+
+@insight(id="persona.primary_dev_machine",
+ inputs=["editor.vscode", "dev.git_global_config", "dev.repos", "dev.repos.my_commits", "dev.shell_history",
+ "dev.ssh_config"])
+def primary_dev_machine(f):
+ """Primary only if editor customised AND git identity set AND own-commit repo in the user area."""
+ ed = f.get("editor.vscode")
+ gc = f.get("dev.git_global_config")
+ if ed is None and gc is None and "dev.repos.my_commits" not in f:
+ return None
+ customised = False
+ if ed is not None:
+ ext = _cnt(ed, "extensions", "n_extensions", "extension_count", default=0) or 0
+ st = _cnt(ed, "settings_keys", "n_settings", "settings", "user_settings", default=0) or 0
+ customised = ext > 0 or st > 0 or _truth(ed, "customised", "customized")
+ ident = gc is not None and _truth(gc, "identity_set", "user_name_set", "has_identity", "user.name", "user_name",
+ "name_set", "email_set")
+ own = bool(_own_commit_repos(f))
+ primary = customised and ident and own
+ hist = _cnt(f.get("dev.shell_history"), "lines", "line_count", "count")
+ claim = ("Primary dev machine" if primary else
+ "Tool box / test target, not the primary dev machine; ask where the user codes")
+ # The deciding input only exists when the repo walk ran. Without it, "not primary" is
+ # an absence of evidence, not evidence of absence: say so weakly and let the agent ask.
+ decided = "dev.repos.my_commits" in f or own
+ strength = "strong" if decided and (primary or (customised and ident)) else "weak"
+ if not decided and not primary:
+ claim += " (own-commit scan not collected)"
+ return _res(claim, strength, {"primary": primary, "editor_customised": customised, "git_identity": ident,
+ "own_commit_repo": own, "shell_history_lines": hist})
+
+
+# ---------------------------------------------------------------- 5 ai_power_user / 6 primary_agent
+
+_AGENTS = {"claude_code": "claude_code.sessions", "codex": "codex.usage", "hermes": "hermes.usage"}
+
+
+def _agent_sessions(f, recent=False):
+ out = {}
+ for name, pid in _AGENTS.items():
+ v = f.get(pid)
+ if v is None:
+ continue
+ n = _sessions_30d(v) if recent else None
+ if n is None:
+ n = _sessions(v)
+ if n is not None:
+ out[name] = n
+ return out
+
+
+@insight(id="persona.ai_power_user",
+ inputs=["claude_code.sessions", "codex.usage", "hermes.usage", "codex.chatgpt_catalog", "ollama.models",
+ "ollama.logs", "browser.automation", "cua_driver.present", "l3.mcp_inventory"])
+def ai_power_user(f):
+ """Usage-weighted. Installed-but-unused tools score 0."""
+ s = _agent_sessions(f)
+ chat = _cnt(f.get("codex.chatgpt_catalog"), "conversations", "count", "n", "total")
+ models = _cnt(f.get("ollama.models"), "models", "count", "n")
+ if not s and chat is None and models is None:
+ return None
+ used = {k: v for k, v in s.items() if v and v >= 3}
+ power = any(v >= 20 for v in s.values()) or len(used) >= 2 or (chat or 0) > 50
+ level = "power_user" if power else "user" if any(v for v in s.values()) or (models or 0) > 0 else "tools_only"
+ extras = [k for k in ("browser.automation", "cua_driver.present", "l3.mcp_inventory") if k in f]
+ return _res(f"AI usage: {level} (sessions {s or 'none'}; ChatGPT conversations {chat})",
+ "strong" if s else "weak",
+ {"level": level, "sessions": s, "chatgpt_conversations": chat, "ollama_models": models,
+ "automation_tools": extras})
+
+
+@insight(id="persona.primary_agent", inputs=["hermes.usage", "codex.usage", "claude_code.sessions"])
+def primary_agent(f):
+ """Agent with the most sessions in the last 30 days."""
+ s = _agent_sessions(f, recent=True)
+ s = {k: v for k, v in s.items() if v}
+ if not s:
+ return None
+ top = max(s, key=s.get)
+ return _res(f"Primary agent on this host: {top} ({int(s[top])} sessions)", "strong" if s[top] >= 3 else "weak",
+ {"agent": top, "sessions": s})
+
+
+# ---------------------------------------------------------------- 7 hermes_developer
+
+@insight(id="persona.hermes_developer",
+ inputs=["dev.repos.my_commits", "dev.repos", "apps.appx_registry", "filter.operator_noise"])
+def hermes_developer(f):
+ """Only user-authored commits in a non-operator hermes-agent clone. Side homes, lab tasks and commit-named
+ bundle builds (HermesBundledCommit*) are operator test artifacts and never fire it."""
+ mc = f.get("dev.repos.my_commits")
+ repos = f.get("dev.repos")
+ if mc is None and repos is None:
+ return None
+ t = _txt(mc)
+ clone = [r for r in (_get(repos or {}, "repos") or []) if isinstance(r, dict)
+ and "hermes-agent" in str(r.get("name", "")).lower() and r.get("class") not in ("operator", "tool_managed")]
+ own = _own_commit_repos(f) or 0
+ if "hermes-agent" in t or (clone and own):
+ return _res("Contributes to hermes-agent (own commits in a user-area clone)", "strong",
+ {"hermes_developer": True, "clones": len(clone), "repos_with_own_commits": own})
+ if clone:
+ return _res("hermes-agent clone present without own commits (reader, not contributor)", "weak",
+ {"hermes_developer": False, "clones": len(clone)})
+ return None
+
+
+# ---------------------------------------------------------------- 8 gamer_tier / 9 genres
+
+def _steam_hours(f):
+ pt = f.get("steam.playtime")
+ if pt is None:
+ return None, None
+ hours = _cnt(pt, "total_hours", "hours_total", "account_hours", "hours", "all_hours")
+ if hours is None:
+ mins = _cnt(pt, "total_minutes", "minutes")
+ hours = mins / 60.0 if mins else None
+ recent = _cnt(pt, "played_last_30d", "games_30d", "recent_games", "last_30d")
+ return hours, recent
+
+
+def _local_hours(f):
+ ls = f.get("steam.local_sessions")
+ if ls is None:
+ return None, None
+ return (_cnt(ls, "hours", "total_hours", "local_hours", "hours_total"),
+ _cnt(ls, "hours_30d", "last_30d_hours", "hours_last_30d"))
+
+
+def _launchers(f):
+ out = []
+ if "steam.present" in f or "steam.installed" in f or "steam.playtime" in f:
+ out.append("steam")
+ if "epic.present" in f or "epic.installs" in f:
+ out.append("epic")
+ lo = f.get("launchers.other")
+ if lo is not None:
+ out += [n for n in _names(lo, "launchers", "found", "names", "items") if n not in out]
+ return out
+
+
+@insight(id="persona.gamer_tier",
+ inputs=["steam.playtime", "steam.local_sessions", "steam.installed", "epic.installs", "launchers.other",
+ "gaming.anticheat", "gcs.game_history", "nvidia.recommendations", "tuning.afterburner",
+ "hw.bluetooth", "consent.microphone", "srum.app_timeline"])
+def gamer_tier(f):
+ """Report 07 score: account hours, 30-day recency, installed GB, launchers, Afterburner."""
+ if not any(k in f for k in ("steam.playtime", "steam.installed", "epic.installs", "launchers.other",
+ "gcs.game_history", "steam.present")):
+ return None
+ hours, recent = _steam_hours(f)
+ gcs = f.get("gcs.game_history")
+ gcs30 = _cnt(gcs, "played_30d", "last_30d", "recent_30d", default=0) or 0
+ inst_gb = 0.0
+ for pid in ("steam.installed", "epic.installs"):
+ g = _cnt(f.get(pid), "size_gb", "total_gb", "gb", "installed_gb")
+ if g:
+ inst_gb += g
+ for row in (_get(f.get("epic.installs") or {}, "manifests") or []):
+ if isinstance(row, (list, tuple)) and len(row) > 1 and isinstance(row[1], (int, float)):
+ inst_gb += row[1]
+ launchers = _launchers(f)
+ score = 0
+ score += 2 if (hours or 0) >= 500 else 1 if (hours or 0) >= 50 else 0
+ r = max(gcs30, recent or 0)
+ score += 2 if r >= 3 else 1 if r else 0
+ score += 1 if inst_gb >= 100 else 0
+ score += 1 if len(launchers) >= 3 else 0
+ score += 1 if "tuning.afterburner" in f else 0
+ tier = "core" if score >= 5 else "regular" if score >= 3 else "casual" if score >= 1 else "none"
+ lh, lh30 = _local_hours(f)
+ return _res(f"Gamer tier: {tier} (score {score})", "strong",
+ {"tier": tier, "score": score, "account_hours": hours, "local_hours": lh, "local_hours_30d": lh30,
+ "installed_gb": round(inst_gb, 1), "launchers": launchers,
+ "anticheat": "gaming.anticheat" in f})
+
+
+@insight(id="persona.genres", inputs=["steam.playtime", "steam.appinfo_genres"])
+def genres(f):
+ """Genre hours from Steam genre ids."""
+ g = f.get("steam.appinfo_genres")
+ if g is None:
+ return None
+ gh = _get(g, "genre_hours", "hours_by_genre", "genres") if isinstance(g, dict) else None
+ per_acc = _get(g, "per_account") if isinstance(g, dict) else None
+ if not isinstance(gh, dict) and isinstance(per_acc, list):
+ gh = {}
+ for acc in per_acc:
+ for row in (acc.get("genre_h") or []) if isinstance(acc, dict) else []:
+ if isinstance(row, (list, tuple)) and len(row) == 2:
+ gh[row[0]] = gh.get(row[0], 0) + (_num(row[1]) or 0)
+ if not isinstance(gh, dict):
+ pt = f.get("steam.playtime") or {}
+ per_app = _get(pt, "per_app", "apps", "games") if isinstance(pt, dict) else None
+ app_genres = _get(g, "app_genres", "by_app", "apps") if isinstance(g, dict) else None
+ if not isinstance(per_app, (dict, list)) or not isinstance(app_genres, dict):
+ return None
+ gh = {}
+ rows = per_app.items() if isinstance(per_app, dict) else [(str(x.get("appid")), x) for x in per_app
+ if isinstance(x, dict)]
+ for appid, row in rows:
+ h = _num(row.get("hours") if isinstance(row, dict) else row) or 0
+ for gn in app_genres.get(str(appid), []) or []:
+ gh[gn] = gh.get(gn, 0) + h
+ gh = {k: round(_num(v) or 0, 1) for k, v in gh.items() if k.lower() not in ("free to play", "early access")}
+ if not gh:
+ return None
+ top = sorted(gh.items(), key=lambda kv: -kv[1])[:4]
+ return _res("Top genres by hours: " + ", ".join(f"{k} {v}" for k, v in top), "strong", {"genre_hours": dict(top)})
+
+
+# ---------------------------------------------------------------- 10 machine_role
+
+@insight(id="persona.machine_role",
+ inputs=["steam.local_sessions", "steam.playtime", "l3.browser_category_share", "files.composition",
+ "userassist.focus", "l3.top_apps_by_time"])
+def machine_role(f):
+ """Gaming rig / work laptop / media / mixed from the largest share."""
+ scores = {"gaming": 0.0, "work": 0.0, "media": 0.0}
+ lh, lh30 = _local_hours(f)
+ if lh is not None:
+ scores["gaming"] += min(1.0, (lh or 0) / 100.0)
+ sh = f.get("l3.browser_category_share")
+ if sh is not None:
+ scores["work"] += _share(sh, "dev", "ai", "work", "docs", "productivity") or 0
+ scores["media"] += _share(sh, "video", "streaming", "music", "media") or 0
+ scores["gaming"] += _share(sh, "gaming", "games") or 0
+ comp = f.get("files.composition")
+ if comp is not None:
+ vid = _share(_get(comp, "byte_share", "share_by_kind", "shares") or {}, "video", "videos")
+ if vid:
+ scores["media"] += vid * 0.5
+ ua = f.get("l3.top_apps_by_time") or f.get("userassist.focus")
+ if ua is not None:
+ t = _txt(ua)
+ for k in ("steam", "game", "epic"):
+ if k in t:
+ scores["gaming"] += 0.2
+ break
+ for k in ("code", "terminal", "pwsh", "powershell", "codex", "hermes"):
+ if k in t:
+ scores["work"] += 0.2
+ break
+ for k in ("vlc", "media player", "spotify", "netflix"):
+ if k in t:
+ scores["media"] += 0.2
+ break
+ if not any(scores.values()):
+ return None
+ ordered = sorted(scores.items(), key=lambda kv: -kv[1])
+ role = ordered[0][0] if ordered[0][1] >= 1.5 * max(ordered[1][1], 0.01) else f"mixed ({ordered[0][0]}+{ordered[1][0]})"
+ return _res(f"Machine role: {role}", "strong" if lh is not None and sh is not None else "weak",
+ {"role": role, "scores": {k: round(v, 2) for k, v in scores.items()}, "local_steam_hours": lh})
+
+
+# ---------------------------------------------------------------- 11 tinkerer_tuner
+
+@insight(id="persona.tinkerer_tuner",
+ inputs=["tuning.afterburner", "tuning.rtss", "tasks.nonms", "periph.rgb_suites", "hw.power_plan",
+ "hw.gpu_history", "hw.monitor_history"])
+def tinkerer_tuner(f):
+ """>= 2 of: custom fan/VF curve, power-limit task, RGB suite, Ultimate Performance plan, hardware swap."""
+ hits = []
+ ab = f.get("tuning.afterburner")
+ if ab is not None and (_truth(ab, "custom_curve", "fan_curve", "vf_curve", "profiles", "custom_fan") or
+ "curve" in _txt(ab)):
+ hits.append("Afterburner custom curve")
+ elif ab is not None:
+ hits.append("Afterburner installed")
+ tk = f.get("tasks.nonms")
+ if tk is not None and ("nvidia-smi" in _txt(tk) or "power_limit" in _txt(tk)):
+ hits.append("GPU power-limit task")
+ if f.get("periph.rgb_suites") is not None:
+ hits.append("RGB suite")
+ pp = f.get("hw.power_plan")
+ if pp is not None and ("ultimate" in _txt(pp) or "e9a42b02" in _txt(pp)):
+ hits.append("Ultimate Performance plan")
+ g, m, _img = _hw_changes(f)
+ if g:
+ hits.append(f"GPU swap ({g})")
+ if m:
+ hits.append(f"monitor change ({m})")
+ if not hits:
+ return None
+ yes = len(hits) >= 2
+ return _res(("Hardware tinkerer/tuner: " if yes else "Some tuning: ") + ", ".join(hits),
+ "strong" if yes else "weak", {"tinkerer": yes, "hits": hits})
+
+
+# ---------------------------------------------------------------- 12 creator / 13 streamer_recorder
+
+CREATIVE = ("blender", "gimp", "obs", "davinci", "resolve", "premiere", "photoshop", "krita", "inkscape",
+ "sketchup", "audacity", "reaper", "clipchamp", "affinity", "creative cloud", "lightroom", "kdenlive",
+ "shotcut", "fl studio", "ableton", "maya", "freecad", "unreal", "unity")
+
+
+@insight(id="persona.creator",
+ inputs=["apps.taxonomy_user_added", "media.obs", "userassist.focus", "consent.microphone", "consent.webcam",
+ "files.composition"])
+def creator(f):
+ """Creative apps installed AND launched by the user; agent-container config does not count."""
+ tx = f.get("apps.taxonomy_user_added")
+ installed = []
+ if tx is not None:
+ c = _get(tx, "counts", "by_category", "categories") or {}
+ n = _num(c.get("creative")) if isinstance(c, dict) else None
+ installed = [x for x in CREATIVE if x in _txt(tx)]
+ if n and not installed:
+ installed = [f"{int(n)} creative apps"]
+ obs = f.get("media.obs")
+ if obs is not None:
+ installed.append("obs")
+ if not installed:
+ return None
+ launched = []
+ ua = _txt(f.get("userassist.focus"))
+ launched += [x for x in CREATIVE if x in ua]
+ if obs is not None:
+ t = _txt(obs)
+ if "openai.codex" not in t and (_truth(obs, "appdata_config", "config_dir", "profiles", "scenes") or
+ (_cnt(obs, "recordings", "scene_collections", default=0) or 0) > 0):
+ launched.append("obs(config)")
+ mic = _txt(f.get("consent.microphone")) + _txt(f.get("consent.webcam"))
+ launched += [x for x in ("obs64", "blender", "resolve") if x in mic]
+ yes = bool(launched)
+ return _res(("Creator: creative apps launched by the user (" + ", ".join(sorted(set(launched))) + ")") if yes
+ else "Creative apps installed but no user-launch evidence (may be agent-installed)", "weak",
+ {"creator": yes, "installed": sorted(set(installed))[:10], "launched": sorted(set(launched))})
+
+
+@insight(id="persona.streamer_recorder",
+ inputs=["media.obs", "nvidia.broadcast", "nvidia.shadowplay", "captures.gamebar", "captures.nvidia",
+ "consent.screen_capture"])
+def streamer_recorder(f):
+ """Recording if captures exist or OBS used mic/camera."""
+ caps = {}
+ for pid in ("captures.gamebar", "captures.nvidia"):
+ n = _cnt(f.get(pid), "count", "files", "n", "captures", "videos")
+ if n:
+ caps[pid.split(".")[1]] = n
+ tools = [k for k in ("media.obs", "nvidia.broadcast", "nvidia.shadowplay") if k in f]
+ if not caps and not tools:
+ return None
+ yes = bool(caps)
+ return _res(("Records gameplay/screen (captures: " + ", ".join(f"{k} {int(v)}" for k, v in caps.items()) + ")")
+ if yes else "Capture tools present, no captures found", "weak",
+ {"records": yes, "captures": caps, "tools": tools})
+
+
+# ---------------------------------------------------------------- 14 voice_chat_gamer
+
+@insight(id="persona.voice_chat_gamer", inputs=["consent.microphone", "discord.usage"])
+def voice_chat_gamer(f):
+ """Mic use by game exes or Discord voice days >= 3."""
+ mic = f.get("consent.microphone")
+ dc = f.get("discord.usage")
+ if mic is None and dc is None:
+ return None
+ game_mic = [n for n in _names(mic, "recent", "items", "exes", "top") if any(g in n for g in GAME_EXE_HINTS)
+ and "steamwebhelper" not in n] if mic is not None else []
+ rtc = _cnt(dc, "rtc_days", "voice_days", "rtc_days_90d", "voice_days_90d") if dc is not None else None
+ discord_mic = "discord" in _txt(mic)
+ yes = bool(game_mic) or (rtc or 0) >= 3
+ if not yes and not discord_mic:
+ return None
+ return _res("Uses voice chat while gaming" if yes else "Discord has mic access; voice use not established",
+ "weak", {"voice_chat": yes, "game_mic_apps": len(game_mic), "discord_rtc_days": rtc})
+
+
+# ---------------------------------------------------------------- 15 hands_on_vs_remote
+
+@insight(id="persona.hands_on_vs_remote",
+ inputs=["srum.app_timeline", "security.openssh_server", "net.tailscale", "acct.hello", "bam.last_run"])
+def hands_on_vs_remote(f):
+ """Deep: input/focus ratio. Default: sshd + Tailscale = remotely administered; Hello use = person present."""
+ st = f.get("srum.app_timeline")
+ if st is not None:
+ r = _num(_get(st, "input_focus_ratio", "input_over_focus", "ratio"))
+ if r is not None:
+ mode = "remote-driven" if r < 0.05 else "hands-on" if r > 0.3 else "mixed"
+ return _res(f"Use is {mode} (input/focus {r:.2f}, 7-day window)", "strong", {"mode": mode, "ratio": r})
+ ssh = "security.openssh_server" in f
+ ts = "net.tailscale" in f
+ hello = f.get("acct.hello")
+ face = isinstance(hello, dict) and (hello.get("face") is True or
+ str(hello.get("last_provider") or "").lower() == "face")
+ if not (ssh or ts or face):
+ return None
+ remote = ssh and ts
+ mode = ("remotely administered, person present at times" if remote and face else
+ "remotely administered" if remote else "hands-on (no remote-admin path)")
+ return _res(f"Access pattern: {mode}", "weak", {"sshd": ssh, "tailscale": ts, "hello_face": face})
+
+
+# ---------------------------------------------------------------- 16 activity_hours
+
+def _hour_hist(v):
+ if v is None:
+ return None
+ h = _get(v, "hours", "hour", "by_hour", "hour_hist", "hours_local", "start_hours") if isinstance(v, dict) else v
+ if isinstance(h, dict):
+ try:
+ arr = [0] * 24
+ for k, n in h.items():
+ arr[int(k) % 24] += _num(n) or 0
+ h = arr
+ except (ValueError, TypeError):
+ return None
+ if isinstance(h, list) and len(h) == 24 and all(isinstance(x, (int, float)) for x in h):
+ return h
+ return None
+
+
+@insight(id="persona.activity_hours",
+ inputs=["browser.history.hour_weekday", "steam.local_sessions", "dev.repos.commit_hours", "files.screenshots",
+ "wu.active_hours", "srum.app_resource"])
+def activity_hours(f):
+ """Peak hours per host; 'night' only if >= 40% of events fall 00-05 in >= 2 sources."""
+ srcs = {}
+ for pid in ("browser.history.hour_weekday", "steam.local_sessions", "dev.repos.commit_hours", "files.screenshots",
+ "srum.app_resource"):
+ h = _hour_hist(f.get(pid))
+ if h and sum(h) > 0:
+ srcs[pid] = h
+ if not srcs:
+ return None
+ total = [sum(h[i] for h in srcs.values()) for i in range(24)]
+ s = sum(total)
+ peak = sorted(range(24), key=lambda i: -total[i])[:3]
+ night_srcs = [p for p, h in srcs.items() if sum(h[0:6]) / sum(h) >= 0.40]
+ night = len(night_srcs) >= 2
+ shares = {p: round(sum(h[0:6]) / sum(h), 2) for p, h in srcs.items()}
+ label = "night" if night else ("afternoon-evening" if sum(total[12:24]) / s >= 0.6 else "daytime" if
+ sum(total[8:18]) / s >= 0.6 else "spread")
+ return _res(f"Active hours: {label}; peak hours {sorted(peak)}", "strong" if len(srcs) >= 2 else "weak",
+ {"label": label, "peak_hours": sorted(peak), "night_share_by_source": shares, "sources": list(srcs)})
+
+
+# ---------------------------------------------------------------- 17 power_habit
+
+def _power_split(f):
+ ps = f.get("l3.power_event_split")
+ if isinstance(ps, dict):
+ return {k: _cnt(ps, k, default=0) for k in ("crash", "button_held", "power_removed")}
+ ph = f.get("eventlog.power_history")
+ if not isinstance(ph, dict):
+ return None
+ got = {k: _cnt(ph, k, f"kp41_{k}", default=None) for k in ("crash", "button_held", "power_removed")}
+ if any(v is not None for v in got.values()):
+ return {k: v or 0 for k, v in got.items()}
+ return None
+
+
+@insight(id="persona.power_habit", inputs=["boot.uptime", "eventlog.power_history", "l3.power_event_split"])
+def power_habit(f):
+ """Power-cycles daily vs sleeps; KP41 power_removed counts toward the power-off habit, not health."""
+ up = f.get("boot.uptime")
+ ph = f.get("eventlog.power_history")
+ if up is None and ph is None:
+ return None
+ uptime_h = _cnt(up, "uptime_h", "uptime_hours", "hours")
+ if uptime_h is None:
+ d = _cnt(up, "uptime_days", "days")
+ uptime_h = d * 24 if d is not None else None
+ boots = _cnt(ph, "boots_30d", "boots", "n_boots", "startups")
+ resumes = _cnt(ph, "resumes_30d", "resumes", "sleep_resumes", "wakes")
+ split = _power_split(f) or {}
+ removed = split.get("power_removed", 0) or 0
+ habit = "unknown"
+ if boots is not None and boots >= 20 and (resumes or 0) <= 3:
+ habit = "power_cycles_daily"
+ elif uptime_h is not None and uptime_h > 72 and (resumes or 0) > 2 * (boots or 0):
+ habit = "sleeps"
+ elif uptime_h is not None and uptime_h > 72:
+ habit = "stays_on"
+ elif boots is not None:
+ habit = "mixed"
+ claim = f"Power habit: {habit}" + (" (no boot history)" if habit == "unknown" else "")
+ if removed:
+ claim += f"; {int(removed)} hard power-offs (switch or outage)"
+ if habit == "power_cycles_daily":
+ claim += "; scheduled jobs need missed-run catch-up"
+ return _res(claim, "strong" if boots is not None else "weak",
+ {"habit": habit, "uptime_h": uptime_h, "boots": boots, "resumes": resumes, "power_removed": removed})
+
+
+# ---------------------------------------------------------------- 18 mobility
+
+@insight(id="persona.mobility", inputs=["hw.battery", "net.history", "net.wifi_profiles", "hw.sleep_study"])
+def mobility(f):
+ """Laptop that moves if battery AND >= 3 wireless networks."""
+ bat = f.get("hw.battery")
+ if bat is None:
+ if "net.history" in f or "net.wifi_profiles" in f:
+ return _res("Desktop (no battery): no mobility defaults", "weak", {"battery": False, "moves": False})
+ return None
+ wl = _cnt(f.get("net.history"), "wireless", "n_wireless", "wifi", "wireless_count")
+ if wl is None:
+ wl = _cnt(f.get("net.wifi_profiles"), "count", "profiles", "n")
+ moves = (wl or 0) >= 3
+ return _res(("Laptop that moves between networks" if moves else "Laptop, mostly stationary") +
+ f" ({wl} wireless networks); use battery-aware defaults", "weak",
+ {"battery": True, "wireless_networks": wl, "moves": moves})
+
+
+# ---------------------------------------------------------------- 19 local_llm_capability
+
+@insight(id="persona.local_llm_capability", inputs=["hw.gpu", "hw.ram", "host.native_arch", "hw.nvidia_smi"])
+def local_llm_capability(f):
+ """VRAM >= 24 GB: large local models; 8-16 GB: small/quantised; ARM64 warns about x64-only CUDA tooling."""
+ g = f.get("hw.gpu")
+ ns = f.get("hw.nvidia_smi")
+ if g is None and ns is None:
+ return None
+ vram = _cnt(ns, "vram_gb", "memory_total_gb", "vram") if ns is not None else None
+ if vram is None and ns is not None:
+ mib = _cnt(ns, "memory_total_mib", "memory_total_mb", "memory.total")
+ vram = mib / 1024.0 if mib else None
+ if vram is None and g is not None:
+ vram = _cnt(g, "vram_gb", "max_vram_gb", "dedicated_gb", "vram")
+ if vram is None:
+ b = _cnt(g, "vram_bytes", "qwMemorySize", "adapter_ram")
+ vram = b / 2 ** 30 if b else None
+ if vram is not None and vram > 4096:
+ vram = vram / 1024.0
+ ram = _cnt(f.get("hw.ram"), "total_gb", "gb", "ram_gb", "installed_gb")
+ if ram is not None and ram > 4096:
+ ram = ram / 2 ** 30
+ arch = str(_get(f.get("host.native_arch") or {}, "arch", "native", "machine", "value") or f.get("host.native_arch")
+ or "").lower()
+ arm = "arm" in arch
+ if vram is None:
+ cap = "unknown_vram"
+ elif vram >= 24:
+ cap = "large_models"
+ elif vram >= 7.5:
+ cap = "small_quantised"
+ else:
+ cap = "cpu_or_tiny"
+ claim = f"Local LLM capability: {cap} (VRAM {round(vram, 1) if vram else '?'} GB, RAM {round(ram) if ram else '?'} GB)"
+ if arm:
+ claim += "; ARM64 host: x64-only CUDA tooling may not run"
+ return _res(claim, "strong" if vram is not None else "weak",
+ {"capability": cap, "vram_gb": vram, "ram_gb": ram, "arm64": arm})
+
+
+# ---------------------------------------------------------------- 20 health_flags
+
+@insight(id="persona.health_flags",
+ inputs=["hw.disks", "hw.ram", "l3.power_event_split", "health.whea_gpu", "health.wer", "health.dumps",
+ "eventlog.power_history"])
+def health_flags(f):
+ """Disk free < 15%, RAM below rated speed or single channel, bugchecks/WHEA in 30 d, repeated app crashes."""
+ flags = []
+ d = f.get("hw.disks")
+ if d is not None:
+ vols = _get(d, "volumes", "disks", "drives") if isinstance(d, dict) else d
+ vols = vols if isinstance(vols, list) else [d]
+ for v in vols:
+ if not isinstance(v, dict):
+ continue
+ pct = _num(v.get("free_pct") or v.get("pct_free"))
+ if pct is None and v.get("free_gb") is not None and v.get("size_gb"):
+ pct = 100.0 * _num(v["free_gb"]) / _num(v["size_gb"])
+ if pct is not None and pct < 15:
+ flags.append(f"disk {v.get('letter') or v.get('name') or '?'} {pct:.0f}% free")
+ r = f.get("hw.ram")
+ if r is not None:
+ sp = _num(_get(r, "configured_mhz", "speed_mhz", "configured_speed"))
+ rated = _num(_get(r, "rated_mhz", "max_mhz", "speed_rated"))
+ for part in (_get(r, "part") or []) if isinstance(_get(r, "part"), list) else []:
+ m = re.search(r"-(\d{4})$", str(part))
+ if m and int(m.group(1)) > (rated or 0):
+ rated = int(m.group(1))
+ if sp and rated and sp < rated * 0.9:
+ flags.append(f"RAM at {int(sp)} of rated {int(rated)} MT/s")
+ mods, slots = _num(_get(r, "modules", "dimms")), _num(_get(r, "slots"))
+ lpddr = any(t in (30, 35) for t in (_get(r, "smbios_type") or []) if isinstance(t, int))
+ if mods == 1 and (slots or 0) >= 2 and not lpddr:
+ flags.append(f"single-channel RAM (1 of {int(slots)} slots)")
+ split = _power_split(f) or {}
+ ps = f.get("l3.power_event_split")
+ crash30 = None
+ if isinstance(ps, dict):
+ crash30 = _num(ps.get("crash_30d"))
+ if crash30 is None and "crash_30d" in ps:
+ crash30 = 0
+ if crash30 is None and not isinstance(ps, dict):
+ crash30 = split.get("crash") or 0
+ if crash30:
+ flags.append(f"{int(crash30)} bugcheck crash(es) in 30 d")
+ wh = _cnt(f.get("health.whea_gpu"), "count_30d", "events_30d")
+ if wh:
+ flags.append(f"{int(wh)} WHEA/GPU error event(s) in 30 d")
+ wer = f.get("health.wer")
+ if wer is not None:
+ n = _cnt(wer, "max_repeat", "top_count")
+ top = (_get(wer, "crashes_by_app") or [[None]])[0]
+ if n and n >= 5:
+ flags.append(f"repeated app crashes ({top[0] if isinstance(top, list) else '?'} x{int(n)})")
+ dm = _cnt(f.get("health.dumps"), "count_30d", "minidumps_30d")
+ if dm:
+ flags.append(f"{int(dm)} crash dump(s) in 30 d")
+ if not any(k in f for k in ("hw.disks", "hw.ram", "health.wer", "health.whea_gpu", "eventlog.power_history")):
+ return None
+ return _res(("Health flags: " + "; ".join(flags)) if flags else "No health flags", "strong",
+ {"flags": flags})
+
+
+# ---------------------------------------------------------------- 21-24
+
+@insight(id="persona.locale_format", inputs=["locale.user", "locale.geo", "kbd.layouts", "tz.zone", "lang.ui"])
+def locale_format(f):
+ """Reply language = UI language; date/currency from the user locale."""
+ ui = _get(f.get("lang.ui") or {}, "ui_language", "language", "lang", "value") or f.get("lang.ui")
+ loc = _get(f.get("locale.user") or {}, "locale", "LocaleName", "name", "value") or f.get("locale.user")
+ tz = _get(f.get("tz.zone") or {}, "zone", "TimeZoneKeyName", "name", "value") or f.get("tz.zone")
+ geo = _get(f.get("locale.geo") or {}, "name", "geo", "Name", "value") or f.get("locale.geo")
+ if not any(isinstance(x, str) for x in (ui, loc, tz, geo)):
+ return None
+ s = lambda x: x if isinstance(x, str) else None
+ fmt = _get(f.get("locale.user") or {}, "short_date", "sShortDate", "date_format")
+ return _res(f"Reply language {s(ui)}; formats from {s(loc)}; time zone {s(tz)}", "strong",
+ {"ui_language": s(ui), "locale": s(loc), "geo": s(geo), "tz": s(tz), "short_date": fmt,
+ "keyboards": _names(f.get("kbd.layouts"), "layouts", "names", "items")[:5]})
+
+
+@insight(id="persona.ui_theme", inputs=["theme.dark"])
+def ui_theme(f):
+ """Match dark UI."""
+ t = f.get("theme.dark")
+ if t is None:
+ return None
+ apps = _get(t, "apps_dark", "AppsUseLightTheme", "apps", "dark") if isinstance(t, dict) else t
+ dark = (apps in (0, "0") if isinstance(t, dict) and "AppsUseLightTheme" in t else bool(apps))
+ if isinstance(t, dict) and "AppsUseLightTheme" in t:
+ dark = t["AppsUseLightTheme"] in (0, "0", False)
+ return _res("Dark UI" if dark else "Light UI", "strong", {"dark": dark})
+
+
+@insight(id="persona.browser_target",
+ inputs=["browser.default", "l3.primary_browser", "browser.profile_prefs", "browser.bookmarks",
+ "browser.extensions"])
+def browser_target(f):
+ """Primary browser; skip import when bookmark/extension counts are 0; no sync unless signed in."""
+ pb = f.get("l3.primary_browser")
+ primary = _get(pb or {}, "primary", "browser", "name") if isinstance(pb, dict) else pb
+ default = _get(f.get("browser.default") or {}, "prog_id", "browser", "default", "name", "ProgId") \
+ if isinstance(f.get("browser.default"), dict) else f.get("browser.default")
+ if not primary and not default:
+ return None
+ bm = _cnt(f.get("browser.bookmarks"), "total", "count", "bookmarks", default=0)
+ ext = _cnt(f.get("browser.extensions"), "user_installed", "count", "total", "extensions", default=0)
+ signed = _truth(f.get("browser.profile_prefs") or {}, "signed_in", "signed_in_profiles", "sync")
+ return _res(f"Use {primary or default}; bookmarks {bm}, extensions {ext}; signed-in profile: {signed}", "strong",
+ {"primary": primary, "default": default, "offer_import": bool(bm or ext), "signed_in": signed})
+
+
+PM_WORDS = ("bitwarden", "1password", "lastpass", "keepass", "dashlane", "proton pass", "nordpass", "enpass")
+
+
+@insight(id="persona.password_manager", inputs=["pm.desktop", "browser.extensions", "l3.browser_category_share"])
+def password_manager(f):
+ """Desktop app, extension, or >= 10 visits to a PM web vault."""
+ found = []
+ pm = f.get("pm.desktop")
+ if pm is not None and _names(pm, "managers", "found", "names"):
+ found += [f"{w} (desktop)" for w in PM_WORDS if w in _txt(pm)] or ["desktop app"]
+ ex = _txt(f.get("browser.extensions"))
+ found += [f"{w} (extension)" for w in PM_WORDS if w in ex]
+ sh = f.get("l3.browser_category_share")
+ if sh is not None:
+ vis = _cnt(sh, "password_manager_visits", "pm_vault_visits")
+ if vis is None:
+ s = _get(sh, "counts", "visits") or {}
+ vis = _num(s.get("password_manager")) if isinstance(s, dict) else None
+ if vis and vis >= 10:
+ found.append(f"web vault ({int(vis)} visits)")
+ if not found:
+ return None
+ return _res("Uses a password manager: " + ", ".join(found), "weak", {"password_manager": found})
+
+
+# ---------------------------------------------------------------- 25-28
+
+@insight(id="persona.comms_surface",
+ inputs=["comms.native_apps", "comms.teams_launched", "discord.usage", "browser.history.workspaces"])
+def comms_surface(f):
+ """Native if the app shows recent use; package presence is not use."""
+ out = {}
+ na = f.get("comms.native_apps")
+ if na is not None and isinstance(na, dict):
+ for app, v in na.items():
+ if app in ("present", "count"):
+ continue
+ used = _truth(v, "recent_use", "used", "launched", "last_used") if isinstance(v, dict) else False
+ out[app] = "native" if used else "installed_unused"
+ if "discord.usage" in f:
+ out["discord"] = "native"
+ if f.get("comms.teams_launched") is not None:
+ out["teams"] = "native"
+ ws = f.get("browser.history.workspaces")
+ if isinstance(ws, dict):
+ for k, v in ws.items():
+ if (_num(v) or 0) > 0 and k not in out:
+ out[k] = "web"
+ if not out:
+ return None
+ return _res("Comms: " + ", ".join(f"{k}={v}" for k, v in out.items()), "strong", {"surfaces": out})
+
+
+@insight(id="persona.storage_locality", inputs=["onedrive.accounts", "onedrive.kfm", "sync.other"])
+def storage_locality(f):
+ """Local-only if no signed-in sync client and no known-folder redirection."""
+ if not any(k in f for k in ("onedrive.accounts", "onedrive.kfm", "sync.other")):
+ return _res("Local-only storage (no signed-in sync client, no folder redirection)", "weak",
+ {"local_only": True})
+ od = f.get("onedrive.accounts")
+ signed = od is not None and (_cnt(od, "signed_in", "accounts", "count", "n", default=1) or 0) > 0
+ kfm = f.get("onedrive.kfm")
+ redirected = kfm is not None and _truth(kfm, "redirected", "any", "folders", "kfm")
+ other = _names(f.get("sync.other"), "clients", "found", "names") if "sync.other" in f else []
+ local = not signed and not redirected and not other
+ return _res("Local-only storage" if local else "Cloud-synced storage (" + ", ".join(
+ [x for x, y in (("OneDrive", signed), ("KFM", redirected)) if y] + other) + ")", "strong",
+ {"local_only": local, "onedrive_signed_in": signed, "kfm": redirected, "other": other})
+
+
+@insight(id="persona.notes_location", inputs=["productivity.notes_apps"])
+def notes_location(f):
+ """No notes app: ask where notes live."""
+ n = f.get("productivity.notes_apps")
+ names = _names(n, "apps", "found", "names") if n is not None else []
+ if not names:
+ return _res("No notes app found; ask where notes live", "weak", {"notes_apps": []})
+ return _res("Notes app(s): " + ", ".join(names[:4]), "weak", {"notes_apps": names})
+
+
+@insight(id="persona.media_consumer", inputs=["media.players", "media.libraries", "files.composition"])
+def media_consumer(f):
+ """No music player and empty Music folder: do not lead with music integrations."""
+ pl = f.get("media.players")
+ lib = f.get("media.libraries")
+ if pl is None and lib is None and "files.composition" not in f:
+ return None
+ players = _names(pl, "players", "found", "names") if pl is not None else []
+ music = _cnt((lib or {}).get("Music"), "audio", default=0) if isinstance(lib, dict) else 0
+ video = _cnt((lib or {}).get("Videos"), "video", default=0) if isinstance(lib, dict) else 0
+ music_player = any(w in " ".join(players) for w in ("spotify", "foobar", "musicbee", "itunes", "winamp", "aimp",
+ "tidal", "apple music"))
+ if not music_player and not music:
+ claim = "Not a music listener on this box: skip music integrations"
+ else:
+ claim = "Listens to music locally"
+ return _res(claim, "strong", {"players": players, "music_files": music, "video_files": video,
+ "music_player": music_player})
+
+
+# ---------------------------------------------------------------- 29-31
+
+@insight(id="persona.multi_machine_owner",
+ inputs=["steam.remote_clients", "net.tailscale", "steam.login_users", "apps.install_timeline"])
+def multi_machine_owner(f):
+ """Several own machines if Tailscale peers >= 3 or Steam remote peers >= 1."""
+ peers = _cnt(f.get("net.tailscale"), "peers", "n_peers", "peer_count", "online_peers")
+ remote = _cnt(f.get("steam.remote_clients"), "count", "clients", "n")
+ if peers is None and remote is None:
+ return None
+ yes = (peers or 0) >= 3 or (remote or 0) >= 1
+ return _res(("Owns several machines" if yes else "Single machine evidence only") +
+ f" (Tailscale peers {peers}, Steam remote clients {remote}); offer cross-machine sync" * yes,
+ "strong", {"multi_machine": yes, "tailscale_peers": peers, "steam_remote_clients": remote})
+
+
+def _defaults_untouched(f):
+ out = []
+ hn = f.get("host.name_default")
+ if hn is not None and (hn is True or _truth(hn, "default", "is_default", "matches")):
+ out.append("hostname")
+ elif hn is None and isinstance(f.get("host.name"), dict):
+ if re.fullmatch(r"(DESKTOP|LAPTOP)-[A-Z0-9]{7,8}", str(f["host.name"].get("name") or "").upper()):
+ out.append("hostname")
+ un = f.get("profile.username_default")
+ if un is not None and (un is True or _truth(un, "default", "is_default")):
+ out.append("username")
+ sp = f.get("theme.spotlight_suggestions")
+ if sp is not None and _truth(sp, "suggestions_on", "on", "enabled", "default"):
+ out.append("spotlight/suggestions")
+ pb = f.get("pins.taskband_oem")
+ if pb is not None and (_cnt(pb, "oem_pins", "count", "n", default=1) or 0) > 0:
+ out.append("OEM taskbar pins")
+ wp = f.get("theme.wallpaper")
+ if wp is not None and _truth(wp, "default", "is_default", "stock"):
+ out.append("wallpaper")
+ return out
+
+
+@insight(id="persona.setup_defaults_untouched",
+ inputs=["theme.wallpaper", "theme.spotlight_suggestions", "host.name_default", "host.name", "pins.taskband_oem"])
+def setup_defaults_untouched(f):
+ """Low cosmetic customisation when >= 3 defaults remain. Tone hint only."""
+ d = _defaults_untouched(f)
+ if not any(k in f for k in ("theme.wallpaper", "theme.spotlight_suggestions", "host.name_default", "host.name",
+ "pins.taskband_oem")):
+ return None
+ low = len(d) >= 3
+ return _res(("Low cosmetic customisation: " if low else "Defaults left: ") + (", ".join(d) or "none"), "weak",
+ {"low_customisation": low, "defaults": d})
+
+
+@insight(id="persona.terse_user", inputs=["browser.history.search_terms", "files.clutter"])
+def terse_user(f):
+ """Short queries and a clean desktop: short replies."""
+ st = f.get("browser.history.search_terms")
+ cl = f.get("files.clutter")
+ words = _num(_get(st or {}, "avg_words", "mean_words", "mean_len_words")) if st is not None else None
+ desk = _cnt(cl, "desktop_items", "desktop", "desktop_files") if cl is not None else None
+ if words is None and desk is None:
+ return None
+ terse = (words is not None and words <= 3) and (desk is None or desk <= 10)
+ if not terse:
+ return None
+ return _res("Terse: prefer short replies", "weak",
+ {"terse": terse, "mean_query_words": words, "desktop_items": desk})
+
+
+# ================================================================ section 4: fresh vs old
+
+def _tenure_anchor(f):
+ pc = _date_of(f.get("profile.created"), "created", "ctime", "date", "created_utc", "value")
+ ob = _date_of(f.get("setup.oobe_done"), "date", "last_write", "oobe_done", "time", "value", "created")
+ anchors = [d for d in (pc, ob) if d]
+ if anchors:
+ return max(anchors), {"profile_created": _iso(pc), "oobe_done": _iso(ob)}
+ inst = _date_of(f.get("os.install_date"), "install_date", "InstallDate", "date", "value")
+ return inst, {"os_install_date": _iso(inst)}
+
+
+@insight(id="install.user_tenure_days",
+ inputs=["profile.created", "setup.oobe_done", "os.install_date", "net.history", "steam.local_sessions",
+ "l3.browser_install_age", "browser.profile_prefs", "prefetch.stat"])
+def user_tenure_days(f):
+ """Days since the current profile took ownership: max(profile.created, setup.oobe_done)."""
+ a, src = _tenure_anchor(f)
+ if a is None:
+ return None
+ days = int(_days(a))
+ first_net = _date_of(f.get("net.history"), "first_created", "first_date", "first_seen", "oldest", "first")
+ val = {"tenure_days": days, "anchor": _iso(a), **src}
+ claim = f"User has owned this install for {days} days (since {_iso(a)})"
+ if first_net and (first_net - a).days > 3:
+ val["first_online"] = _iso(first_net)
+ claim += f"; first network {_iso(first_net)}"
+ return _res(claim, "strong" if "profile_created" in src or "oobe_done" in src else "weak", val)
+
+
+@insight(id="install.os_lineage",
+ inputs=["setup.sysreset", "hw.gpu_history", "hw.monitor_history", "setup.oem", "setup.image_date", "os.install_date",
+ "setup.source_os_lineage", "setup.oldest_lineage_date", "setup.windows_old",
+ "pca.generaldb", "amcache.inventory_app", "wdi.startupinfo"])
+def os_lineage(f):
+ """reset > redeployed_image > oem_image > in_place_upgrade > clean, plus lineage age in years."""
+ inst = _date_of(f.get("os.install_date"), "install_date", "InstallDate", "date", "value")
+ oldest = _date_of(f.get("setup.oldest_lineage_date"), "oldest", "date", "oldest_date", "value")
+ img = _date_of(f.get("setup.image_date"), "image_date", "date", "clone_date", "oldest", "value")
+ lineage = f.get("setup.source_os_lineage")
+ gh = f.get("hw.gpu_history")
+ if inst is None and not any(k in f for k in ("setup.sysreset", "setup.oem", "setup.source_os_lineage")):
+ return None
+ img_devices = _hw_changes(f)[2]
+ redeployed = img_devices > 0 or (gh is not None and _truth(gh, "image_devices_absent", "redeployed"))
+ oem = _truth(f.get("setup.oem") or {}, "oem_image")
+ reset = _truth(f.get("setup.sysreset") or {}, "reset")
+ wold = _truth(f.get("setup.windows_old") or {}, "windows_old", "windows_bt")
+ if oldest is None:
+ oldest = _date_of(lineage, "oldest")
+ if reset:
+ kind = "reset"
+ elif redeployed:
+ kind = "redeployed_image"
+ elif oem and img and inst and img < inst - timedelta(days=30):
+ kind = "oem_image"
+ elif wold:
+ kind = "in_place_upgrade"
+ elif lineage is not None and (_cnt(lineage, "count", default=0) or 0) > 0:
+ kind = "in_place_upgrade"
+ else:
+ kind = "clean"
+ first = min([d for d in (oldest, inst, img) if d], default=None)
+ years = round(_days(first) / 365.25, 2) if first else None
+ val = {"os_lineage": kind, "install_date": _iso(inst), "oldest_lineage_date": _iso(oldest),
+ "image_date": _iso(img), "lineage_years": years, "oem": oem, "image_devices_gone": img_devices}
+ claim = f"OS lineage: {kind}" + (f", {years} years old (from {_iso(first)})" if years is not None else "")
+ return _res(claim, "strong" if inst else "weak", val)
+
+
+def _lived_in(f):
+ pts, why = 0.0, []
+
+ def add(n, r):
+ nonlocal pts
+ pts += n
+ why.append(f"+{n} {r}")
+ fp = f.get("age.footprint_counts")
+ pf = _cnt(f.get("prefetch.stat"), "files", "count", "n")
+ if pf is None:
+ pf = _cnt(fp, "prefetch", "prefetch_count", "Prefetch")
+ if pf is not None and pf >= 400:
+ add(1, f"Prefetch {int(pf)}")
+ rc = _cnt(fp, "recent", "recent_lnk", "recent_count", "Recent")
+ if rc is None:
+ rc = _cnt(f.get("files.recent_lnk"), "count", "n", "lnk")
+ if rc is not None and rc >= 150:
+ add(1, f"Recent .lnk {int(rc)}")
+ ua = _cnt(f.get("userassist.focus"), "total_focus_h", "focus_hours", "total_hours", "focus_h")
+ if ua is not None and ua >= 50:
+ add(1, f"UserAssist focus {ua:.0f} h")
+ fs = _cnt(f.get("featureusage.appswitched"), "total", "switches", "count", "sum")
+ if fs is not None and fs >= 1000:
+ add(1, f"FeatureUsage switches {int(fs)}")
+ bv = _cnt(f.get("browser.history.stats"), "visits", "total_visits", "visit_count", "visits_total")
+ if bv is not None and bv >= 1000:
+ add(1, f"browser visits {int(bv)}")
+ s = _agent_sessions(f)
+ if any((v or 0) >= 20 for v in s.values()):
+ add(1, "local agent sessions >= 20")
+ lh, _ = _local_hours(f)
+ if lh is not None and lh >= 50:
+ add(1, f"local Steam {lh:.0f} h")
+ gu = _cnt(f.get("gcs.game_history"), "uninstalled_since", "uninstalled", "n_uninstalled")
+ if gu is not None and gu >= 5:
+ add(1, f"GCS uninstalled games {int(gu)}")
+ comp = f.get("files.composition")
+ dl = _num(_get(comp or {}, "downloads_older_90d_share", "downloads_old_share", "older_90d_share"))
+ if dl is not None and (dl / 100.0 if dl > 1 else dl) > 0.25:
+ add(1, "Downloads > 25% older than 90 d")
+ cl = f.get("files.clutter")
+ if (_cnt(cl, "temp_files", "temp", "TEMP") or 0) > 1000:
+ add(0.5, "TEMP > 1000 files")
+ pw = f.get("files.profile_size_walk")
+ if (_cnt(pw, "custom_root_dirs", "custom_dirs", "nonstandard_dirs") or 0) >= 10:
+ add(0.5, "custom profile-root dirs >= 10")
+ g, m, _img = _hw_changes(f)
+ hw = int(bool(g)) + int(bool(m))
+ if hw:
+ add(min(hw, 2), "device changes after install")
+ ua_n = None
+ tx = f.get("apps.taxonomy_user_added")
+ if tx is not None:
+ ua_n = _cnt(tx, "user_added_total", "user_added", "total", "count", "n")
+ if ua_n is None:
+ ua_n = _cnt(f.get("apps.preinstalled_split"), "user_added", "n_user_added", "user")
+ if ua_n:
+ n = min(3, int(ua_n // 20))
+ if n:
+ add(n, f"user-added apps {int(ua_n)}")
+ it = f.get("apps.install_timeline")
+ months = _cnt(it, "months_spread", "distinct_months", "months_active") if it is not None else None
+ if months is None and tx is not None:
+ bm = _get(tx, "by_month")
+ months = len([m for m, n in bm.items() if (_num(n) or 0) > 0]) if isinstance(bm, dict) else None
+ if (months or 0) >= 3:
+ add(1, f"installs spread over {months} months")
+ pts = min(pts, 10.0)
+ d = _defaults_untouched(f)
+ pen = 0.5 * len(d)
+ return max(0.0, pts - pen), why, d
+
+
+@insight(id="install.lived_in_score",
+ inputs=["prefetch.stat", "age.footprint_counts", "userassist.focus", "featureusage.appswitched",
+ "browser.history.stats", "hermes.usage", "codex.usage", "claude_code.sessions",
+ "steam.local_sessions", "gcs.game_history", "files.composition", "files.clutter",
+ "files.profile_size_walk", "hw.gpu_history", "hw.monitor_history", "apps.taxonomy_user_added",
+ "apps.preinstalled_split", "apps.install_timeline", "host.name_default", "host.name", "profile.username_default",
+ "theme.spotlight_suggestions", "pins.taskband_oem"])
+def lived_in_score(f):
+ """Sum of accumulated-use points (cap 10) minus 0.5 per untouched default (min 0)."""
+ score, why, d = _lived_in(f)
+ if not why and not d:
+ return None
+ return _res(f"Lived-in score {score:g}/10", "strong" if len(why) >= 3 else "weak",
+ {"lived_in": score, "points": why, "defaults_untouched": d})
+
+
+@insight(id="install.user_history_elsewhere",
+ inputs=["files.age_hist", "files.pre_install_mtime", "files.composition", "steam.playtime", "codex.chatgpt_catalog",
+ "hermes.usage", "os.install_date", "profile.created"])
+def user_history_elsewhere(f):
+ """Account/file history older than this install. Says the person is not new; never makes the install old."""
+ a, _ = _tenure_anchor(f)
+ ev = {}
+ pim = _cnt(f.get("files.pre_install_mtime"), "count", "files", "n", "older_than_install")
+ migrated = bool(pim)
+ if pim:
+ ev["files_older_than_install"] = pim
+ ah = f.get("files.age_hist")
+ oldest_file = _date_of(ah, "oldest", "oldest_mtime", "min") if ah is not None else None
+ if oldest_file and a and oldest_file < a - timedelta(days=30):
+ migrated = True
+ ev["oldest_file"] = _iso(oldest_file)
+ comp = f.get("files.composition")
+ if isinstance(comp, dict) and isinstance(comp.get("folders"), dict) and a is not None:
+ old = {k: v.get("oldest_year") for k, v in comp["folders"].items()
+ if isinstance(v, dict) and isinstance(v.get("oldest_year"), int) and v["oldest_year"] < a.year - 1
+ and not _operator(k)}
+ if old:
+ migrated = True
+ ev["files_older_than_install"] = old
+ pt = f.get("steam.playtime")
+ lp = _date_of(pt, "oldest_last_played", "first_last_played", "oldest") if pt is not None else None
+ if lp is None and isinstance(pt, dict):
+ dates = [_dt(row[2]) for acc in (pt.get("per_account") or []) if isinstance(acc, dict)
+ for row in (acc.get("top") or []) if isinstance(row, (list, tuple)) and len(row) > 2]
+ lp = min([d for d in dates if d], default=None)
+ if lp and a and lp < a:
+ ev["steam_since"] = _iso(lp)
+ elif pt is not None and (_steam_hours(f)[0] or 0) > 0:
+ ev["steam_account_hours"] = _steam_hours(f)[0]
+ cg = f.get("codex.chatgpt_catalog")
+ cgd = _date_of(cg, "oldest", "oldest_date", "first", "since") if cg is not None else None
+ if cgd and (a is None or cgd < a):
+ ev["chatgpt_since"] = _iso(cgd)
+ hu = f.get("hermes.usage")
+ hd = _date_of(hu, "first", "first_session", "oldest", "since") if hu is not None else None
+ if hd and a and hd < a - timedelta(days=1):
+ ev["hermes_since"] = _iso(hd)
+ if not ev:
+ if not any(k in f for k in ("files.age_hist", "files.pre_install_mtime", "steam.playtime",
+ "codex.chatgpt_catalog")):
+ return None
+ return _res("No history older than this install", "weak",
+ {"user_history_elsewhere": False, "migrated_user": False})
+ return _res("User has history that predates this install (" + ", ".join(ev) + ")", "strong",
+ {"user_history_elsewhere": True, "migrated_user": migrated, "evidence": ev})
+
+
+@insight(id="install.install_state",
+ inputs=["profile.created", "setup.oobe_done", "os.install_date", "prefetch.stat", "age.footprint_counts",
+ "browser.history.stats", "userassist.focus", "apps.taxonomy_user_added"])
+def install_state(f):
+ """fresh: tenure < 30 d and lived_in < 3; settling: tenure < 120 d and lived_in < 6; else established."""
+ a, _ = _tenure_anchor(f)
+ if a is None:
+ return None
+ t = _days(a)
+ li, _, _ = _lived_in(f)
+ state = "fresh" if t < 30 and li < 3 else "settling" if t < 120 and li < 6 else "established"
+ return _res(f"Install state: {state} (tenure {int(t)} d, lived-in {li:g})", "strong",
+ {"install_state": state, "tenure_days": int(t), "lived_in": li})
+
+
+# ================================================================ report 13 derivations
+
+_PHONE_VENDORS = ("samsung", "google", "pixel", "xiaomi", "oneplus", "motorola", "huawei", "oppo", "vivo", "apple",
+ "iphone", "nothing", "realme")
+
+
+@insight(id="phone.wu_driver_hint", inputs=["wu.history", "phone.link", "hw.usb_history"])
+def wu_driver_hint(f):
+ """Phone vendor from Windows Update driver titles (modem/USB/ADB drivers). Model is not recorded."""
+ wu = f.get("wu.history")
+ if wu is None:
+ return None
+ titles = _names(wu, "driver_titles", "drivers", "titles") or [_txt(wu)]
+ hits = set()
+ for t in titles:
+ if not re.search(r"\b(modem|usb|mtp|adb|android|mobile)\b", t):
+ continue
+ for v in _PHONE_VENDORS:
+ if re.search(rf"\b{v}\b", t):
+ hits.add(v)
+ if not hits:
+ return None
+ paired = f.get("phone.link")
+ return _res("A " + "/".join(sorted(hits)) + " phone was connected by USB at least once (model unknown)", "weak",
+ {"phone_vendor": sorted(hits), "phone_link_paired": _truth(paired or {}, "paired",
+ "HasPreviouslyPaired")})
+
+
+@insight(id="l3.image_origin",
+ inputs=["pca.generaldb", "wdi.startupinfo", "amcache.inventory_app", "lsm.sessions", "os.install_date",
+ "profile.created", "setup.oem", "setup.image_date", "setup.system_log_oldest",
+ "eventlog.power_history"])
+def image_origin(f):
+ """Earliest record per source vs the profile creation: >= 2 sources more than 30 d older = OEM-preloaded image."""
+ a, _ = _tenure_anchor(f)
+ earliest = {}
+ for pid, keys in (("pca.generaldb", ("first", "first_date", "oldest", "min_date", "start")),
+ ("wdi.startupinfo", ("oldest_other_sid", "oldest", "first", "min_date")),
+ ("amcache.inventory_app", ("oldest_install", "oldest", "first", "min_install_date")),
+ ("lsm.sessions", ("first", "oldest", "since", "first_event")),
+ ("setup.image_date", ("setupapi_first", "image_date")),
+ ("setup.system_log_oldest", ("oldest", "system_log_oldest", "date", "value")),
+ ("eventlog.power_history", ("system_log_oldest",))):
+ d = _date_of(f.get(pid), *keys) if pid in f else None
+ if d is None and pid == "setup.image_date" and isinstance(f.get(pid), dict):
+ d = _dt(str(f[pid].get("setupapi_first") or "").replace("/", "-"))
+ if d:
+ earliest[pid] = d
+ if not earliest or a is None:
+ return None
+ pre = {k: _iso(v) for k, v in earliest.items() if v < a - timedelta(days=30)}
+ if len(pre) >= 2:
+ oem = _truth(f.get("setup.oem") or {}, "oem_image")
+ origin = "oem_image" if oem else "pre_staged_image"
+ claim = (f"{'OEM-preloaded' if oem else 'Pre-staged'} image: {len(pre)} sources have records from more than "
+ f"30 days before the profile ({_iso(a)})")
+ return _res(claim, "strong" if len(pre) >= 3 or oem else "weak",
+ {"origin": origin, "pre_profile_records": pre, "profile": _iso(a)})
+ return _res(f"Clean install: earliest records are within 30 days of the profile ({_iso(a)})",
+ "strong" if len(earliest) >= 2 else "weak",
+ {"origin": "clean", "earliest": {k: _iso(v) for k, v in earliest.items()}})
+
+
+RE_TOOLS = ("ghidra", "dnspy", "ida", "x64dbg", "ilspy", "cheat engine", "wireshark", "procmon", "jdk")
+
+
+@insight(id="l3.persona_additions",
+ inputs=["explorer.muicache", "msi.install_events", "search.windows_db", "gpu.per_app_prefs",
+ "boot.diag_perf"])
+def persona_additions(f):
+ """Launched-app and install-event evidence: AAA gamer, creator, reverse-engineer."""
+ mui = f.get("explorer.muicache")
+ msi = f.get("msi.install_events")
+ sdb = f.get("search.windows_db")
+ gpu = f.get("gpu.per_app_prefs")
+ if not any((mui, msi, sdb, gpu)):
+ return None
+ blob = " ".join(_txt(x) for x in (mui, msi, sdb) if x is not None)
+ blob = " ".join(w for w in blob.split() if not _operator(w))
+ tags = {}
+ games = _cnt(mui, "games", "n_games", "game_names")
+ hdr = _cnt(gpu, "autohdr_games", "autohdr", "n_autohdr")
+ if (games or 0) >= 10 or (hdr or 0) >= 2:
+ tags["aaa_gamer"] = {"launched_games": games, "autohdr_titles": hdr}
+ cr = sorted({w for w in CREATIVE if w in blob})
+ if len(cr) >= 3:
+ tags["creator"] = cr
+ rt = sorted({w for w in RE_TOOLS if w in blob and w != "jdk"})
+ if rt:
+ tags["reverse_engineering"] = rt
+ if not tags:
+ return None
+ return _res("Launched/installed-app evidence: " + ", ".join(tags), "strong" if len(tags) >= 1 and mui else "weak",
+ tags)
+
+
+@insight(id="persona.dense_ui", inputs=["display.per_monitor_dpi", "shell.taskbar_dev_settings"])
+def dense_ui(f):
+ """Display scaled below recommended plus the taskbar End-task toggle: prefer compact output."""
+ dpi = f.get("display.per_monitor_dpi")
+ tb = f.get("shell.taskbar_dev_settings")
+ below = dpi is not None and ((_num(_get(dpi, "min_offset", "dpi_offset", "DpiValue")) or 0) < 0 or
+ _truth(dpi, "below_recommended", "scaled_down"))
+ endtask = tb is not None and _truth(tb, "TaskbarEndTask", "end_task", "endtask")
+ if not (below or endtask):
+ return None
+ return _res("Dense-UI power user: prefer compact output", "weak", {"scaled_below": below, "end_task": endtask})
+
+
+@insight(id="persona.clipboard_flows", inputs=["input.typing_clipboard"])
+def clipboard_flows(f):
+ """Clipboard history on and Win+V used."""
+ v = f.get("input.typing_clipboard")
+ if v is None:
+ return None
+ on = _truth(v, "clipboard_history", "EnableClipboardHistory", "history_on")
+ used = _truth(v, "win_v_used", "ShellHotKeyUsed", "hotkey_used")
+ if not on:
+ return None
+ return _res("Clipboard history in use" + (" (Win+V used)" if used else ""), "weak",
+ {"clipboard_history": on, "win_v_used": used})
+
+
+@insight(id="persona.windows_ai_off", inputs=["winai.surfaces"])
+def windows_ai_off(f):
+ """No Recall, Copilot disabled, no Copilot app: do not suggest Windows Copilot features."""
+ v = f.get("winai.surfaces")
+ if v is None:
+ return None
+ t = _txt(v)
+ recall = _truth(v, "recall", "recall_present", "aix")
+ copilot = _truth(v, "copilot_app", "copilot_enabled") and "featureisdisabled" not in t
+ if recall or copilot:
+ return _res("Windows AI surfaces present", "weak", {"recall": recall, "copilot": copilot})
+ return _res("Windows Copilot/Recall off: do not suggest them", "weak", {"recall": False, "copilot": False})
+
+
+@insight(id="persona.skip_print_phone", inputs=["print.printers_scanners", "phone.link"])
+def skip_print_phone(f):
+ """No physical printer/scanner and no paired phone: skip those onboarding steps."""
+ pr = f.get("print.printers_scanners")
+ ph = f.get("phone.link")
+ if pr is None and ph is None:
+ return None
+ printers = _cnt(pr, "physical", "physical_printers", "n_physical", "real_printers", default=0) if pr is not None else None
+ scanners = _cnt(pr, "scanners", "n_scanners", default=0) if pr is not None else None
+ paired = _truth(ph or {}, "paired", "HasPreviouslyPaired", "has_paired")
+ skip = []
+ if pr is not None and not printers and not scanners:
+ skip.append("print/scan")
+ if ph is not None and not paired:
+ skip.append("phone")
+ if not skip:
+ return None
+ return _res("Skip onboarding for: " + ", ".join(skip), "weak",
+ {"physical_printers": printers, "scanners": scanners, "phone_paired": paired})
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.py
new file mode 100644
index 00000000000..4bbf06f919d
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/host_identity.py
@@ -0,0 +1,1577 @@
+"""Host, identity, install age, locale, shell prefs, security posture and network probes (Windows).
+
+Signal ids follow reports/14-triage.json. Every route here is registry, stat or a single small spawn,
+except the PowerShell sidecar probes (CIM-only signals) and the deep tier.
+No I/O at import time.
+"""
+from __future__ import annotations
+
+import datetime as _dt
+import os
+import re
+import sys
+
+from userscan.registry import probe, ps_probe
+
+# ---------------------------------------------------------------- helpers
+
+_NOISE_RX = re.compile(r"(^|[\\/])(hn-e2e|ns960|ns923[^\\/]*|lhm|shots|user-insights-lab|hermes-[^\\/]*)([\\/]|$)", re.I)
+_NT_CV = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
+_NOW = None
+
+
+def _now():
+ global _NOW
+ if _NOW is None:
+ _NOW = _dt.datetime.now(_dt.timezone.utc)
+ return _NOW
+
+
+def _is_noise(path: str) -> bool:
+ return bool(path) and bool(_NOISE_RX.search(path))
+
+
+def _root(path: str):
+ import winreg
+ head, _, sub = path.partition("\\")
+ return {"HKLM": winreg.HKEY_LOCAL_MACHINE, "HKCU": winreg.HKEY_CURRENT_USER,
+ "HKU": winreg.HKEY_USERS, "HKCR": winreg.HKEY_CLASSES_ROOT}.get(head), sub
+
+
+def _vals(path: str, limit: int = 3000):
+ """All values of a key as {name: data}, or None if the key is missing."""
+ if sys.platform != "win32":
+ return None
+ import winreg
+ root, sub = _root(path)
+ try:
+ k = winreg.OpenKey(root, sub)
+ except OSError:
+ return None
+ out = {}
+ with k:
+ for i in range(limit):
+ try:
+ n, v, _t = winreg.EnumValue(k, i)
+ except OSError:
+ break
+ out[n] = v
+ return out
+
+
+def _subs(h, path: str):
+ return h.reg(path) or []
+
+
+def _key_exists(path: str) -> bool:
+ if sys.platform != "win32":
+ return False
+ import winreg
+ root, sub = _root(path)
+ try:
+ winreg.CloseKey(winreg.OpenKey(root, sub))
+ return True
+ except OSError:
+ return False
+
+
+def _value_present(path: str, name: str) -> bool:
+ """Presence of a registry value without reading its data (T3-safe)."""
+ import ctypes
+ from ctypes import wintypes
+ root, sub = _root(path)
+ adv = ctypes.WinDLL("advapi32")
+ fn = adv.RegGetValueW
+ fn.argtypes = [wintypes.HKEY, wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.DWORD,
+ ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(wintypes.DWORD)]
+ fn.restype = wintypes.LONG
+ cb = wintypes.DWORD(0)
+ rc = fn(wintypes.HKEY(root), sub, name, 0x0000FFFF, None, None, ctypes.byref(cb))
+ return rc == 0
+
+
+def _lastwrite(path: str):
+ if sys.platform != "win32":
+ return None
+ import winreg
+ root, sub = _root(path)
+ try:
+ with winreg.OpenKey(root, sub) as k:
+ return _ft_iso(winreg.QueryInfoKey(k)[2])
+ except OSError:
+ return None
+
+
+def _ft_iso(ft):
+ if not isinstance(ft, int) or ft <= 0:
+ return None
+ try:
+ return (_dt.datetime(1601, 1, 1, tzinfo=_dt.timezone.utc)
+ + _dt.timedelta(microseconds=ft // 10)).isoformat(timespec="seconds")
+ except OverflowError:
+ return None
+
+
+def _unix_iso(s):
+ if not isinstance(s, int) or s <= 0:
+ return None
+ return _dt.datetime.fromtimestamp(s, _dt.timezone.utc).isoformat(timespec="seconds")
+
+
+def _systemtime(b):
+ if not isinstance(b, (bytes, bytearray)) or len(b) < 16:
+ return None
+ y, mo, _dow, d, hh, mi, s, _ms = [int.from_bytes(b[i:i + 2], "little") for i in range(0, 16, 2)]
+ try:
+ return _dt.datetime(y, mo, d, hh, mi, s).isoformat()
+ except ValueError:
+ return None
+
+
+def _days_ago(iso):
+ if not iso:
+ return None
+ t = _dt.datetime.fromisoformat(iso)
+ if t.tzinfo is None:
+ t = t.replace(tzinfo=_dt.timezone.utc)
+ return round((_now() - t).total_seconds() / 86400, 2)
+
+
+def _within(iso, days):
+ d = _days_ago(iso)
+ return d is not None and d <= days
+
+
+def _birth(h, path: str):
+ """Creation time (Windows st_birthtime / st_ctime) as iso, or None."""
+ try:
+ st = os.stat(h.expand(path))
+ except OSError:
+ return None
+ t = getattr(st, "st_birthtime", None) or st.st_ctime
+ return _dt.datetime.fromtimestamp(t, _dt.timezone.utc).isoformat(timespec="seconds")
+
+
+def _s32(x):
+ return x - (1 << 32) if isinstance(x, int) and x >= (1 << 31) else x
+
+
+def _run_text(h, args, timeout_ms):
+ """h.run returns bytes or str depending on its text flag; normalise to str (None on failure)."""
+ out = h.run(args, timeout_ms)
+ if out is None:
+ return None
+ return out.decode("utf-8", "replace") if isinstance(out, (bytes, bytearray)) else str(out)
+
+
+def _current_sid(h):
+ """SID of the collecting user, matched from ProfileList by profile path. Cached on h."""
+ if hasattr(h, "_hi_sid"):
+ return h._hi_sid
+ home = os.path.normcase(os.path.normpath(h.l0.get("home", "")))
+ sid = None
+ base = _NT_CV + r"\ProfileList"
+ for s in _subs(h, base):
+ p = h.reg(base + "\\" + s, "ProfileImagePath") or ""
+ if os.path.normcase(os.path.normpath(os.path.expandvars(p))) == home:
+ sid = s
+ break
+ h._hi_sid = sid
+ return sid
+
+
+def _sid_kind(sid):
+ if not sid:
+ return None
+ if sid.startswith("S-1-12-1-"):
+ return "azuread"
+ if sid.startswith("S-1-5-21-"):
+ return "local_or_domain"
+ return "other"
+
+
+# ================================================================ host
+
+@probe(id="host.native_arch", level="L1", family="host", tier="T0", collect="core")
+def native_arch(h, facts):
+ """Machine architecture from IsWow64Process2 nativeMachine (L0 fact)."""
+ return {"present": True, "arch": h.l0.get("native_arch")}
+
+
+@probe(id="host.python_emulated", level="L1", family="host", tier="T0", collect="core")
+def python_emulated(h, facts):
+ """Collector interpreter arch from its PE header vs machine arch; emulated x64 Python on ARM64 is 2-6x slower."""
+ return {"present": True, "python_arch": h.l0.get("python_arch"),
+ "native_arch": h.l0.get("native_arch"), "emulated": bool(h.l0.get("python_emulated"))}
+
+
+@probe(id="os.build", level="L1", family="host", tier="T0", collect="core")
+def os_build(h, facts):
+ """OS build as CurrentBuild.UBR plus DisplayVersion (not BuildLabEx)."""
+ b = h.reg(_NT_CV, "CurrentBuild")
+ if not b:
+ return None
+ ubr = h.reg(_NT_CV, "UBR")
+ return {"present": True, "build": f"{b}.{ubr}" if ubr is not None else str(b),
+ "current_build": int(b), "display_version": h.reg(_NT_CV, "DisplayVersion")}
+
+
+@probe(id="os.edition", level="L1", family="host", tier="T0", collect="core")
+def os_edition(h, facts):
+ """Windows edition and marketing name (ProductName says 'Windows 10' on 11; derive from build)."""
+ name = h.reg(_NT_CV, "ProductName") or ""
+ b = int(h.reg(_NT_CV, "CurrentBuild") or 0)
+ return {"present": bool(name), "marketing_name": name.replace("Windows 10", "Windows 11") if b >= 22000 else name,
+ "edition_id": h.reg(_NT_CV, "EditionID"),
+ "composition_edition_id": h.reg(_NT_CV, "CompositionEditionID"),
+ "installation_type": h.reg(_NT_CV, "InstallationType")}
+
+
+@probe(id="os.insider", level="L1", family="host", tier="T0", collect="core")
+def os_insider(h, facts):
+ """Windows Insider ring enrollment (WindowsSelfHost keys)."""
+ a = r"HKLM\SOFTWARE\Microsoft\WindowsSelfHost\Applicability"
+ branch, ring = h.reg(a, "BranchName"), h.reg(a, "Ring")
+ return {"present": True, "insider": bool(branch or ring), "branch": branch, "ring": ring,
+ "ui_branch": h.reg(r"HKLM\SOFTWARE\Microsoft\WindowsSelfHost\UI\Selection", "UIBranch")}
+
+
+# ================================================================ identity
+
+_CRED_PROVIDERS = {
+ "{D6886603-9D2F-4EB2-B667-1971041FA96B}": "PIN", "{60B78E88-EAD8-445C-9CFD-0B87F74EA6CD}": "Password",
+ "{8AF662BF-65A0-4D0A-A540-A338A999D36F}": "Face", "{BEC09223-B018-416D-A0AC-523971B639F5}": "Fingerprint",
+ "{F8A1793B-7873-4046-B2A7-1F318747F427}": "FIDO", "{1B283861-754F-4022-AD47-A5EAAA618894}": "SmartCard",
+ "{27FBDB57-B613-4AF2-9D7E-4FA7A66C21AD}": "TrustedSignal",
+ "{C5D7540A-CD51-453B-B22B-05305BA03F07}": "CloudExperienceCredProv",
+}
+_LOGONUI = r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI"
+
+
+@probe(id="acct.account_type", level="L1", family="identity", tier="T0", collect="core")
+def account_type(h, facts):
+ """Local vs Microsoft vs Entra account: SID prefix, LogonUI domain prefix, IdentityCRL/IdentityStore counts (no names)."""
+ sid = _current_sid(h)
+ llu = (h.reg(_LOGONUI, "LastLoggedOnSAMUser") or h.reg(_LOGONUI, "LastLoggedOnUser") or "").lower()
+ msa_prefix = llu.startswith("microsoftaccount\\")
+ aad_prefix = llu.startswith("azuread\\")
+ crl = len(_subs(h, r"HKCU\Software\Microsoft\IdentityCRL\StoredIdentities"))
+ providers = {}
+ if sid:
+ base = r"HKLM\SOFTWARE\Microsoft\IdentityStore\Cache" + "\\" + sid + r"\IdentityCache"
+ for s in _subs(h, base)[:20]:
+ pn = str(h.reg(base + "\\" + s, "ProviderName"))
+ providers[pn] = providers.get(pn, 0) + 1
+ kind = _sid_kind(sid)
+ if kind == "azuread" or aad_prefix:
+ t = "entra"
+ elif msa_prefix or any("microsoftaccount" in p.lower() for p in providers):
+ t = "microsoft"
+ elif kind == "local_or_domain":
+ t = "local"
+ else:
+ t = "unknown"
+ return {"present": True, "type": t, "sid_kind": kind, "logonui_msa_prefix": msa_prefix,
+ "logonui_azuread_prefix": aad_prefix,
+ "last_logon_is_collecting_user": (llu.split("\\")[-1] == h.l0.get("user", "").lower()) if llu else None,
+ "identitycrl_stored_identities": crl, "identitystore_providers": providers}
+
+
+@probe(id="host.name", level="L1", family="identity", tier="T0", collect="core")
+def host_name(h, facts):
+ """Computer name. local_only: identifies the machine, never send off-host."""
+ n = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName", "ComputerName")
+ pending = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName", "ComputerName")
+ return {"present": bool(n), "name": n, "local_only": True,
+ "pending_rename": bool(pending and n and pending.lower() != n.lower())}
+
+
+_DEFAULT_USERS = {"public", "default", "default user", "all users", "defaultapppool"}
+
+
+@probe(id="profile.count", level="L1", family="identity", tier="T0", collect="core")
+def profile_count(h, facts):
+ """Number of real user profiles (ProfileList non-system SIDs, C:\\Users dirs); operator side homes excluded."""
+ base = _NT_CV + r"\ProfileList"
+ nonsys, noise = 0, 0
+ for s in _subs(h, base):
+ if s in ("S-1-5-18", "S-1-5-19", "S-1-5-20") or not s.startswith(("S-1-5-21-", "S-1-12-1-")):
+ continue
+ p = os.path.expandvars(h.reg(base + "\\" + s, "ProfileImagePath") or "")
+ if _is_noise(p):
+ noise += 1
+ continue
+ nonsys += 1
+ users = []
+ try:
+ with os.scandir(r"C:\Users") as it:
+ for _, e in zip(range(200), it):
+ if e.is_dir() and e.name.lower() not in _DEFAULT_USERS:
+ users.append(e.name)
+ except OSError:
+ pass
+ users_real = [n for n in users if not _is_noise("\\" + n)]
+ return {"present": True, "nonsystem": nonsys, "operator_excluded": noise,
+ "c_users_nondefault": len(users_real), "current_found": _current_sid(h) is not None}
+
+
+@probe(id="profile.last_load", level="L1", family="identity", tier="T0", collect="core", gate="profile.count")
+def profile_last_load(h, facts):
+ """Last interactive profile load time of the collecting user (ProfileList FILETIME)."""
+ sid = _current_sid(h)
+ if not sid:
+ return None
+ k = _NT_CV + r"\ProfileList" + "\\" + sid
+ lo, hi = h.reg(k, "LocalProfileLoadTimeLow"), h.reg(k, "LocalProfileLoadTimeHigh")
+ if lo is None or hi is None:
+ return None
+ t = _ft_iso((hi << 32) | lo)
+ return {"present": True, "last_load": t, "days_ago": _days_ago(t)}
+
+
+@probe(id="profile.rid", level="L1", family="identity", tier="T0", collect="core", gate="profile.count")
+def profile_rid(h, facts):
+ """RID of the collecting user; 1001 = first account created at OOBE."""
+ sid = _current_sid(h)
+ if not sid:
+ return None
+ rid = int(sid.rsplit("-", 1)[-1])
+ return {"present": True, "rid": rid, "first_oobe_user": rid == 1001}
+
+
+_AGENT_ACCT_RX = re.compile(r"^(CodexSandbox\w*|ClaudeSandbox\w*|WsiAccount|sshd|docker-users)$", re.I)
+
+
+@probe(id="acct.local_users", level="L2", family="identity", tier="T1", collect="extended", gate="profile.count")
+def local_users(h, facts):
+ """Local account counts via NetUserEnum (no PowerShell); names never emitted, agent sandbox accounts counted by kind."""
+ import ctypes
+ from ctypes import wintypes
+
+ class USER_INFO_20(ctypes.Structure):
+ _fields_ = [("name", wintypes.LPWSTR), ("full_name", wintypes.LPWSTR), ("comment", wintypes.LPWSTR),
+ ("flags", wintypes.DWORD), ("user_id", wintypes.DWORD)]
+ net = ctypes.WinDLL("netapi32")
+ net.NetUserEnum.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p),
+ wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD),
+ ctypes.POINTER(wintypes.DWORD)]
+ net.NetApiBufferFree.argtypes = [ctypes.c_void_p]
+ buf = ctypes.c_void_p()
+ read, total, resume = wintypes.DWORD(), wintypes.DWORD(), wintypes.DWORD(0)
+ rc = net.NetUserEnum(None, 20, 2, ctypes.byref(buf), 0xFFFFFFFF, ctypes.byref(read), ctypes.byref(total), ctypes.byref(resume))
+ if rc not in (0, 234) or not buf:
+ return {"present": False, "error": rc}
+ me = h.l0.get("user", "").lower()
+ out = {"total": 0, "enabled": 0, "enabled_kinds": {"current": 0, "builtin": 0, "agent_or_tool": 0, "other_human": 0}}
+ try:
+ arr = ctypes.cast(buf, ctypes.POINTER(USER_INFO_20 * read.value)).contents
+ for u in arr:
+ out["total"] += 1
+ if u.flags & 0x2: # UF_ACCOUNTDISABLE
+ continue
+ out["enabled"] += 1
+ name = (u.name or "")
+ if name.lower() == me:
+ kind = "current"
+ elif u.user_id in (500, 501, 503, 504):
+ kind = "builtin"
+ elif _AGENT_ACCT_RX.match(name):
+ kind = "agent_or_tool"
+ else:
+ kind = "other_human"
+ out["enabled_kinds"][kind] += 1
+ finally:
+ net.NetApiBufferFree(buf)
+ out["present"] = True
+ return out
+
+
+# ================================================================ install_age
+
+@probe(id="age.footprint_counts", level="L1", family="install_age", tier="T0", collect="core")
+def footprint_counts(h, facts):
+ """Lived-in counts: Prefetch, Recent .lnk, Uninstall entries, AppX package dirs."""
+ recent = h.list_dir(os.path.join(h.l0.get("appdata", ""), r"Microsoft\Windows\Recent"), 5000)
+ return {"present": True,
+ "prefetch": h.count_dir(r"C:\Windows\Prefetch", 5000),
+ "recent_lnk": sum(1 for n in recent if n.lower().endswith(".lnk")),
+ "uninstall_hklm": len(_subs(h, r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall")),
+ "uninstall_hklm_wow64": len(_subs(h, r"HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall")),
+ "uninstall_hkcu": len(_subs(h, r"HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall")),
+ "packages_dirs": h.count_dir(os.path.join(h.l0.get("localappdata", ""), "Packages"), 5000)}
+
+
+_MS_PKG_RX = re.compile(r"^(Microsoft|MicrosoftWindows|Windows|MicrosoftCorporationII|Clipchamp|MSTeams)\b", re.I)
+
+
+@probe(id="apps.appx_provisioned", level="L1", family="install_age", tier="T0", collect="core")
+def appx_provisioned(h, facts):
+ """Image-provisioned AppX packages (AppxAllUserStore); non-Microsoft ones mark an OEM image, deprovisioned ones a debloat."""
+ base = r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore"
+ apps = _subs(h, base + r"\Applications")
+ if not apps:
+ return None
+ oem = sorted({a.split("_")[0] for a in apps if not _MS_PKG_RX.match(a)})
+ return {"present": True, "provisioned": len(apps), "oem_provisioned": len(oem), "oem_families": oem[:20],
+ "deprovisioned": len(_subs(h, base + r"\Deprovisioned"))}
+
+
+@probe(id="os.install_date", level="L1", family="install_age", tier="T0", collect="core")
+def os_install_date(h, facts):
+ """Current OS image install date (last install, not first use)."""
+ d = h.reg(_NT_CV, "InstallDate")
+ iso = _unix_iso(d)
+ return {"present": bool(iso), "install_date": iso, "days_ago": _days_ago(iso),
+ "install_time": _ft_iso(h.reg(_NT_CV, "InstallTime"))}
+
+
+@probe(id="profile.created", level="L1", family="install_age", tier="T0", collect="core", gate="profile.count")
+def profile_created(h, facts):
+ """Creation time of the user profile folder and NTUSER.DAT: user-tenure anchor."""
+ home = h.l0.get("home", "")
+ folder, ntuser = _birth(h, home), _birth(h, os.path.join(home, "NTUSER.DAT"))
+ first = min([t for t in (folder, ntuser) if t], default=None)
+ return {"present": bool(first), "created": first, "folder": folder, "ntuser": ntuser, "days_ago": _days_ago(first)}
+
+
+@probe(id="setup.image_date", level="L1", family="install_age", tier="T0", collect="core")
+def setup_image_date(h, facts):
+ """Factory/capture date of the image: CloneTag, setupapi.setup.log head, Windows dir and Panther ctimes."""
+ clone = h.reg(r"HKLM\SYSTEM\Setup", "CloneTag")
+ if isinstance(clone, list):
+ clone = clone[0] if clone else None
+ first = None
+ try:
+ with open(r"C:\Windows\INF\setupapi.setup.log", "r", encoding="utf-8", errors="replace") as f:
+ m = re.search(r"Section start (\d{4}/\d\d/\d\d \d\d:\d\d:\d\d)", f.read(8192))
+ first = m.group(1) if m else None
+ except OSError:
+ pass
+ dates = []
+ if isinstance(clone, str):
+ try:
+ dates.append(_dt.datetime.strptime(clone.strip(), "%a %b %d %H:%M:%S %Y").isoformat())
+ except ValueError:
+ pass
+ if first:
+ dates.append(first.replace("/", "-").replace(" ", "T"))
+ win = _birth(h, r"C:\Windows")
+ if win:
+ dates.append(win[:19])
+ return {"present": True, "image_date": min(dates) if dates else None, "clonetag": clone, "setupapi_first": first,
+ "windows_dir_created": win,
+ "software_hive_created": _birth(h, r"C:\Windows\System32\config\SOFTWARE"),
+ "panther_setupact_created": _birth(h, r"C:\Windows\Panther\setupact.log"),
+ "panther_unattend": h.exists(r"C:\Windows\Panther\unattend.xml"),
+ "panther_miglog": h.exists(r"C:\Windows\Panther\MigLog.xml")}
+
+
+@probe(id="setup.oem", level="L1", family="install_age", tier="T0", collect="core")
+def setup_oem(h, facts):
+ """OEM preload marker: OEMInformation Manufacturer/Model and C:\\Recovery\\OEM."""
+ k = r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\OEMInformation"
+ mfr = h.reg(k, "Manufacturer")
+ rec = _birth(h, r"C:\Recovery\OEM")
+ return {"present": True, "oem_image": bool(mfr), "manufacturer": mfr, "model": h.reg(k, "Model"),
+ "recovery_oem_created": rec}
+
+
+@probe(id="setup.oobe_done", level="L1", family="install_age", tier="T0", collect="core")
+def setup_oobe_done(h, facts):
+ """OOBE key LastWriteTime: when the user took ownership of the machine."""
+ t = _lastwrite(r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Setup\OOBE")
+ return {"present": bool(t), "date": t, "days_ago": _days_ago(t)}
+
+
+@probe(id="setup.source_os_lineage", level="L1", family="install_age", tier="T0", collect="core")
+def source_os_lineage(h, facts):
+ """Prior OS installs from HKLM\\SYSTEM\\Setup\\Source OS keys (survive resets and upgrades)."""
+ rows = []
+ for s in _subs(h, r"HKLM\SYSTEM\Setup"):
+ if not s.startswith("Source OS"):
+ continue
+ k = r"HKLM\SYSTEM\Setup" + "\\" + s
+ rows.append({"date": (_unix_iso(h.reg(k, "InstallDate")) or "")[:10] or None,
+ "edition": h.reg(k, "EditionID"), "build": h.reg(k, "CurrentBuild"),
+ "version": h.reg(k, "DisplayVersion") or h.reg(k, "ReleaseId")})
+ rows.sort(key=lambda r: r["date"] or "")
+ return {"present": True, "count": len(rows), "oldest": rows[0]["date"] if rows else None,
+ "editions": sorted({r["edition"] for r in rows if r["edition"]}), "lineage": rows[:20]}
+
+
+@probe(id="setup.sysreset", level="L1", family="install_age", tier="T0", collect="core")
+def setup_sysreset(h, facts):
+ """C:\\$SysReset presence and ctime: 'Reset this PC' marker."""
+ t = _birth(h, r"C:\$SysReset")
+ return {"present": True, "reset": bool(t), "created": t}
+
+
+@probe(id="setup.windows_old", level="L1", family="install_age", tier="T0", collect="core")
+def setup_windows_old(h, facts):
+ """In-place upgrade residue: C:\\Windows.old, C:\\$WINDOWS.~BT."""
+ return {"present": True, "windows_old": h.exists(r"C:\Windows.old"), "windows_bt": h.exists(r"C:\$WINDOWS.~BT")}
+
+
+_TYPES = {71: "wireless", 6: "wired", 23: "vpn", 243: "mobile_broadband", 53: "virtual"}
+_CATS = {0: "public", 1: "private", 2: "domain"}
+
+
+def _network_profiles(h):
+ if hasattr(h, "_hi_netprof"):
+ return h._hi_netprof
+ base = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Profiles"
+ rows = []
+ for s in _subs(h, base)[:500]:
+ v = _vals(base + "\\" + s) or {}
+ rows.append({"type": _TYPES.get(v.get("NameType"), str(v.get("NameType"))),
+ "category": _CATS.get(v.get("Category"), str(v.get("Category"))),
+ "created": _systemtime(v.get("DateCreated")),
+ "last": _systemtime(v.get("DateLastConnected"))})
+ h._hi_netprof = rows
+ return rows
+
+
+@probe(id="net.history", level="L2", family="install_age", tier="T1", collect="core", gate="os.install_date")
+def net_history(h, facts):
+ """NetworkList profiles: network count by type and first/last DateCreated (first-online marker). No SSIDs."""
+ rows = _network_profiles(h)
+ if not rows:
+ return None
+ by_type, by_cat = {}, {}
+ for r in rows:
+ by_type[r["type"]] = by_type.get(r["type"], 0) + 1
+ by_cat[r["category"]] = by_cat.get(r["category"], 0) + 1
+ created = sorted(r["created"] for r in rows if r["created"])
+ last = sorted(r["last"] for r in rows if r["last"])
+ return {"present": True, "networks": len(rows), "by_type": by_type, "by_category": by_cat,
+ "first_created": created[0] if created else None, "last_created": created[-1] if created else None,
+ "last_connected": last[-1] if last else None}
+
+
+def _utf16_strings(b, minlen=6):
+ return [x.decode("utf-16le") for x in re.findall(rb"(?:[\x20-\x7e]\x00){%d,}" % minlen, b)]
+
+
+@probe(id="pins.taskband_oem", level="L2", family="install_age", tier="T0", collect="core", gate="pins.taskbar")
+def taskband_oem(h, facts):
+ """Packaged-app pins in the Taskband blob; OEM AUMIDs still present = untouched OEM taskbar layout."""
+ fav = h.reg(r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Taskband", "Favorites")
+ if not isinstance(fav, (bytes, bytearray)):
+ return None
+ aumids = sorted({s.split("_")[0] + "!" + s.split("!")[-1] for s in _utf16_strings(fav) if "!" in s and "_" in s})
+ oem = [a for a in aumids if not _MS_PKG_RX.match(a)]
+ return {"present": True, "packaged_pins": len(aumids), "oem_pins": oem, "oem_layout_present": bool(oem),
+ "taskband_lastwrite": _lastwrite(r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Taskband")}
+
+
+@probe(id="setup.system_log_oldest", level="L2", family="install_age", tier="T0", collect="extended", gate="os.install_date")
+def system_log_oldest(h, facts):
+ """Oldest retained System event (measures log retention; image-date corroboration only)."""
+ txt = _run_text(h, ["wevtutil", "qe", "System", "/c:1", "/rd:false", "/f:xml"], 5000) or ""
+ m = re.search(r"SystemTime='([^']+)'", txt)
+ if not m:
+ return None
+ info = _run_text(h, ["wevtutil", "gli", "System"], 3000) or ""
+ n = re.search(r"numberOfLogRecords:\s*(\d+)", info)
+ return {"present": True, "oldest": m.group(1)[:19], "records": int(n.group(1)) if n else None}
+
+
+# ================================================================ locale
+
+_INTL = r"HKCU\Control Panel\International"
+
+
+@probe(id="kbd.layouts", level="L1", family="locale", tier="T0", collect="core")
+def kbd_layouts(h, facts):
+ """Keyboard layouts from Preload + Substitutes (GetKeyboardLayoutList is empty over ssh)."""
+ pre = _vals(r"HKCU\Keyboard Layout\Preload") or {}
+ sub = _vals(r"HKCU\Keyboard Layout\Substitutes") or {}
+ out, seen = [], set()
+ for k in sorted(pre, key=lambda x: int(x) if x.isdigit() else 0):
+ klid = sub.get(pre[k], pre[k])
+ if klid.upper() in seen:
+ continue
+ seen.add(klid.upper())
+ out.append({"klid": klid, "name": h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\Keyboard Layouts" + "\\" + klid, "Layout Text")})
+ return {"present": bool(out), "layouts": out, "count": len(out), "preload_entries": len(pre),
+ "ime": any(str(x["klid"]).upper().startswith("E0") for x in out)}
+
+
+@probe(id="kbd.scancode_map", level="L1", family="locale", tier="T0", collect="core")
+def kbd_scancode_map(h, facts):
+ """Scancode Map key remaps (e.g. CapsLock->Ctrl): power-user hint."""
+ v = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\Keyboard Layout", "Scancode Map")
+ n = (int.from_bytes(v[8:12], "little") - 1) if isinstance(v, (bytes, bytearray)) and len(v) >= 12 else 0
+ return {"present": True, "remapped": n > 0, "remaps": max(n, 0)}
+
+
+def _lcid_name(lcid):
+ import ctypes
+ buf = ctypes.create_unicode_buffer(85)
+ ctypes.windll.kernel32.LCIDToLocaleName(lcid, buf, 85, 0)
+ return buf.value
+
+
+@probe(id="lang.ui", level="L1", family="locale", tier="T0", collect="core")
+def lang_ui(h, facts):
+ """User and system UI language plus installed language packs: reply language."""
+ import ctypes
+ k32 = ctypes.windll.kernel32
+ user = _lcid_name(k32.GetUserDefaultUILanguage())
+ return {"present": True, "language": user, "user": user,
+ "system": _lcid_name(k32.GetSystemDefaultUILanguage()),
+ "packs": _subs(h, r"HKLM\SYSTEM\CurrentControlSet\Control\MUI\UILanguages")}
+
+
+@probe(id="lang.user_list", level="L1", family="locale", tier="T0", collect="core")
+def lang_user_list(h, facts):
+ """User language preference list (Control Panel\\International\\User Profile Languages)."""
+ langs = h.reg(_INTL + r"\User Profile", "Languages") or []
+ return {"present": bool(langs), "languages": list(langs)}
+
+
+@probe(id="locale.geo", level="L1", family="locale", tier="T0", collect="core")
+def locale_geo(h, facts):
+ """Home location (country) from Geo Name/Nation."""
+ name, nation = h.reg(_INTL + r"\Geo", "Name"), h.reg(_INTL + r"\Geo", "Nation")
+ return {"present": bool(name or nation), "name": name, "nation_id": nation}
+
+
+@probe(id="locale.system", level="L1", family="locale", tier="T0", collect="core")
+def locale_system(h, facts):
+ """System locale, install language and ANSI code page (UTF-8 beta flag)."""
+ nls = r"HKLM\SYSTEM\CurrentControlSet\Control\Nls"
+ acp = h.reg(nls + r"\CodePage", "ACP")
+ return {"present": True, "default": h.reg(nls + r"\Language", "Default"),
+ "install_language": h.reg(nls + r"\Language", "InstallLanguage"),
+ "acp": acp, "utf8": acp == "65001"}
+
+
+@probe(id="locale.user", level="L1", family="locale", tier="T0", collect="core")
+def locale_user(h, facts):
+ """User date/time/number/currency format for replies."""
+ v = _vals(_INTL) or {}
+ if not v:
+ return None
+ keep = ("LocaleName", "sShortDate", "sShortTime", "sTimeFormat", "iMeasure", "sCurrency", "iPaperSize", "iFirstDayOfWeek", "sDecimal")
+ d = {k: v.get(k) for k in keep if k in v}
+ t = v.get("sShortTime") or v.get("sTimeFormat") or ""
+ d["clock_24h"] = "H" in t
+ d["metric"] = v.get("iMeasure") == "0"
+ d["present"] = True
+ return d
+
+
+@probe(id="tz.auto", level="L1", family="locale", tier="T0", collect="core")
+def tz_auto(h, facts):
+ """Automatic time zone service and NTP server."""
+ start = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Services\tzautoupdate", "Start")
+ return {"present": True, "auto_tz": {2: True, 3: True, 4: False}.get(start), "tzautoupdate_start": start,
+ "ntp": h.reg(r"HKLM\SYSTEM\CurrentControlSet\Services\W32Time\Parameters", "NtpServer")}
+
+
+@probe(id="tz.zone", level="L1", family="locale", tier="T0", collect="core")
+def tz_zone(h, facts):
+ """Time zone key name and signed bias in minutes."""
+ k = r"HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation"
+ name = h.reg(k, "TimeZoneKeyName")
+ return {"present": bool(name), "zone": name, "bias_min": _s32(h.reg(k, "Bias")),
+ "active_bias_min": _s32(h.reg(k, "ActiveTimeBias"))}
+
+
+# ================================================================ shell_prefs
+
+@probe(id="pins.taskbar", level="L1", family="shell_prefs", tier="T0", collect="core")
+def pins_taskbar(h, facts):
+ """Taskbar .lnk pins (desktop apps the user pinned)."""
+ d = os.path.join(h.l0.get("appdata", ""), r"Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar")
+ names = sorted(n[:-4] for n in h.list_dir(d, 200) if n.lower().endswith(".lnk"))
+ return {"present": True, "pins": names, "count": len(names)}
+
+
+_EXPLORER = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer"
+
+
+@probe(id="shell.explorer_prefs", level="L1", family="shell_prefs", tier="T0", collect="core")
+def explorer_prefs(h, facts):
+ """Explorer/taskbar preferences: HideFileExt, Hidden, search box mode, auto-hide, widgets, dev toggles."""
+ adv = _vals(_EXPLORER + r"\Advanced") or {}
+ keep = ("HideFileExt", "Hidden", "ShowSuperHidden", "TaskbarAl", "TaskbarDa", "TaskbarMn", "ShowTaskViewButton",
+ "LaunchTo", "TaskbarEndTask", "ShowCopilotButton", "Start_IrisRecommendations")
+ d = {k: adv.get(k) for k in keep if k in adv}
+ d["SearchboxTaskbarMode"] = h.reg(r"HKCU\Software\Microsoft\Windows\CurrentVersion\Search", "SearchboxTaskbarMode")
+ sr = h.reg(_EXPLORER + r"\StuckRects3", "Settings")
+ if isinstance(sr, (bytes, bytearray)) and len(sr) > 12:
+ d["taskbar_autohide"] = bool(sr[8] & 0x01)
+ d["taskbar_edge"] = {0: "left", 1: "top", 2: "right", 3: "bottom"}.get(sr[12], sr[12])
+ d["classic_context_menu"] = _key_exists(r"HKCU\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32")
+ d["dev_mode"] = h.reg(r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock", "AllowDevelopmentWithoutDevLicense")
+ d["sudo"] = h.reg(r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Sudo", "Enabled")
+ d["long_paths"] = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\FileSystem", "LongPathsEnabled")
+ d["ps_execution_policy_cu"] = h.reg(r"HKCU\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell", "ExecutionPolicy")
+ d["ps_execution_policy_lm"] = h.reg(r"HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell", "ExecutionPolicy")
+ d["present"] = True
+ return d
+
+
+@probe(id="theme.dark", level="L1", family="shell_prefs", tier="T0", collect="core")
+def theme_dark(h, facts):
+ """Dark mode for apps and system, transparency."""
+ k = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"
+ a, s = h.reg(k, "AppsUseLightTheme"), h.reg(k, "SystemUsesLightTheme")
+ return {"present": True, "apps_dark": a == 0, "system_dark": s == 0, "transparency": h.reg(k, "EnableTransparency")}
+
+
+@probe(id="theme.spotlight_suggestions", level="L1", family="shell_prefs", tier="T0", collect="core")
+def spotlight_suggestions(h, facts):
+ """Spotlight / suggestions / silent app installs left on: weak untouched-defaults hint."""
+ cdm = _vals(r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager") or {}
+ return {"present": True, "lock_spotlight": cdm.get("RotatingLockScreenEnabled"),
+ "silent_installs": cdm.get("SilentInstalledAppsEnabled"),
+ "suggestions_on": sum(1 for k, v in cdm.items() if k.startswith("SubscribedContent-") and k.endswith("Enabled") and v == 1),
+ "system_pane_suggestions": cdm.get("SystemPaneSuggestionsEnabled")}
+
+
+@probe(id="theme.wallpaper", level="L1", family="shell_prefs", tier="T0", collect="core")
+def theme_wallpaper(h, facts):
+ """Wallpaper type only (solid/picture/slideshow/spotlight) and whether history holds stock or user images; never paths."""
+ wps = _vals(_EXPLORER + r"\Wallpapers") or {}
+ cur = h.reg(r"HKCU\Control Panel\Desktop", "WallPaper") or ""
+ bt = {0: "picture", 1: "solid_color", 2: "slideshow", 3: "spotlight"}.get(wps.get("BackgroundType"), wps.get("BackgroundType"))
+
+ def cls(p):
+ pl = (p or "").lower()
+ if not pl:
+ return "none"
+ if "\\windows\\web\\" in pl:
+ return "stock"
+ if "transcodedwallpaper" in pl:
+ return "user_copy"
+ return "user"
+ hist = [cls(wps.get(f"BackgroundHistoryPath{i}")) for i in range(5) if wps.get(f"BackgroundHistoryPath{i}")]
+ return {"present": True, "type": bt, "current": cls(cur), "history_stock": hist.count("stock"),
+ "history_user": sum(1 for x in hist if x.startswith("user"))}
+
+
+# ================================================================ security
+
+@probe(id="acct.autologon", level="L1", family="security", tier="T0", collect="core")
+def acct_autologon(h, facts):
+ """AutoAdminLogon flag and DefaultPassword presence (value never read)."""
+ k = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
+ return {"present": True, "auto_admin_logon": h.reg(k, "AutoAdminLogon"),
+ "default_password_present": _value_present(k, "DefaultPassword")}
+
+
+@probe(id="acct.hello", level="L1", family="security", tier="T0", collect="core")
+def acct_hello(h, facts):
+ """Windows Hello: NGC PIN credentials, WinBio enrolled factors, last sign-in credential provider."""
+ pins = len(_subs(h, _LOGONUI + r"\NgcPin\Credentials"))
+ factors = 0
+ wb = r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WinBio\AccountInfo"
+ for s in _subs(h, wb)[:20]:
+ factors |= int(h.reg(wb + "\\" + s, "EnrolledFactors") or 0)
+ lp = str(h.reg(_LOGONUI, "LastLoggedOnProvider") or "").upper()
+ return {"present": True, "pin_credentials": pins, "face": bool(factors & 0x2), "fingerprint": bool(factors & 0x8),
+ "last_provider": _CRED_PROVIDERS.get(lp, "other" if lp else None)}
+
+
+_CS = r"Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore"
+
+
+@probe(id="consent.store", level="L1", family="security", tier="T1", collect="core")
+def consent_store(h, facts):
+ """ConsentStore capability keys (HKCU + HKLM) and global allow state of the key capabilities."""
+ cu, lm = _subs(h, "HKCU\\" + _CS), _subs(h, "HKLM\\" + _CS)
+ if not cu and not lm:
+ return None
+ glob = {c: h.reg("HKLM\\" + _CS + "\\" + c, "Value") for c in ("webcam", "microphone", "location", "graphicsCaptureWithoutBorder", "passkeys")}
+ return {"present": True, "hkcu_capabilities": len(cu), "hklm_capabilities": len(lm), "machine_value": glob}
+
+
+def _consent_apps(h, root, cap):
+ base = root + "\\" + _CS + "\\" + cap
+ apps, noise = [], 0
+ for sub in _subs(h, base)[:400]:
+ if sub == "NonPackaged":
+ for s2 in _subs(h, base + r"\NonPackaged")[:400]:
+ path = s2.replace("#", "\\")
+ if _is_noise(path):
+ noise += 1
+ continue
+ v = _vals(base + r"\NonPackaged" + "\\" + s2) or {}
+ apps.append((os.path.basename(path), False, v))
+ else:
+ v = _vals(base + "\\" + sub) or {}
+ apps.append((sub.split("_")[0], True, v))
+ rows = {}
+ for name, packaged, v in apps:
+ start, stop = _ft_iso(v.get("LastUsedTimeStart")), _ft_iso(v.get("LastUsedTimeStop"))
+ key = name.lower()
+ r = {"app": name, "packaged": packaged, "value": v.get("Value"), "start": start, "stop": stop}
+ prev = rows.get(key)
+ if prev is None or (start or "") > (prev["start"] or ""):
+ rows[key] = r
+ return list(rows.values()), noise
+
+
+def _consent_summary(h, caps, hklm_top=False):
+ rows, noise = [], 0
+ for cap in caps:
+ r, n = _consent_apps(h, "HKCU", cap)
+ rows += r
+ noise += n
+ if not rows and not noise:
+ return None
+ merged = {}
+ for r in rows:
+ k = r["app"].lower()
+ if k not in merged or (r["start"] or "") > (merged[k]["start"] or ""):
+ merged[k] = r
+ rows = list(merged.values())
+ used = sorted((r for r in rows if r["start"]), key=lambda r: r["start"], reverse=True)
+ recent = []
+ for r in used[:8]:
+ d = _days_ago(r["start"])
+ sess = None
+ if r["stop"]:
+ sess = round((_dt.datetime.fromisoformat(r["stop"]) - _dt.datetime.fromisoformat(r["start"])).total_seconds(), 1)
+ recent.append({"app": r["app"], "days_ago": d, "last_session_s": sess, "in_use_now": not r["stop"]})
+ out = {"present": True, "apps": len(rows), "allow": sum(1 for r in rows if r["value"] == "Allow"),
+ "deny": sum(1 for r in rows if r["value"] == "Deny"), "ever_used": len(used),
+ "used_7d": sum(1 for r in used if _within(r["start"], 7)),
+ "used_30d": sum(1 for r in used if _within(r["start"], 30)),
+ "recent": recent, "operator_excluded": noise}
+ if hklm_top:
+ sysrows = []
+ for cap in caps:
+ r, _n = _consent_apps(h, "HKLM", cap)
+ sysrows += [x for x in r if x["start"]]
+ sysrows.sort(key=lambda r: r["start"], reverse=True)
+ out["system_recent"] = [{"app": r["app"], "days_ago": _days_ago(r["start"])} for r in sysrows[:4]]
+ return out
+
+
+@probe(id="consent.webcam", level="L2", family="security", tier="T1", collect="core", gate="consent.store")
+def consent_webcam(h, facts):
+ """Apps that used the camera (last session per app); HKLM system use (Hello face) listed separately."""
+ return _consent_summary(h, ["webcam"], hklm_top=True)
+
+
+@probe(id="consent.microphone", level="L2", family="security", tier="T1", collect="core", gate="consent.store")
+def consent_microphone(h, facts):
+ """Apps that used the microphone: voice chat, recording, streaming, agents."""
+ return _consent_summary(h, ["microphone"])
+
+
+@probe(id="consent.location", level="L2", family="security", tier="T1", collect="core", gate="consent.store")
+def consent_location(h, facts):
+ """Apps that read location; HKLM system readers listed separately."""
+ return _consent_summary(h, ["location"], hklm_top=True)
+
+
+@probe(id="consent.passkeys", level="L2", family="security", tier="T1", collect="core", gate="consent.store")
+def consent_passkeys(h, facts):
+ """Apps that used Windows passkeys."""
+ return _consent_summary(h, ["passkeys"])
+
+
+@probe(id="consent.screen_capture", level="L2", family="security", tier="T1", collect="core", gate="consent.store")
+def consent_screen_capture(h, facts):
+ """Apps that used border-less or programmatic screen capture (computer-use and capture tools)."""
+ return _consent_summary(h, ["graphicsCaptureWithoutBorder", "graphicsCaptureProgrammatic"])
+
+
+@probe(id="dev.ssh_dir_presence", level="L1", family="security", tier="T3", collect="core")
+def ssh_dir_presence(h, facts):
+ """~/.ssh file kinds by stat only (keys never opened); known_hosts line count, config Host count."""
+ d = os.path.join(h.l0.get("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": h.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}
+ kh = os.path.join(d, "known_hosts")
+ try:
+ with open(kh, "rb") as f:
+ out["known_hosts_lines"] = sum(1 for ln in f if ln.strip())
+ except OSError:
+ pass
+ try:
+ with open(os.path.join(d, "config"), encoding="utf-8", errors="replace") as f:
+ out["config_host_entries"] = sum(1 for ln in f if re.match(r"\s*Host\s+", ln, re.I))
+ except OSError:
+ pass
+ return out
+
+
+_PM_PATHS = {
+ "1Password": [r"%LOCALAPPDATA%\1Password", r"%ProgramFiles%\1Password"],
+ "Bitwarden": [r"%APPDATA%\Bitwarden", r"%LOCALAPPDATA%\Programs\Bitwarden"],
+ "KeePass": [r"%ProgramFiles%\KeePass Password Safe 2", r"%ProgramFiles(x86)%\KeePass Password Safe 2"],
+ "KeePassXC": [r"%ProgramFiles%\KeePassXC", r"%LOCALAPPDATA%\KeePassXC"],
+ "Proton Pass": [r"%LOCALAPPDATA%\Programs\ProtonPass", r"%LOCALAPPDATA%\Programs\Proton Pass"],
+ "Dashlane": [r"%LOCALAPPDATA%\Dashlane", r"%ProgramFiles%\Dashlane"],
+ "Enpass": [r"%ProgramFiles%\Enpass", r"%LOCALAPPDATA%\Programs\Enpass"],
+ "NordPass": [r"%LOCALAPPDATA%\Programs\nordpass", r"%ProgramFiles%\NordPass"],
+ "LastPass": [r"%ProgramFiles%\LastPass", r"%ProgramFiles(x86)%\LastPass"],
+ "RoboForm": [r"%ProgramFiles%\Siber Systems\AI RoboForm", r"%ProgramFiles(x86)%\Siber Systems\AI RoboForm"],
+ "Keeper": [r"%LOCALAPPDATA%\Programs\keeper-password-manager"],
+}
+
+
+@probe(id="pm.desktop", level="L1", family="security", tier="T0", collect="core")
+def pm_desktop(h, facts):
+ """Desktop password manager installs by directory presence (vaults never touched)."""
+ found = sorted(n for n, paths in _PM_PATHS.items() if any(h.exists(p) for p in paths))
+ return {"present": bool(found), "managers": found, "count": len(found)}
+
+
+@probe(id="security.defender_exclusions_count", level="L1", family="security", tier="T0", collect="core")
+def defender_exclusions_count(h, facts):
+ """Defender exclusion value counts per kind (admin token needed, else unknown); tamper registry value."""
+ base = r"HKLM\SOFTWARE\Microsoft\Windows Defender"
+ if not _key_exists(base):
+ return None
+ out = {"present": True}
+ for kind in ("Paths", "Processes", "Extensions", "IpAddresses"):
+ v = _vals(base + r"\Exclusions" + "\\" + kind)
+ out[kind.lower()] = len(v) if v is not None else "unknown"
+ out["tamper_protection_reg"] = h.reg(base + r"\Features", "TamperProtection")
+ out["disable_antispyware_policy"] = h.reg(r"HKLM\SOFTWARE\Policies\Microsoft\Windows Defender", "DisableAntiSpyware")
+ return out
+
+
+@probe(id="security.firewall", level="L1", family="security", tier="T0", collect="core")
+def security_firewall(h, facts):
+ """Firewall EnableFirewall per profile from registry (Get-NetFirewallProfile dropped: 7.4 s on ARM64)."""
+ base = r"HKLM\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy"
+ out = {}
+ for label, key in (("domain", "DomainProfile"), ("private", "StandardProfile"), ("public", "PublicProfile")):
+ v = h.reg(base + "\\" + key, "EnableFirewall")
+ out[label] = None if v is None else bool(v)
+ if all(v is None for v in out.values()):
+ return None
+ out["present"] = True
+ out["all_on"] = all(out[k] for k in ("domain", "private", "public"))
+ return out
+
+
+@probe(id="security.openssh_server", level="L1", family="security", tier="T3", collect="core")
+def openssh_server(h, facts):
+ """OpenSSH server: service start type, DefaultShell, non-secret sshd_config directives, admin keys file size only."""
+ start = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Services\sshd", "Start")
+ pd = os.environ.get("ProgramData", r"C:\ProgramData")
+ shell = h.reg(r"HKLM\SOFTWARE\OpenSSH", "DefaultShell")
+ directives = {}
+ try:
+ with open(os.path.join(pd, "ssh", "sshd_config"), encoding="utf-8", errors="replace") as f:
+ for i, line in enumerate(f):
+ if i > 2000:
+ break
+ 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"):
+ directives[k] = parts[1] if len(parts) > 1 else ""
+ elif k in ("allowusers", "allowgroups", "match"):
+ directives[k] = "<set>"
+ except OSError:
+ pass
+ aak = h.meta(os.path.join(pd, "ssh", "administrators_authorized_keys"))
+ return {"present": start is not None, "sshd_start": start, "sshd_auto": start == 2,
+ "ssh_agent_start": h.reg(r"HKLM\SYSTEM\CurrentControlSet\Services\ssh-agent", "Start"),
+ "default_shell": os.path.basename(shell) if shell else None, "sshd_config": directives,
+ "admin_authorized_keys_bytes": aak.get("bytes") if aak.get("present") else None}
+
+
+@probe(id="security.rdp", level="L1", family="security", tier="T0", collect="core")
+def security_rdp(h, facts):
+ """Remote Desktop accepting connections, NLA, port; client MRU count."""
+ ts = r"HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server"
+ deny = h.reg(ts, "fDenyTSConnections")
+ if deny is None:
+ return None
+ return {"present": True, "rdp_on": deny == 0, "nla": h.reg(ts + r"\WinStations\RDP-Tcp", "UserAuthentication"),
+ "port": h.reg(ts + r"\WinStations\RDP-Tcp", "PortNumber"),
+ "remote_assistance": h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\Remote Assistance", "fAllowToGetHelp"),
+ "client_mru": len(_vals(r"HKCU\Software\Microsoft\Terminal Server Client\Default") or {})}
+
+
+_TOOL_RX = {
+ "remote_access": re.compile(r"tailscale|anydesk|parsec|chrome remote desktop|teamviewer|rustdesk|sunshine|moonlight|realvnc|tightvnc|ultravnc|tigervnc|splashtop|hamachi|ngrok|cloudflared|nomachine|jump desktop|screenconnect|netbird", re.I),
+ "vpn": re.compile(r"wireguard|openvpn|nordvpn|proton ?vpn|mullvad|expressvpn|cisco (anyconnect|secure client)|globalprotect|forticlient|surfshark|windscribe|private internet access|cloudflare warp|cloudflare one|zerotier|pritunl|softether|tunnelbear|zscaler|netskope", re.I),
+ "virtualization": re.compile(r"virtualbox|vmware|qemu|docker desktop|podman|multipass|vagrant|sandboxie", re.I),
+}
+_SVC = {"Tailscale": "remote_access", "AnyDesk": "remote_access", "Parsec": "remote_access", "chromoting": "remote_access",
+ "TeamViewer": "remote_access", "RustDesk": "remote_access", "SunshineService": "remote_access",
+ "CloudflareWARP": "vpn", "WireGuardManager": "vpn", "OpenVPNService": "vpn", "ZeroTierOneService": "vpn",
+ "MullvadVPN": "vpn", "nordvpn-service": "vpn", "ProtonVPN Service": "vpn", "com.docker.service": "virtualization",
+ "vmms": "virtualization"}
+
+
+def _inventory(h):
+ if hasattr(h, "_hi_inv"):
+ return h._hi_inv
+ hits = {k: [] for k in _TOOL_RX}
+ seen, n = set(), 0
+ for root in (r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
+ r"HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall",
+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall"):
+ for s in _subs(h, root)[:1500]:
+ name = h.reg(root + "\\" + s, "DisplayName")
+ if not isinstance(name, str):
+ continue
+ n += 1
+ for cat, rx in _TOOL_RX.items():
+ if rx.search(name) and name not in seen:
+ seen.add(name)
+ hits[cat].append({"name": name, "version": h.reg(root + "\\" + s, "DisplayVersion"),
+ "install_date": h.reg(root + "\\" + s, "InstallDate")})
+ svcs = {}
+ for svc, cat in _SVC.items():
+ st = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Services" + "\\" + svc, "Start")
+ if st is not None:
+ svcs[svc] = {"category": cat, "start": st}
+ h._hi_inv = {"scanned": n, "hits": hits, "services": svcs}
+ return h._hi_inv
+
+
+@probe(id="security.remote_tools", level="L1", family="security", tier="T0", collect="core")
+def remote_tools(h, facts):
+ """Remote-access tools and virtualization from Uninstall keys + service keys (AnyDesk, Parsec, Tailscale, Sunshine, Docker...)."""
+ inv = _inventory(h)
+ svc = {k: v["start"] for k, v in inv["services"].items() if v["category"] in ("remote_access", "virtualization")}
+ return {"present": True, "uninstall_scanned": inv["scanned"], "remote_access": inv["hits"]["remote_access"],
+ "virtualization": inv["hits"]["virtualization"], "services": svc,
+ "tailscale_cli": h.exists(r"%ProgramFiles%\Tailscale\tailscale.exe")}
+
+
+@probe(id="security.secureboot", level="L1", family="security", tier="T0", collect="core")
+def secureboot(h, facts):
+ """UEFI Secure Boot state from registry."""
+ v = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\SecureBoot\State", "UEFISecureBootEnabled")
+ return {"present": v is not None, "secure_boot": bool(v) if v is not None else None}
+
+
+@probe(id="security.smartscreen", level="L1", family="security", tier="T0", collect="core")
+def smartscreen(h, facts):
+ """SmartScreen and Smart App Control state (absent SmartScreenEnabled = default on)."""
+ ex = h.reg(r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer", "SmartScreenEnabled")
+ pol = h.reg(r"HKLM\SOFTWARE\Policies\Microsoft\Windows\System", "EnableSmartScreen")
+ sac = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\CI\Policy", "VerifiedAndReputablePolicyState")
+ return {"present": True, "explorer": ex if ex is not None else "default_on", "policy": pol,
+ "edge_user": h.reg(r"HKCU\Software\Microsoft\Edge\SmartScreenEnabled", ""),
+ "smart_app_control": {0: "off", 1: "on", 2: "evaluation"}.get(sac, sac)}
+
+
+@probe(id="security.telemetry", level="L1", family="security", tier="T0", collect="core")
+def telemetry(h, facts):
+ """Diagnostic data level, advertising ID, tailored experiences: privacy-conscious toggles."""
+ return {"present": True,
+ "allow_telemetry": h.reg(r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection", "AllowTelemetry"),
+ "policy_allow_telemetry": h.reg(r"HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection", "AllowTelemetry"),
+ "diagtrack_start": h.reg(r"HKLM\SYSTEM\CurrentControlSet\Services\DiagTrack", "Start"),
+ "advertising_id": h.reg(r"HKCU\Software\Microsoft\Windows\CurrentVersion\AdvertisingInfo", "Enabled"),
+ "tailored_experiences": h.reg(r"HKCU\Software\Microsoft\Windows\CurrentVersion\Privacy", "TailoredExperiencesWithDiagnosticDataEnabled"),
+ "recall_disabled_policy": h.reg(r"HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsAI", "DisableAIDataAnalysis")}
+
+
+@probe(id="security.uac", level="L1", family="security", tier="T0", collect="core")
+def uac(h, facts):
+ """UAC slider level from EnableLUA, ConsentPromptBehaviorAdmin, PromptOnSecureDesktop."""
+ k = r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
+ lua, c, s = h.reg(k, "EnableLUA"), h.reg(k, "ConsentPromptBehaviorAdmin"), h.reg(k, "PromptOnSecureDesktop")
+ if lua == 0:
+ lvl = "off"
+ elif c == 2:
+ lvl = "4_always_notify"
+ elif c == 5 and s == 1:
+ lvl = "3_default"
+ elif c == 5 and s == 0:
+ lvl = "2_no_dim"
+ elif c == 0:
+ lvl = "1_never_notify"
+ else:
+ lvl = f"custom_c{c}_s{s}"
+ return {"present": lua is not None, "level": lvl, "enable_lua": lua, "consent_prompt_admin": c,
+ "secure_desktop": s, "filter_admin_token": h.reg(k, "FilterAdministratorToken")}
+
+
+@probe(id="acct.admins", level="L2", family="security", tier="T0", collect="extended", gate="security.uac")
+def acct_admins(h, facts):
+ """Administrators group member count by kind via NetLocalGroupGetMembers (no net.exe spawn); names never emitted."""
+ import ctypes
+ from ctypes import wintypes
+ adv, net = ctypes.WinDLL("advapi32"), ctypes.WinDLL("netapi32")
+ psid = ctypes.c_void_p()
+ if not adv.ConvertStringSidToSidW(ctypes.c_wchar_p("S-1-5-32-544"), ctypes.byref(psid)):
+ return None
+ name, dom = ctypes.create_unicode_buffer(256), ctypes.create_unicode_buffer(256)
+ cn, cd, use = wintypes.DWORD(256), wintypes.DWORD(256), wintypes.DWORD()
+ ok = adv.LookupAccountSidW(None, psid, name, ctypes.byref(cn), dom, ctypes.byref(cd), ctypes.byref(use))
+ ctypes.windll.kernel32.LocalFree(psid)
+ if not ok:
+ return None
+
+ class LGMI2(ctypes.Structure):
+ _fields_ = [("sid", ctypes.c_void_p), ("use", wintypes.DWORD), ("name", wintypes.LPWSTR)]
+ net.NetLocalGroupGetMembers.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p),
+ wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD),
+ ctypes.c_void_p]
+ buf = ctypes.c_void_p()
+ read, total = wintypes.DWORD(), wintypes.DWORD()
+ rc = net.NetLocalGroupGetMembers(None, name.value, 2, ctypes.byref(buf), 0xFFFFFFFF, ctypes.byref(read), ctypes.byref(total), None)
+ if rc != 0 or not buf:
+ return {"present": False, "error": rc}
+ me = _current_sid(h)
+ kinds = {"builtin_admin": 0, "current_user": 0, "local_other": 0, "group": 0, "domain_or_entra": 0}
+ try:
+ arr = ctypes.cast(buf, ctypes.POINTER(LGMI2 * read.value)).contents
+ for m in arr:
+ s = ctypes.c_wchar_p()
+ sid = ""
+ if adv.ConvertSidToStringSidW(ctypes.c_void_p(m.sid), ctypes.byref(s)):
+ sid = s.value or ""
+ ctypes.windll.kernel32.LocalFree(s)
+ if me and sid == me:
+ kinds["current_user"] += 1
+ elif sid.endswith("-500") and sid.startswith("S-1-5-21-"):
+ kinds["builtin_admin"] += 1
+ elif m.use in (2, 4): # SidTypeGroup, SidTypeAlias
+ kinds["group"] += 1
+ elif sid.startswith("S-1-12-1-") or (me and sid.startswith("S-1-5-21-") and sid.rsplit("-", 1)[0] != me.rsplit("-", 1)[0]):
+ kinds["domain_or_entra"] += 1
+ else:
+ kinds["local_other"] += 1
+ finally:
+ net.NetApiBufferFree(buf)
+ return {"present": True, "count": read.value, "kinds": kinds, "current_is_member": kinds["current_user"] > 0}
+
+
+@probe(id="security.bcdedit", level="L2", family="security", tier="T0", collect="extended", gate="security.uac", needs_admin=True)
+def bcdedit(h, facts):
+ """Boot flags: testsigning, hypervisorlaunchtype (Docker/WSL readiness), isolatedcontext. Admin only."""
+ out = _run_text(h, ["bcdedit", "/enum", "{current}"], 4000)
+ if not out:
+ return None
+ flags = {}
+ for line in out.splitlines():
+ m = re.match(r"^(testsigning|nointegritychecks|hypervisorlaunchtype|flightsigning|debug|bootdebug|isolatedcontext)\s+(\S+)", line.strip(), re.I)
+ if m:
+ flags[m.group(1).lower()] = m.group(2)
+ return {"present": True, "lines": len(out.splitlines()), **flags}
+
+
+_PS_AV = r"""
+try {
+ $av = @(Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntiVirusProduct -ErrorAction Stop | ForEach-Object {
+ $s = [int]$_.productState
+ [ordered]@{ name = $_.displayName; state = ('0x{0:X6}' -f $s); enabled = (($s -band 0x1000) -ne 0); up_to_date = (($s -band 0x10) -eq 0) } })
+ [ordered]@{ present = ($av.Count -gt 0); count = $av.Count; third_party = @($av | Where-Object { $_.name -notmatch 'Windows Defender|Microsoft Defender' }).Count; products = $av }
+} catch { [ordered]@{ present = $false; error = $_.Exception.GetType().Name } }
+"""
+ps_probe("security.av_products", _PS_AV, level="L2", family="security", tier="T0", collect="extended", gate="security.uac",
+ doc="Registered antivirus products (SecurityCenter2); third-party AV presence.")
+
+_PS_DEFENDER = r"""
+try {
+ $s = Get-MpComputerStatus -ErrorAction Stop
+ [ordered]@{ present = $true; rtp = $s.RealTimeProtectionEnabled; av = $s.AntivirusEnabled; mode = [string]$s.AMRunningMode;
+ tamper = $s.IsTamperProtected; sig_age_d = $s.AntivirusSignatureAge; quick_scan_age_d = $s.QuickScanAge;
+ full_scan_age_d = $(if ($s.FullScanAge -ge 4294967295) { 'never' } else { $s.FullScanAge }); smart_app_control = [string]$s.SmartAppControlState }
+} catch { [ordered]@{ present = $false; error = $_.Exception.GetType().Name } }
+"""
+ps_probe("security.defender_status_ps", _PS_DEFENDER, level="L2", family="security", tier="T0", collect="deep",
+ gate="security.defender_exclusions_count",
+ doc="Get-MpComputerStatus route (2-4 s on ARM64). Fallback and cross-check for security.defender_status.")
+
+_SAC_STATE = {0: "Off", 1: "On", 2: "Evaluation"}
+
+
+def _ft_bytes_days(b):
+ """Whole days since a FILETIME stored as REG_BINARY (Get-MpComputerStatus *Age semantics)."""
+ if not isinstance(b, (bytes, bytearray)) or len(b) < 8:
+ return None, None
+ iso = _ft_iso(int.from_bytes(b[:8], "little"))
+ d = _days_ago(iso)
+ return iso, (None if d is None else int(d))
+
+
+@probe(id="security.defender_status", level="L2", family="security", tier="T0", collect="core",
+ gate="security.defender_exclusions_count")
+def defender_status(h, facts):
+ """Defender real-time, tamper, signature and scan ages from the registry (same keys as the Get-MpComputerStatus route)."""
+ base = r"HKLM\SOFTWARE\Microsoft\Windows Defender"
+ pol = r"HKLM\SOFTWARE\Policies\Microsoft\Windows Defender"
+ running = h.reg(base, "IsServiceRunning")
+ if running is None:
+ return None
+ running = running == 1
+ rtm_off = 1 in (h.reg(base + r"\Real-Time Protection", "DisableRealtimeMonitoring"),
+ h.reg(pol + r"\Real-Time Protection", "DisableRealtimeMonitoring"))
+ av_off = 1 in (h.reg(base, "DisableAntiVirus"), h.reg(base, "DisableAntiSpyware"), h.reg(pol, "DisableAntiSpyware"))
+ passive = 1 in (h.reg(base, "PassiveMode"),
+ h.reg(r"HKLM\SOFTWARE\Policies\Microsoft\Windows Advanced Threat Protection", "ForceDefenderPassiveMode"))
+ tp = h.reg(base + r"\Features", "TamperProtection")
+ sig_iso, sig_age = _ft_bytes_days(h.reg(base + r"\Signature Updates", "AVSignatureApplied"))
+ scan_iso, scan_age = _ft_bytes_days(h.reg(base + r"\Scan", "LastScanRun"))
+ scan_type = h.reg(base + r"\Scan", "LastScanType")
+ sac = h.reg(r"HKLM\SYSTEM\CurrentControlSet\Control\CI\Policy", "VerifiedAndReputablePolicyState")
+ excl = {}
+ for kind in h.reg(base + r"\Exclusions") or []:
+ v = _vals(base + r"\Exclusions" + "\\" + kind)
+ excl[kind.lower()] = len(v) if v is not None else "unknown"
+ return {
+ "present": True,
+ "rtp": running and not av_off and not rtm_off,
+ "av": running and not av_off,
+ "mode": "Not running" if not running else ("Passive Mode" if passive else "Normal"),
+ "tamper": None if tp is None else bool(tp & 1),
+ "sig_age_d": sig_age,
+ # LastScanRun holds only the most recent scan; the other scan type's age is unknown, not "never".
+ "quick_scan_age_d": scan_age if scan_type == 1 else None,
+ "full_scan_age_d": scan_age if scan_type == 2 else None,
+ "smart_app_control": _SAC_STATE.get(sac),
+ "route": "registry",
+ "service_running": running,
+ "product_status": h.reg(base, "ProductStatus"),
+ "pua": h.reg(base, "PUAProtection"),
+ "maps": h.reg(base + r"\Spynet", "SpyNetReporting"),
+ "sig_version": h.reg(base + r"\Signature Updates", "AVSignatureVersion"),
+ "engine_version": h.reg(base + r"\Signature Updates", "EngineVersion"),
+ "sig_applied": sig_iso,
+ "last_scan": scan_iso,
+ "last_scan_type": {1: "quick", 2: "full", 3: "custom"}.get(scan_type, scan_type),
+ "exclusion_counts": excl,
+ }
+
+_PS_SERVICES = r"""
+$n = 'Tailscale','AnyDesk','Parsec','chromoting','TeamViewer','RustDesk','SunshineService','sshd','ssh-agent','TermService','WinRM','RemoteRegistry','WireGuardManager','OpenVPNService','CloudflareWARP','ZeroTierOneService','WinDefend','MpsSvc','wscsvc','vmms','com.docker.service','WbioSrvc','NgcSvc','BDESVC'
+$r = [ordered]@{}
+Get-Service -Name $n -ErrorAction SilentlyContinue | ForEach-Object { $r[$_.Name] = [string]$_.Status }
+[ordered]@{ present = ($r.Count -gt 0); running = @($r.Keys | Where-Object { $r[$_] -eq 'Running' }); stopped = @($r.Keys | Where-Object { $r[$_] -ne 'Running' }) }
+"""
+ps_probe("security.services_state", _PS_SERVICES, level="L2", family="security", tier="T0", collect="extended", gate="security.uac",
+ doc="Running state of remote-access, security and virtualization services (SCM).")
+
+_PS_VBS = r"""
+try {
+ $g = Get-CimInstance -Namespace root/Microsoft/Windows/DeviceGuard -ClassName Win32_DeviceGuard -ErrorAction Stop
+ $hv = (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity' -Name Enabled -ErrorAction SilentlyContinue).Enabled
+ [ordered]@{ present = $true; vbs_status = $g.VirtualizationBasedSecurityStatus; services_running = @($g.SecurityServicesRunning);
+ services_configured = @($g.SecurityServicesConfigured); hvci_reg = $hv }
+} catch { [ordered]@{ present = $false; error = $_.Exception.GetType().Name } }
+"""
+ps_probe("security.vbs_hvci", _PS_VBS, level="L2", family="security", tier="T0", collect="extended", gate="security.uac",
+ doc="VBS/HVCI runtime status (Win32_DeviceGuard) plus HVCI registry flag.")
+
+_PS_BITLOCKER = r"""
+try {
+ $v = @(Get-BitLockerVolume -ErrorAction Stop | ForEach-Object { [ordered]@{ mount = $_.MountPoint; type = [string]$_.VolumeType;
+ status = [string]$_.VolumeStatus; protection = [string]$_.ProtectionStatus; method = [string]$_.EncryptionMethod;
+ protectors = @($_.KeyProtector | ForEach-Object { [string]$_.KeyProtectorType }) } })
+ [ordered]@{ present = $true; volumes = $v }
+} catch { [ordered]@{ present = $false; error = $_.Exception.GetType().Name } }
+"""
+ps_probe("security.bitlocker", _PS_BITLOCKER, level="L2", family="security", tier="T0", collect="deep", gate="security.uac",
+ needs_admin=True, doc="BitLocker status per volume, protector types only. Admin only; non-admin = unknown.")
+
+_PS_CERTS = r"""
+$rx = 'mitmproxy|fiddler|charles|burp|portswigger|mkcert|development|testing|test only|zscaler|netskope|fortinet|umbrella|kaspersky|avast|eset|bitdefender'
+$cu = @(Get-ChildItem Cert:\CurrentUser\Root); $lm = @(Get-ChildItem Cert:\LocalMachine\Root)
+[ordered]@{ present = $true; cu_roots = $cu.Count; lm_roots = $lm.Count;
+ flagged = @(($cu + $lm) | Where-Object { $_.Subject -match $rx } | ForEach-Object { $_.Subject -replace '^.*?CN=([^,]+).*$', '$1' } | Select-Object -Unique -First 10) }
+"""
+ps_probe("security.cert_roots", _PS_CERTS, level="L2", family="security", tier="T0", collect="deep", gate="security.uac",
+ doc="Root store counts; flags interception/test/dev roots by CN.")
+
+_PS_DEFPREFS = r"""
+try {
+ $p = Get-MpPreference -ErrorAction Stop
+ $rx = [regex]::Escape($env:USERPROFILE)
+ $noise = '(^|\\)(hn-e2e|ns960|ns923[^\\]*|lhm|shots|user-insights-lab|hermes-[^\\]*)(\\|$)'
+ $paths = @($p.ExclusionPath | Where-Object { $_ } | ForEach-Object { $_ -replace $rx, '%USERPROFILE%' })
+ [ordered]@{ present = $true; exclusion_paths = @($paths | Where-Object { $_ -notmatch $noise });
+ operator_excluded = @($paths | Where-Object { $_ -match $noise }).Count;
+ exclusion_processes = @($p.ExclusionProcess | Where-Object { $_ }).Count; exclusion_extensions = @($p.ExclusionExtension | Where-Object { $_ });
+ pua = $p.PUAProtection; maps = $p.MAPSReporting; cfa = $p.EnableControlledFolderAccess; network_protection = $p.EnableNetworkProtection }
+} catch { [ordered]@{ present = $false; error = $_.Exception.GetType().Name } }
+"""
+ps_probe("security.defender_prefs", _PS_DEFPREFS, level="L2", family="security", tier="T2", collect="deep",
+ gate="security.defender_exclusions_count", doc="Defender preferences; exclusion paths are T2 (reveal game drives, lab dirs).")
+
+_PS_TPM = r"""
+try {
+ $t = Get-Tpm -ErrorAction Stop
+ $w = Get-CimInstance -Namespace root/cimv2/Security/MicrosoftTpm -ClassName Win32_Tpm -ErrorAction SilentlyContinue
+ [ordered]@{ present = [bool]$t.TpmPresent; ready = [bool]$t.TpmReady; manufacturer = ([string]$t.ManufacturerIdTxt).Trim([char]0, ' '); spec = [string]$w.SpecVersion }
+} catch { [ordered]@{ present = $false; error = $_.Exception.GetType().Name } }
+"""
+ps_probe("security.tpm", _PS_TPM, level="L2", family="security", tier="T0", collect="deep", gate="security.uac",
+ needs_admin=True, doc="TPM presence/readiness and spec version.")
+
+
+# ================================================================ network
+
+@probe(id="net.hosts_proxy", level="L1", family="network", tier="T0", collect="core")
+def hosts_proxy(h, facts):
+ """hosts file active-entry counts (block/loopback) and user proxy flags; entries never emitted."""
+ hp = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "drivers", "etc", "hosts")
+ n = blk = loop = 0
+ try:
+ with open(hp, encoding="utf-8", errors="replace") as f:
+ for i, ln in enumerate(f):
+ if i > 200000:
+ break
+ s = ln.split("#", 1)[0].strip()
+ if not s:
+ continue
+ n += 1
+ ip = s.split()[0]
+ if ip in ("0.0.0.0", "::"):
+ blk += 1
+ elif ip.startswith("127.") or ip == "::1":
+ loop += 1
+ except OSError:
+ return None
+ isk = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
+ ps = h.reg(isk, "ProxyServer")
+ return {"present": True, "hosts_entries": n, "hosts_block": blk, "hosts_loopback": loop,
+ "hosts_blocklist": blk >= 100, "proxy_enable": h.reg(isk, "ProxyEnable"),
+ "proxy_kind": None if not ps else ("loopback" if re.search(r"127\.0\.0\.1|localhost", ps) else "remote"),
+ "pac": h.reg(isk, "AutoConfigURL") is not None}
+
+
+_VPN_DIRS = {"Tailscale": r"%ProgramFiles%\Tailscale", "Cloudflare WARP": r"%ProgramFiles%\Cloudflare\Cloudflare WARP",
+ "WireGuard": r"%ProgramFiles%\WireGuard", "OpenVPN": r"%ProgramFiles%\OpenVPN",
+ "OpenVPN Connect": r"%ProgramFiles%\OpenVPN Connect", "ZeroTier": r"%ProgramData%\ZeroTier",
+ "Mullvad": r"%ProgramFiles%\Mullvad VPN", "ProtonVPN": r"%ProgramFiles%\Proton\VPN"}
+
+
+@probe(id="net.vpn_clients", level="L1", family="network", tier="T0", collect="core")
+def vpn_clients(h, facts):
+ """VPN/mesh clients (Tailscale, WARP, WireGuard, OpenVPN, ZeroTier...) by install dir, Uninstall and service keys."""
+ inv = _inventory(h)
+ dirs = sorted(k for k, p in _VPN_DIRS.items() if h.exists(p))
+ svc = {k: v["start"] for k, v in inv["services"].items() if v["category"] == "vpn" or k == "Tailscale"}
+ return {"present": True, "dirs": dirs, "uninstall": inv["hits"]["vpn"], "services": svc,
+ "count": len(set(dirs) | {x["name"] for x in inv["hits"]["vpn"]})}
+
+
+@probe(id="net.wifi_profiles", level="L1", family="network", tier="T0", collect="core")
+def wifi_profiles(h, facts):
+ """Saved Wi-Fi profile count from Wlansvc XML file count per interface; files never opened, SSIDs never read."""
+ base = os.path.join(os.environ.get("ProgramData", r"C:\ProgramData"), r"Microsoft\Wlansvc\Profiles\Interfaces")
+ ifs = h.list_dir(base, 50)
+ if not ifs:
+ return {"present": h.exists(base), "profiles": 0, "interfaces": 0, "readable": h.exists(base)}
+ per = [sum(1 for n in h.list_dir(os.path.join(base, i), 500) if n.lower().endswith(".xml")) for i in ifs]
+ return {"present": True, "count": sum(per), "interfaces": len(ifs), "profiles_max_per_interface": max(per)}
+
+
+_NET_CLASS = r"HKLM\SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}"
+_NET_CONN = r"HKLM\SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}"
+
+
+def _adapter_kind(desc: str, iftype):
+ d = desc.lower()
+ if "tailscale" in d or "wireguard" in d or "tap-" in d or "wintun" in d or "warp" in d or "zerotier" in d:
+ return "tunnel"
+ if "hyper-v" in d or "virtual" in d or "vmware" in d or "virtualbox" in d or "vethernet" in d:
+ return "virtual"
+ if "bluetooth" in d:
+ return "bluetooth"
+ if iftype == 71 or "wi-fi" in d or "wireless" in d or "wlan" in d or "802.11" in d:
+ return "wifi"
+ if iftype == 6 or "ethernet" in d or "gbe" in d or "lan" in d:
+ return "ethernet"
+ if iftype == 243 or "mobile" in d or "wwan" in d:
+ return "mobile"
+ return "other"
+
+
+@probe(id="net.adapters", level="L2", family="network", tier="T0", collect="extended", gate="net.hosts_proxy")
+def net_adapters(h, facts):
+ """Network adapters from the Network class registry (Get-NetAdapter is 4.6 s on ARM64); hidden/miniport adapters skipped."""
+ rows = []
+ for s in _subs(h, _NET_CLASS)[:200]:
+ if not s.isdigit():
+ continue
+ v = _vals(_NET_CLASS + "\\" + s) or {}
+ ch = v.get("Characteristics") or 0
+ guid = v.get("NetCfgInstanceId")
+ desc = v.get("DriverDesc") or ""
+ if not guid or ch & 0x8 or re.search(r"WAN Miniport|Kernel Debug|Teredo|6to4|IP-HTTPS|ISATAP|Microsoft Wi-Fi Direct|RAS Async", desc, re.I):
+ continue
+ name = h.reg(_NET_CONN + "\\" + guid + r"\Connection", "Name")
+ ift = v.get("*IfType")
+ try:
+ ift = int(ift) if ift is not None else None
+ except (TypeError, ValueError):
+ ift = None
+ tcp = r"HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces" + "\\" + guid.lower()
+ ip = h.reg(tcp, "DhcpIPAddress") or h.reg(tcp, "IPAddress")
+ if isinstance(ip, list):
+ ip = ip[0] if ip else None
+ has_ip = bool(ip) and ip not in ("0.0.0.0",)
+ rows.append({"name": name, "desc": desc, "kind": _adapter_kind(desc, ift), "physical": bool(ch & 0x4),
+ "has_ipv4": has_ip})
+ if not rows:
+ return None
+ kinds = {}
+ for r in rows:
+ kinds[r["kind"]] = kinds.get(r["kind"], 0) + 1
+ return {"present": True, "count": len(rows), "by_kind": kinds, "adapters": rows[:20]}
+
+
+@probe(id="net.connection_profiles", level="L2", family="network", tier="T0", collect="extended", gate="net.hosts_proxy")
+def connection_profiles(h, facts):
+ """Network category (public/private/domain) by network type from NetworkList (Get-NetConnectionProfile is 0.9 s on ARM64); no names."""
+ rows = _network_profiles(h)
+ if not rows:
+ return None
+ grid = {}
+ for r in rows:
+ grid.setdefault(r["type"], {}).setdefault(r["category"], 0)
+ grid[r["type"]][r["category"]] += 1
+ newest = sorted((r for r in rows if r["last"]), key=lambda r: r["last"], reverse=True)[:3]
+ return {"present": True, "by_type_category": grid,
+ "private_physical": sum(1 for r in rows if r["category"] == "private" and r["type"] in ("wireless", "wired")),
+ "most_recent": [{"type": r["type"], "category": r["category"], "last": r["last"]} for r in newest]}
+
+
+_DNS_KNOWN = {"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", "149.112.112.112": "quad9", "208.67.222.222": "opendns", "208.67.220.220": "opendns",
+ "100.100.100.100": "tailscale_magicdns", "94.140.14.14": "adguard", "94.140.15.15": "adguard",
+ "45.90.28.0": "nextdns", "45.90.30.0": "nextdns", "76.76.2.0": "controld", "76.76.10.0": "controld"}
+
+
+def _dns_class(ip: str) -> str:
+ if ip in _DNS_KNOWN:
+ return _DNS_KNOWN[ip]
+ if re.match(r"^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|fe80|fec0|fd)", ip, re.I):
+ return "private_lan"
+ if ip.startswith("127.") or ip == "::1":
+ return "loopback"
+ if ip.startswith("100.") and 64 <= int(ip.split(".")[1]) <= 127:
+ return "cgnat_or_tailnet"
+ return "other_public"
+
+
+@probe(id="net.dns", level="L2", family="network", tier="T0", collect="extended", gate="net.hosts_proxy")
+def net_dns(h, facts):
+ """DNS resolver classes per interface from Tcpip Interfaces registry (raw IPs never emitted) plus DoH table size."""
+ base = r"HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces"
+ classes, static = {}, 0
+ n_if = 0
+ for g in _subs(h, base)[:100]:
+ ns = h.reg(base + "\\" + g, "NameServer") or ""
+ dhcp = h.reg(base + "\\" + g, "DhcpNameServer") or ""
+ servers = [x for x in re.split(r"[ ,]+", ns or dhcp) if x]
+ if not servers:
+ continue
+ n_if += 1
+ static += 1 if ns else 0
+ for ip in servers:
+ c = _dns_class(ip)
+ classes[c] = classes.get(c, 0) + 1
+ doh = len(_subs(h, r"HKLM\SYSTEM\CurrentControlSet\Services\Dnscache\Parameters\DohWellKnownServers"))
+ return {"present": bool(n_if), "interfaces_with_dns": n_if, "static_dns_interfaces": static,
+ "resolver_classes": classes, "doh_known_servers": doh,
+ "custom_resolver": any(c not in ("private_lan", "other_public", "loopback") for c in classes)}
+
+
+@probe(id="net.tailscale", level="L2", family="network", tier="T1", collect="extended", gate="net.vpn_clients")
+def net_tailscale(h, facts):
+ """Tailscale state via 'tailscale status --json': peer counts by OS and online count; peer names never emitted."""
+ import json
+ exe = h.expand(r"%ProgramFiles%\Tailscale\tailscale.exe")
+ if not os.path.exists(exe):
+ return None
+ out = _run_text(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 = {}
+ for p in peers:
+ o = p.get("OS") or "?"
+ by_os[o] = by_os.get(o, 0) + 1
+ 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": by_os,
+ "exit_node_in_use": any(p.get("ExitNode") for p in peers),
+ "magicdns": bool((j.get("CurrentTailnet") or {}).get("MagicDNSEnabled"))}
+
+
+# ================================================================ usage (L3 rule as a probe)
+
+_KP41_Q = "*[System[Provider[@Name='Microsoft-Windows-Kernel-Power'] and (EventID=41)]]"
+
+
+def _kp41_events(h):
+ import xml.etree.ElementTree as ET
+ out = _run_text(h, ["wevtutil", "qe", "System", "/q:" + _KP41_Q, "/c:500", "/rd:true", "/f:xml"], 8000)
+ if out is None:
+ return None
+ txt = out.strip()
+ if not txt:
+ return []
+ ns = {"e": "http://schemas.microsoft.com/win/2004/08/events/event"}
+ try:
+ root = ET.fromstring("<r>" + txt + "</r>")
+ except ET.ParseError:
+ return None
+ rows = []
+ for ev in root.findall("e:Event", ns):
+ tc = ev.find("e:System/e:TimeCreated", ns)
+ data = {d.get("Name"): (d.text or "") for d in ev.findall("e:EventData/e:Data", ns)}
+ rows.append({"time": (tc.get("SystemTime") if tc is not None else "")[:19],
+ "bugcheck": int(data.get("BugcheckCode") or 0),
+ "button": int(data.get("PowerButtonTimestamp") or 0)})
+ return rows
+
+
+@probe(id="l3.power_event_split", level="L2", family="usage", tier="T1", collect="extended", gate="os.build")
+def power_event_split(h, facts):
+ """Kernel-Power 41 split per event: crash (BugcheckCode!=0), button_held (PowerButtonTimestamp!=0), else power_removed.
+ Only crash is a health signal; power_removed is a power-off habit (wall/PSU switch or outage). Never flag by count."""
+ rows, via = None, "wevtutil"
+ rec = facts.get("eventlog.power_history")
+ ph = rec.get("value") if isinstance(rec, dict) and rec.get("status") == "ok" else None
+ if isinstance(ph, dict) and isinstance(ph.get("kp41"), list) and isinstance(ph.get("kp41_split"), dict):
+ total = sum(int(v or 0) for v in ph["kp41_split"].values())
+ if total == len(ph["kp41"]):
+ rows = []
+ for e in ph["kp41"]:
+ bc = str(e.get("bugcheck") or "0")
+ rows.append({"time": str(e.get("t") or "")[:19], "bugcheck": int(bc, 16) if bc.lower().startswith("0x") else int(bc or 0),
+ "button": 1 if e.get("class") == "button_held" else 0})
+ via = "eventlog.power_history"
+ if rows is None:
+ rows = _kp41_events(h)
+ if rows is None:
+ return None
+ counts = {"crash": 0, "button_held": 0, "power_removed": 0}
+ last30 = {"crash": 0, "button_held": 0, "power_removed": 0}
+ codes, events = {}, []
+ for r in rows:
+ cls = "crash" if r["bugcheck"] else ("button_held" if r["button"] else "power_removed")
+ counts[cls] += 1
+ d = _days_ago(r["time"]) if r["time"] else None
+ if d is not None and d <= 30:
+ last30[cls] += 1
+ if r["bugcheck"]:
+ codes[hex(r["bugcheck"])] = codes.get(hex(r["bugcheck"]), 0) + 1
+ events.append({"date": r["time"][:10], "class": cls, "bugcheck": hex(r["bugcheck"]) if r["bugcheck"] else None})
+ return {"present": True, "via": via, "events": len(rows), **counts,
+ "crash_30d": last30["crash"], "button_held_30d": last30["button_held"], "power_removed_30d": last30["power_removed"],
+ "bugcheck_codes": codes, "health_flag_crash_30d": last30["crash"] > 0,
+ "power_off_habit_hint": counts["power_removed"] >= 3, "timeline": events[:60]}
diff --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.py
new file mode 100644
index 00000000000..eb2b6a52b4a
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_apps.py
@@ -0,0 +1,2332 @@
+"""Linux user-level probes: apps, ai_agents, dev, browser, comms_work, files, gaming, media.
+
+Registration only at import time. Signal ids match the Windows modules wherever Linux has a source, so
+derive.py rules fire unchanged. Where a Windows extractor is path-agnostic (Claude/Codex JSONL scans,
+Chromium History SQL, Steam VDF parsing, known-folder composition) this module primes the shared cache
+of that extractor with Linux paths and calls it, instead of copying it.
+
+Scope is the invoking user's home plus world-readable system inventories (dpkg status, apt/dpkg logs,
+.desktop files, /opt). Another account's home is never read. Docker is queried through the CLI with
+`ps` and `images` only.
+"""
+from __future__ import annotations
+
+import collections
+import configparser
+import datetime as dt
+import glob
+import gzip
+import json
+import os
+import re
+import shutil
+import subprocess
+import 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
+
+LX = "linux"
+APPS, AI, DEV, BROWSER, COMMS, FILES, GAMING, MEDIA = (
+ "apps", "ai_agents", "dev", "browser", "comms_work", "files", "gaming", "media")
+
+
+# ------------------------------------------------------------------ registration helpers
+
+def _taken(id):
+ return any(q.id == id and q.os in (LX, "any") for q in REGISTRY.values())
+
+
+def _lp(id, **kw):
+ """Register a Linux probe unless another module already registered this id for Linux."""
+ kw.setdefault("os", LX)
+ if _taken(id):
+ return lambda fn: fn
+ return probe(id, **kw)
+
+
+def _win_meta(id):
+ return next((q for q in REGISTRY.values() if q.id == id and q.os == "windows"), None)
+
+
+def _mirror(id, fn, prime=None, **override):
+ """Register a Linux probe that primes a shared cache with Linux paths, then runs the Windows extractor fn.
+ Level/family/tier/collect/gate/timeout default to the Windows registration of the same id."""
+ w = _win_meta(id)
+ meta = {"level": w.level, "family": w.family, "tier": w.tier, "collect": w.collect, "gate": w.gate,
+ "timeout_ms": w.timeout_ms} if w else {}
+ meta.update(override)
+
+ def run(h, facts):
+ if prime:
+ prime(h)
+ return fn(h, facts)
+ run.__name__ = getattr(fn, "__name__", id.replace(".", "_"))
+ run.__doc__ = (fn.__doc__ or "").strip() + " [Linux: shared extractor over Linux paths]"
+ _lp(id, **meta)(run)
+
+
+# ------------------------------------------------------------------ paths and small helpers
+
+def _U(h):
+ return ad._U(h) if h is not None else os.path.expanduser("~")
+
+
+def _cfg(h, *p):
+ return os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.join(_U(h), ".config"), *p)
+
+
+def _data(h, *p):
+ return os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(_U(h), ".local", "share"), *p)
+
+
+def _cachedir(h, *p):
+ return os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.join(_U(h), ".cache"), *p)
+
+
+def _state(h, *p):
+ return os.path.join(os.environ.get("XDG_STATE_HOME") or os.path.join(_U(h), ".local", "state"), *p)
+
+
+def _flat(h, appid, *p):
+ return os.path.join(_U(h), ".var", "app", appid, *p)
+
+
+def _snapu(h, name, *p):
+ return os.path.join(_U(h), "snap", name, *p)
+
+
+_isdir, _ls, _mtime, _iso, _top, _read_json = ad._isdir, ad._ls, ad._mtime, ad._iso, ad._top, ad._read_json
+
+
+def _ex(*paths):
+ return any(p and os.path.exists(p) for p in paths)
+
+
+def _first(*paths):
+ return next((p for p in paths if p and os.path.exists(p)), None)
+
+
+def _newest_mtime(paths):
+ best = 0
+ for p in paths:
+ try:
+ best = max(best, os.stat(p).st_mtime)
+ except OSError:
+ continue
+ return best or None
+
+
+def _day(ts):
+ try:
+ return dt.datetime.fromtimestamp(ts).strftime("%Y-%m-%d") if ts else None
+ except (OSError, ValueError, OverflowError):
+ return None
+
+
+def _memo(h, name, fn):
+ return ad._memo(h, "lx:" + name, fn)
+
+
+def _extra_bins_static():
+ return [d for d in _extra_bins(None) if os.path.isdir(d)]
+
+
+def _extra_bins(h):
+ U = _U(h) if h is not None else os.path.expanduser("~")
+ return [os.path.join(U, ".local", "bin"), os.path.join(U, "bin"), os.path.join(U, ".bun", "bin"),
+ os.path.join(U, ".cargo", "bin"), os.path.join(U, "go", "bin"), os.path.join(U, ".deno", "bin"),
+ os.path.join(U, ".npm-global", "bin"), _data(h, "pnpm"), os.path.join(U, ".volta", "bin"),
+ _data(h, "fnm", "aliases", "default", "bin"), os.path.join(U, ".hermes", "bin"),
+ os.path.join(U, ".nix-profile", "bin"), "/usr/local/go/bin", "/snap/bin", "/var/lib/flatpak/exports/bin",
+ _data(h, "flatpak", "exports", "bin"), "/home/linuxbrew/.linuxbrew/bin"]
+
+
+def _fact(facts, id):
+ """Value of an earlier probe. The runner passes its record dicts ({'value': ...}); accept bare values too."""
+ f = facts.get(id)
+ if isinstance(f, dict) and "status" in f and "value" in f:
+ return f["value"] if f.get("status") == "ok" else None
+ return f
+
+
+def _which(h, name):
+ """shutil.which over PATH, then the user's tool dirs (a non-login ssh shell often lacks ~/.local/bin)."""
+ p = shutil.which(name)
+ if p:
+ return p
+ for d in _extra_bins(h):
+ c = os.path.join(d, name)
+ if os.path.isfile(c) and os.access(c, os.X_OK):
+ return c
+ return None
+
+
+_SPAWN_PATH = None
+
+
+def _spawn(args, timeout=5.0):
+ """(rc, stdout, ms) with stdin closed; stderr dropped. PATH gains the user's tool dirs so #!/usr/bin/env node
+ shims (npm, pnpm) resolve their interpreter."""
+ t = time.perf_counter()
+ try:
+ path = os.environ.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"))
+ 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)
+
+
+def _open_text(p, maxb=30_000_000):
+ """Read a text file (plain or .gz). None on failure or when larger than maxb."""
+ try:
+ if os.path.getsize(p) > maxb:
+ return None
+ if p.endswith(".gz"):
+ with gzip.open(p, "rt", encoding="utf-8", errors="replace") as f:
+ return f.read(maxb * 4)
+ with open(p, encoding="utf-8", errors="replace") as f:
+ return f.read()
+ except OSError:
+ return None
+
+
+_OP_TOP = re.compile(r"^(hn-e2e|ns960|ns923.*|lhm|shots|uil|user-insights-lab|userscan.*|\.?hermes-(?!agent$).+)$", re.I)
+_OP_DEEP = re.compile(r"(^|/)(user-insights-lab|userscan[^/]*|hn-e2e|ns960|ns923[^/]*)(/|$)", re.I)
+
+
+def _is_op(h, path):
+ """Operator (lab) noise: side homes and lab dirs directly under home, or lab dir names at any depth."""
+ U = _U(h).rstrip("/") + "/"
+ p = os.path.abspath(path)
+ if _OP_DEEP.search(p):
+ return True
+ if p.startswith(U):
+ first = p[len(U):].split("/", 1)[0]
+ return bool(first and _OP_TOP.match(first))
+ return False
+
+
+def _age_bucket(age_s):
+ return bf._age_bucket(age_s)
+
+
+# ------------------------------------------------------------------ own-user process table
+
+_SAFE_NAME = re.compile(r"^[\w.@+\-]{1,40}$")
+
+
+def _procs(h):
+ """Counter of process names for the invoking uid (argv0 basename; for interpreters also argv1 basename),
+ plus the total process count across all users (a count, no names)."""
+ def build():
+ me = os.getuid()
+ names, total = collections.Counter(), 0
+ for pid in os.listdir("/proc"):
+ if not pid.isdigit():
+ continue
+ total += 1
+ try:
+ if os.stat(f"/proc/{pid}").st_uid != me:
+ continue
+ with open(f"/proc/{pid}/cmdline", "rb") as f:
+ argv = f.read(4096).split(b"\0")
+ with open(f"/proc/{pid}/comm", encoding="utf-8", errors="replace") as f:
+ comm = f.read().strip()
+ except OSError:
+ continue
+ a0 = os.path.basename(argv[0].decode("utf-8", "replace")) if argv and argv[0] else comm
+ a0 = a0.split(" ")[0] or comm
+ n = a0 if _SAFE_NAME.match(a0) else comm
+ if re.match(r"^(python[\d.]*|node|bun|deno|uv|npx|bunx)$", n) and len(argv) > 1 and argv[1]:
+ a1 = os.path.basename(argv[1].decode("utf-8", "replace"))
+ if _SAFE_NAME.match(a1) and not a1.startswith("-"):
+ n = f"{n}:{a1}"
+ names[n] += 1
+ return {"names": names, "total_all_users": total}
+ return _memo(h, "procs", build)
+
+
+def _running(h, pattern):
+ rx = re.compile(pattern, re.I)
+ return {k: v for k, v in _procs(h)["names"].items() if rx.search(k)}
+
+
+# ================================================================== apps
+
+def _parse_deb822(text):
+ for block in text.split("\n\n"):
+ d, last = {}, None
+ for line in block.splitlines():
+ if not line:
+ continue
+ if line[0] in " \t":
+ continue
+ k, _, v = line.partition(":")
+ d[k] = v.strip()
+ last = k
+ if d:
+ yield d
+
+
+def _os_install_date():
+ for p in ("/var/log/installer", "/lost+found", "/etc/machine-id"):
+ try:
+ return _day(os.stat(p).st_mtime)
+ except OSError:
+ continue
+ return None
+
+
+def _dpkg(h):
+ """dpkg status + apt extended_states + dpkg.log* + apt history.log*. No spawn (replaces dpkg -l and
+ apt list --installed / apt-mark showmanual, which cost 0.3-1.5 s)."""
+ def build():
+ txt = _open_text("/var/lib/dpkg/status", 60_000_000)
+ if txt is None:
+ return None
+ pkgs = {}
+ for d in _parse_deb822(txt):
+ if "install ok installed" not in d.get("Status", ""):
+ continue
+ pkgs[d.get("Package")] = {"section": d.get("Section", ""), "arch": d.get("Architecture", ""),
+ "kb": int(d.get("Installed-Size", "0") or 0), "priority": d.get("Priority", "")}
+ auto = set()
+ es = _open_text("/var/lib/apt/extended_states")
+ for d in _parse_deb822(es or ""):
+ if d.get("Auto-Installed") == "1":
+ auto.add(d.get("Package"))
+ first_inst, months = {}, collections.Counter()
+ oldest_log = None
+ for f in sorted(glob.glob("/var/log/dpkg.log*"))[:30]:
+ t = _open_text(f)
+ if not t:
+ continue
+ for m in re.finditer(r"^(\d{4}-\d\d-\d\d) [\d:]+ install (\S+?)(?::\S+)? ", t, re.M):
+ d, p = m.group(1), m.group(2)
+ oldest_log = d if oldest_log is None or d < oldest_log else oldest_log
+ months[d[:7]] += 1
+ if p not in first_inst or d < first_inst[p]:
+ first_inst[p] = d
+ requested = []
+ me = os.getuid()
+ os_inst = _os_install_date()
+ for f in sorted(glob.glob("/var/log/apt/history.log*"))[:30]:
+ t = _open_text(f)
+ if not t:
+ continue
+ for block in t.split("\n\n"):
+ sd = re.search(r"^Start-Date: (\d{4}-\d\d-\d\d)", block, re.M)
+ cl = re.search(r"^Commandline: (.+)$", block, re.M)
+ if not (sd and cl):
+ continue
+ toks = cl.group(1).split()
+ if "install" not in toks or "--reinstall" in toks or re.search(r"unattended|packagekit|aptdaemon", toks[0]):
+ continue
+ rb = re.search(r"^Requested-By: .*\((\d+)\)", block, re.M)
+ # image build and installer runs have no Requested-By and predate the install day
+ if not rb and (not os_inst or sd.group(1) <= os_inst):
+ continue
+ by_me = bool(rb and int(rb.group(1)) == me)
+ for tok in toks[toks.index("install") + 1:]:
+ if tok.startswith("-"):
+ continue
+ if "/" in tok:
+ if not tok.endswith(".deb"):
+ continue
+ tok = os.path.basename(tok).split("_")[0]
+ name = re.split(r"[=:]", tok)[0]
+ if name:
+ requested.append((name, sd.group(1), by_me))
+ return {"pkgs": pkgs, "auto": auto, "first_install": first_inst, "install_months": months,
+ "oldest_log": oldest_log, "requested": requested, "os_install": os_inst}
+ return _memo(h, "dpkg", build)
+
+
+_DESKTOP_DIRS = [("system", "/usr/share/applications"), ("local", "/usr/local/share/applications"),
+ ("snap", "/var/lib/snapd/desktop/applications"),
+ ("flatpak", "/var/lib/flatpak/exports/share/applications")]
+_CAT_MAP = [("gaming", r"\bGame\b"), ("dev", r"\bDevelopment\b|IDE|TextEditor"), ("comms", r"InstantMessaging|Chat|Email|Telephony|VideoConference"),
+ ("creative", r"AudioVideo|Audio|Video|Graphics|Photography"), ("productivity", r"\bOffice\b|WebBrowser|Office"),
+ ("utilities", r"Utility|System|Settings|FileManager|TerminalEmulator|Monitor")]
+
+
+def _desktop(h):
+ """Parse .desktop launchers (system, /usr/local, snap, flatpak, user). Names and categories only."""
+ def build():
+ dirs = list(_DESKTOP_DIRS) + [("user", _data(h, "applications")),
+ ("flatpak_user", _data(h, "flatpak", "exports", "share", "applications"))]
+ out = []
+ for src, d in dirs:
+ for n in (_ls(d, 3000) or []):
+ if not n.endswith(".desktop"):
+ continue
+ p = os.path.join(d, n)
+ try:
+ with open(p, encoding="utf-8", errors="replace") as f:
+ txt = f.read(64_000)
+ st = os.stat(p)
+ except OSError:
+ continue
+ sec = txt.split("[Desktop Entry]", 1)[-1].split("\n[", 1)[0]
+ kv = {}
+ for line in sec.splitlines():
+ k, s, v = line.partition("=")
+ if s and k.strip() in ("Name", "Exec", "Categories", "NoDisplay", "Hidden", "Type", "MimeType",
+ "OnlyShowIn", "X-KDE-ServiceTypes"):
+ kv.setdefault(k.strip(), v.strip())
+ exe = (kv.get("Exec") or "").split()
+ exe0 = next((x for x in exe if not x.startswith(("env", "-")) and "=" not in x), "")
+ launchable = kv.get("Type", "Application") == "Application" and kv.get("NoDisplay", "").lower() != "true" \
+ and kv.get("Hidden", "").lower() != "true" and not n.startswith(("kcm_", "org.kde.kcm"))
+ out.append({"id": n[:-8], "name": kv.get("Name") or n[:-8], "src": src, "exec": exe0,
+ "categories": kv.get("Categories", ""), "mime": kv.get("MimeType", ""),
+ "launchable": launchable, "ctime": _day(st.st_ctime)})
+ return out
+ return _memo(h, "desktop", build)
+
+
+def _cls(name, extra=""):
+ c = ad._classify(name, "", extra)
+ if c != "other":
+ return c
+ for cat, rx in _CAT_MAP:
+ if re.search(rx, extra or ""):
+ return cat
+ return "other"
+
+
+def _snaps():
+ out = []
+ for n in (_ls("/snap", 500) or []):
+ if n in ("bin", "README") or not _isdir(os.path.join("/snap", n)):
+ continue
+ cur = os.path.join("/snap", n, "current")
+ try:
+ rev = os.readlink(cur)
+ ctime = _day(os.stat(os.path.join("/snap", n)).st_ctime)
+ except OSError:
+ rev, ctime = None, None
+ out.append({"name": n, "revision": rev, "installed": ctime})
+ return out
+
+
+def _flatpaks(h):
+ out = []
+ for scope, root in (("system", "/var/lib/flatpak/app"), ("user", _data(h, "flatpak", "app"))):
+ for n in (_ls(root, 1000) or []):
+ try:
+ ct = _day(os.stat(os.path.join(root, n)).st_ctime)
+ except OSError:
+ ct = None
+ out.append({"id": n, "scope": scope, "installed": ct})
+ return out
+
+
+_BASE_SNAPS = re.compile(r"^(core\d*|snapd|bare|gnome-\d.*|gtk-common-themes|kf5-.*|kde-.*|mesa-.*|firmware-updater|snap-store|snapd-desktop-integration|lxd)$")
+
+
+def _taxonomy(h):
+ """User-facing app inventory: user-requested apt packages, /opt apps, snaps, flatpaks, launchable .desktop
+ entries, ~/.local/bin AI CLIs. 'pre' = shipped with the image (not user-requested, not /opt, not user scope)."""
+ def build():
+ apps = {}
+
+ def add(name, cat, date, src, pre):
+ n = ad._norm(name)
+ if not n:
+ return
+ a = apps.setdefault(n, {"name": name, "category": cat, "date": None, "sources": set(), "pre": pre})
+ a["sources"].add(src)
+ a["pre"] = a["pre"] and pre
+ if cat != "other" and a["category"] == "other":
+ a["category"] = cat
+ if date and (not a["date"] or date < a["date"]):
+ a["date"] = date
+ dp = _dpkg(h) or {"pkgs": {}, "requested": [], "first_install": {}}
+ req = {}
+ for name, d, _me in dp["requested"]:
+ if name in dp["pkgs"] and (name not in req or d < req[name]):
+ req[name] = d
+ for name, d in req.items():
+ add(name, _cls(name, dp["pkgs"][name]["section"]), d, "apt_requested", False)
+ for n in (_ls("/opt", 200) or []):
+ if n not in ("containerd",) and _isdir(os.path.join("/opt", n)):
+ try:
+ ct = _day(os.stat(os.path.join("/opt", n)).st_ctime)
+ except OSError:
+ ct = None
+ add(n, _cls(n), ct, "opt", False)
+ for s in _snaps():
+ if not _BASE_SNAPS.match(s["name"]):
+ add(s["name"], _cls(s["name"]), s["installed"], "snap", False)
+ for f in _flatpaks(h):
+ nm = f["id"].split(".")[-1]
+ add(nm, _cls(f["id"]), f["installed"], "flatpak", False)
+ req_names = set(req)
+ oi = dp.get("os_install") or ""
+ post = {p for p, d in dp["first_install"].items() if d > oi and p in dp["pkgs"]} | req_names
+
+ def post_pkg(*names):
+ for n in names:
+ n = (n or "").lower()
+ if len(n) >= 4 and any(p == n or (len(p) >= 4 and (p.startswith(n) or n.startswith(p))) for p in post):
+ return True
+ return False
+ for e in _desktop(h):
+ if not e["launchable"]:
+ continue
+ user_scope = e["src"] in ("user", "flatpak_user", "snap", "flatpak")
+ from_opt = e["exec"].startswith("/opt/")
+ pre = not (user_scope or from_opt or post_pkg(e["id"].split(".")[-1], os.path.basename(e["exec"])))
+ add(e["name"], _cls(e["name"], e["categories"]), e["ctime"] if not pre else None, "desktop_" + e["src"], pre)
+ for nm in _ls(os.path.join(_U(h), ".local", "bin")) or []:
+ if nm.lower() in ("claude", "codex", "hermes", "ollama", "gemini", "aider", "goose", "opencode", "cua-driver",
+ "agent-browser", "copilot"):
+ add(nm, "ai", _mtime(os.path.join(_U(h), ".local", "bin", nm)), "local_bin", False)
+ allv = list(apps.values())
+ user = [v for v in allv if v["category"] in ad.USER_CATS or v["category"] == "other"]
+ return {"os_install": dp.get("os_install"), "all": allv, "user": user}
+ return _memo(h, "taxonomy", build)
+
+
+@_lp("apps.dpkg", level="L1", family=APPS, tier="T0", collect="core")
+def apps_dpkg(h, facts):
+ """dpkg package database present (stat only; parsed by the L2 extractors)."""
+ m = h.meta("/var/lib/dpkg/status")
+ if not m.get("present"):
+ return None
+ return {"present": True, "status_bytes": m["bytes"], "status_mtime": _day(m["mtime"]),
+ "apt": os.path.exists("/usr/bin/apt"), "os_install": _os_install_date()}
+
+
+@_lp("apps.packages", level="L2", family=APPS, tier="T0", collect="core", gate="apps.dpkg", timeout_ms=4000)
+def apps_packages(h, facts):
+ """Installed deb packages: count, manual vs auto, sections, user-requested installs (apt history), log range."""
+ dp = _dpkg(h)
+ if not dp:
+ return None
+ pk = dp["pkgs"]
+ manual = [p for p in pk if p not in dp["auto"]]
+ secs = collections.Counter((v["section"] or "?").split("/")[-1] for v in pk.values())
+ req = {n: d for n, d, _ in dp["requested"] if n in pk}
+ req_me = sorted({n for n, _, me in dp["requested"] if me and n in pk})
+ return {"present": True, "count": len(pk), "manual": len(manual), "auto": len(pk) - len(manual),
+ "installed_gb": round(sum(v["kb"] for v in pk.values()) / 1e6, 2),
+ "sections_top": dict(secs.most_common(12)), "user_requested": len(req),
+ "user_requested_by_me": len(req_me), "user_requested_names": sorted(req)[:60],
+ "dpkg_log_oldest": dp["oldest_log"], "os_install": dp["os_install"],
+ "install_events_by_month": dict(sorted(dp["install_months"].items()))}
+
+
+@_lp("apps.snap", level="L1", family=APPS, tier="T0", collect="core")
+def apps_snap(h, facts):
+ """Snap packages from /snap (no `snap list` spawn); base/runtime snaps flagged."""
+ if not _isdir("/snap"):
+ return None
+ s = _snaps()
+ user = [x["name"] for x in s if not _BASE_SNAPS.match(x["name"])]
+ return {"present": bool(s), "count": len(s), "user_facing": sorted(user), "snapd": _ex("/usr/lib/snapd/snapd"),
+ "user_snap_dirs": len(_ls(os.path.join(_U(h), "snap")) or [])}
+
+
+@_lp("apps.flatpak", level="L1", family=APPS, tier="T0", collect="core")
+def apps_flatpak(h, facts):
+ """Flatpak apps (system + user installation dirs; no `flatpak list` spawn)."""
+ f = _flatpaks(h)
+ if not f and not _ex("/usr/bin/flatpak"):
+ return None
+ return {"present": True, "binary": _ex("/usr/bin/flatpak"), "count": len(f),
+ "apps": sorted(x["id"] for x in f)[:60], "user_scope": sum(1 for x in f if x["scope"] == "user")}
+
+
+@_lp("apps.desktop_entries", level="L2", family=APPS, tier="T0", collect="core", gate="apps.dpkg")
+def apps_desktop_entries(h, facts):
+ """Launchable .desktop entries by source and category; user-created launchers listed by name."""
+ ents = _desktop(h)
+ if not ents:
+ return None
+ la = [e for e in ents if e["launchable"]]
+ by_src = collections.Counter(e["src"] for e in la)
+ cats = collections.Counter(_cls(e["name"], e["categories"]) for e in la)
+ return {"present": True, "files": len(ents), "launchable": len(la), "by_source": dict(by_src),
+ "by_category": dict(cats.most_common()),
+ "user_launchers": sorted(e["id"] for e in ents if e["src"] in ("user", "flatpak_user"))[:30]}
+
+
+@_lp("apps.taxonomy", level="L2", family=APPS, tier="T0", collect="core", gate="apps.dpkg")
+def apps_taxonomy(h, facts):
+ """Merged user-facing inventory (apt requested + /opt + snap + flatpak + .desktop + ~/.local/bin) by category."""
+ t = _taxonomy(h)
+ cats = ad.USER_CATS + ["other"]
+ return {"present": True, "unique_all": len(t["all"]), "unique_user_facing": len(t["user"]),
+ "counts_all": dict(collections.Counter(v["category"] for v in t["all"]).most_common()),
+ "counts_user_facing": {c: sum(1 for v in t["user"] if v["category"] == c) for c in cats},
+ "names": {c: sorted(v["name"] for v in t["user"] if v["category"] == c)[:60] for c in cats}}
+
+
+@_lp("apps.taxonomy_user_added", level="L2", family=APPS, tier="T0", collect="core", gate="apps.dpkg")
+def apps_taxonomy_user_added(h, facts):
+ """Category counts of apps the user added (not shipped with the image)."""
+ t = _taxonomy(h)
+ cats = ad.USER_CATS + ["other"]
+ added = [v for v in t["user"] if not v["pre"]]
+ months = collections.Counter(v["date"][:7] for v in added if v["date"])
+ return {"present": True, "profile_created": _day(os.stat(_U(h)).st_ctime), "image_date": t["os_install"],
+ "user_added_total": len(added), "preinstalled_total": len(t["user"]) - len(added),
+ "counts": {c: sum(1 for v in added if v["category"] == c) for c in cats},
+ "by_month": dict(sorted(months.items())), "undated": sum(1 for v in added if not v["date"])}
+
+
+@_lp("apps.install_timeline", level="L2", family=APPS, tier="T0", collect="core", gate="apps.dpkg")
+def apps_install_timeline(h, facts):
+ """Month spread of user-requested installs (apt history, snap, flatpak, /opt); dpkg dependency installs separate."""
+ dp = _dpkg(h) or {}
+ t = _taxonomy(h)
+ months = collections.Counter(v["date"][:7] for v in t["user"] if not v["pre"] and v["date"])
+ return {"present": bool(months or dp.get("install_months")), "distinct_months": len(months),
+ "by_month": dict(sorted(months.items())), "first": min(months) if months else None,
+ "last": max(months) if months else None,
+ "dpkg_install_months": len(dp.get("install_months") or {}), "log_window_starts": dp.get("oldest_log")}
+
+
+@_lp("apps.autostart", level="L1", family=APPS, tier="T0", collect="core")
+def apps_autostart(h, facts):
+ """XDG autostart entries (user + /etc/xdg) and enabled systemd --user units (names only)."""
+ user = sorted(n[:-8] for n in (_ls(_cfg(h, "autostart")) or []) if n.endswith(".desktop"))
+ sysn = len([n for n in (_ls("/etc/xdg/autostart") or []) if n.endswith(".desktop")])
+ units = set()
+ for w in glob.glob(_cfg(h, "systemd", "user", "*.wants"))[:50]:
+ units.update(n for n in (_ls(w) or []) if n.endswith((".service", ".timer", ".socket")))
+ own = sorted(n for n in (_ls(_cfg(h, "systemd", "user")) or []) if n.endswith((".service", ".timer")))
+ return {"present": True, "user_autostart": user, "system_autostart_count": sysn,
+ "systemd_user_enabled": sorted(units)[:40], "systemd_user_unit_files": own[:40]}
+
+
+_PROC_INTEREST = re.compile(r"claude|codex|hermes|ollama|lm ?studio|cursor|windsurf|copilot|gemini|opencode|aider|cua|"
+ r"agent-browser|docker|discord|steam|slack|teams|^code$|brave|chrome|firefox|tailscale|obs|"
+ r"spotify|tmux|zellij|screen|node|bun|python|signal|telegram|zoom|vnc|plasmashell|kwin", re.I)
+
+
+@_lp("tasks.nonms", level="L2", family=APPS, tier="T2", collect="extended", gate="apps.dpkg", timeout_ms=3000)
+def tasks_nonms(h, facts):
+ """This user's scheduled jobs: `crontab -l` entry count and command names, systemd --user timers; lab jobs counted
+ separately."""
+ rc, txt, _ms = _spawn(["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(), 0
+ for j in jobs:
+ parts = j.split()
+ cmd = parts[5] if not j.startswith("@") and len(parts) > 5 else (parts[1] if len(parts) > 1 else "")
+ if _OP_DEEP.search(j) or re.search(r"hermes-|user-insights|uil/", j):
+ op += 1
+ continue
+ names[os.path.basename(cmd)[:40]] += 1
+ timers = sorted(n for n in (_ls(_cfg(h, "systemd", "user")) or []) if n.endswith(".timer"))
+ if not jobs and not timers:
+ return {"present": False}
+ return {"present": True, "count": len(jobs) - op, "cron_commands": dict(names.most_common(10)),
+ "operator_lab_jobs": op, "systemd_user_timers": timers[:20]}
+
+
+@_lp("proc.snapshot", level="L1", family=APPS, tier="T1", collect="core")
+def proc_snapshot(h, facts):
+ """/proc snapshot for the invoking uid only: count, top names, running agents/apps; other users as a count."""
+ p = _procs(h)
+ n = p["names"]
+ return {"present": True, "total": sum(n.values()), "distinct": len(n), "top": dict(n.most_common(20)),
+ "interesting": dict(sorted((k, v) for k, v in n.items() if _PROC_INTEREST.search(k))),
+ "all_users_total": p["total_all_users"]}
+
+
+# ================================================================== ai_agents
+
+@_lp("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 = _U(h)
+ cat = {
+ "cursor": [os.path.join(U, ".cursor"), _cfg(h, "Cursor"), "/opt/Cursor", "/usr/share/cursor"],
+ "windsurf": [os.path.join(U, ".codeium"), os.path.join(U, ".windsurf"), _cfg(h, "Windsurf")],
+ "gemini_cli": [os.path.join(U, ".gemini")],
+ "opencode": [_data(h, "opencode"), _cfg(h, "opencode"), os.path.join(U, ".opencode")],
+ "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")],
+ "goose": [_cfg(h, "goose"), _data(h, "goose")], "amp": [_cfg(h, "amp")],
+ "chatgpt_desktop": [_cfg(h, "ChatGPT")],
+ "lm_studio": [os.path.join(U, ".lmstudio"), os.path.join(U, ".cache", "lm-studio"), _cfg(h, "LM Studio")],
+ "jan": [_cfg(h, "Jan"), _data(h, "Jan"), os.path.join(U, "jan")], "gpt4all": [_data(h, "nomic.ai")],
+ "msty": [_cfg(h, "Msty")], "anythingllm": [_cfg(h, "anythingllm-desktop")],
+ "hf_hub": [_cachedir(h, "huggingface", "hub")], "vllm": [_cachedir(h, "vllm")],
+ "llama_cpp": [_cachedir(h, "llama.cpp")], "comfyui": [os.path.join(U, "ComfyUI")],
+ }
+ found = {k: _ex(*v) for k, v in cat.items()}
+ hf_models = sum(1 for n in (_ls(_cachedir(h, "huggingface", "hub")) 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}
+
+
+def _npm_roots(h):
+ U = _U(h)
+ roots = [os.path.join(U, ".npm-global", "lib", "node_modules"), os.path.join(U, ".local", "lib", "node_modules"),
+ "/usr/local/lib/node_modules", "/usr/lib/node_modules"]
+ roots += glob.glob(_data(h, "fnm", "node-versions", "*", "installation", "lib", "node_modules"))[:10]
+ roots += glob.glob(os.path.join(U, ".nvm", "versions", "node", "*", "lib", "node_modules"))[:10]
+ roots += glob.glob(os.path.join(U, ".volta", "tools", "image", "packages", "*", "lib", "node_modules"))[:20]
+ return [r for r in roots if _isdir(r)]
+
+
+def _npm_pkg(h, name):
+ for r in _npm_roots(h):
+ pj = _read_json(os.path.join(r, name, "package.json"))
+ if isinstance(pj, dict):
+ return {"root": "user" if r.startswith(_U(h)) else "system", "version": pj.get("version")}
+ return None
+
+
+@_lp("browser.automation", level="L1", family=AI, tier="T0", collect="core")
+def browser_automation(h, facts):
+ """Browser-automation runtimes on disk: Playwright, puppeteer, camoufox, agent-browser (npm or binary)."""
+ U = _U(h)
+ out = {}
+ for label, p in (("playwright_cache", _cachedir(h, "ms-playwright")), ("puppeteer", _cachedir(h, "puppeteer")),
+ ("camoufox", _cachedir(h, "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)}
+ ab = []
+ npm = _npm_pkg(h, "agent-browser")
+ if npm:
+ ab.append({"where": "npm_" + npm["root"], "version": npm["version"]})
+ hb = glob.glob(os.path.join(U, ".hermes", "hermes-agent", "node_modules", "agent-browser", "package.json"))
+ if hb:
+ ab.append({"where": "hermes_bundled", "version": (_read_json(hb[0]) or {}).get("version")})
+ exe = _which(h, "agent-browser")
+ if exe:
+ ab.append({"where": "binary", "path_kind": "user" if exe.startswith(U) else "system"})
+ if _isdir(os.path.join(U, ".agent-browser")):
+ out["agent_browser_home"] = {"mtime": _mtime(os.path.join(U, ".agent-browser"))}
+ if ab:
+ out["agent_browser"] = ab
+ return {"present": bool(out), **out}
+
+
+_mirror("browser_harness.present", ad.browser_harness_present)
+
+
+@_lp("claude_code.present", level="L1", family=AI, tier="T0", collect="core")
+def claude_code_present(h, facts):
+ """Claude Code CLI: ~/.claude home, native install (~/.local/bin/claude -> versions/), npm global."""
+ U = _U(h)
+ home = os.path.join(U, ".claude")
+ link = os.path.join(U, ".local", "bin", "claude")
+ npm = _npm_pkg(h, "@anthropic-ai/claude-code")
+ if not (_isdir(home) or os.path.lexists(link) or npm):
+ return None
+ ver = None
+ try:
+ ver = os.path.basename(os.readlink(link))
+ except OSError:
+ pass
+ vers = _ls(_data(h, "claude", "versions")) or []
+ return {"present": True, "home": _isdir(home), "native_exe": os.path.exists(link), "exe_version": ver,
+ "npm_install": bool(npm), "npm_version": (npm or {}).get("version"), "installed_versions": len(vers),
+ "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)
+
+
+@_lp("claude_desktop.present", level="L1", family=AI, tier="T0", collect="core")
+def claude_desktop_present(h, facts):
+ """Claude desktop (community Linux builds): ~/.config/Claude and MCP server names from its config."""
+ d = _cfg(h, "Claude")
+ if not _isdir(d):
+ return None
+ cfg = _read_json(os.path.join(d, "claude_desktop_config.json"))
+ return {"present": True, "installed": _ex("/usr/bin/claude-desktop", "/opt/Claude"), "config_mtime": _mtime(d),
+ "mcp_servers": sorted((cfg.get("mcpServers") or {}).keys()) if isinstance(cfg, dict) else []}
+
+
+@_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)
+ npm = _npm_pkg(h, "@openai/codex")
+ exe = _which(h, "codex")
+ if not (_isdir(home) or npm or exe):
+ return None
+ return {"present": True, "home": _isdir(home), "npm_cli": bool(npm), "npm_version": (npm or {}).get("version"),
+ "binary": bool(exe), "home_mtime": _mtime(home)}
+
+
+@_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"))
+
+
+_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)
+
+
+@_lp("cua_driver.present", level="L1", family=AI, tier="T0", collect="core")
+def cua_driver_present(h, facts):
+ """cua-driver (computer-use): ~/.cua-driver release dirs, binary on PATH, running."""
+ home = os.path.join(_U(h), ".cua-driver")
+ exe = _which(h, "cua-driver")
+ if not (_isdir(home) or exe):
+ 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, "binary": bool(exe), "releases": rel[-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"))}
+
+
+def _hermes_homes_lx(h):
+ env = os.environ.get("HERMES_HOME") or ""
+ U = _U(h)
+ cands = []
+ for role, p in (("HERMES_HOME", env), ("dot_hermes", os.path.join(U, ".hermes"))):
+ if p and _isdir(p) and all(os.path.realpath(p) != os.path.realpath(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) \
+ or (cands[0] if cands else None)
+ side = [p for p in glob.glob(os.path.join(U, ".hermes-*")) + glob.glob(os.path.join(U, "hermes-*")) if _isdir(p)][:50]
+ return {"env_set": bool(env), "cands": cands, "primary": primary, "side": side}
+
+
+def _prime_hermes(h):
+ ad._memo(h, "hermes_homes", lambda: _hermes_homes_lx(h))
+
+
+@_lp("hermes.present", level="L1", family=AI, tier="T0", collect="core")
+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)
+ 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 ad.tomllib and os.path.exists(pp):
+ try:
+ with open(pp, "rb") as f:
+ ver = ad.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")),
+ "profiles": len(_ls(os.path.join(p, "profiles")) or []), "cron_jobs": len(_ls(os.path.join(p, "cron")) or [])})
+ units = sorted(n for n in (_ls(_cfg(h, "systemd", "user")) or []) if "hermes" in n.lower())
+ desktop = glob.glob(_cfg(h, "Hermes*"))
+ if not (homes or hh["side"] or units or desktop or _which(h, "hermes")):
+ 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"]), "cli_on_path": bool(_which(h, "hermes")),
+ "systemd_user_units": units, "desktop_userdata_dirs": len(desktop),
+ "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)
+
+
+@_lp("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 (Claude Code, Codex, Hermes, VS Code, Cursor...)."""
+ _prime_hermes(h)
+ U = _U(h)
+ by = {}
+ cj = ad._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")
+ if ad.tomllib and os.path.exists(cp):
+ try:
+ with open(cp, "rb") as f:
+ by["codex"] = sorted((ad.tomllib.load(f).get("mcp_servers") or {}).keys())
+ except Exception:
+ pass
+ for label, path, keys in [("vscode", _cfg(h, "Code", "User", "mcp.json"), ("servers", "mcpServers")),
+ ("claude_desktop", _cfg(h, "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 = ad._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"]
+ except OSError:
+ pass
+ user = sorted({n for v in by.values() for n in v if n not in ad.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})}
+
+
+@_lp("ollama.present", level="L1", family=AI, tier="T0", collect="core")
+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)
+ svc_home = _isdir("/usr/share/ollama")
+ if not (exe or unit or _isdir(os.path.join(_U(h), ".ollama")) or svc_home):
+ return None
+ return {"present": True, "binary": bool(exe), "systemd_unit": bool(unit), "models_dir": _isdir(mroot),
+ "service_account_home": svc_home, "OLLAMA_MODELS_set": bool(os.environ.get("OLLAMA_MODELS")),
+ "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 on daimon; 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)}
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.py
new file mode 100644
index 00000000000..a17f0e41279
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/linux_system.py
@@ -0,0 +1,2161 @@
+"""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.
+
+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.
+L1 probes read files only. Every subprocess sits in an L2 probe behind a gate.
+"""
+from __future__ import annotations
+
+import collections
+import ctypes
+import datetime as dt
+import glob
+import gzip
+import json
+import os
+import platform
+import pwd
+import re
+import grp
+import threading
+import time
+
+from userscan.registry import probe
+
+OS = "linux"
+
+
+def _home():
+ """Invoking user's home at call time (the runner points _home() at an overridden l0 home)."""
+ return os.path.expanduser("~")
+
+OPERATOR_RX = re.compile(r"(hn-e2e|ns960|ns923|/lhm\b|/shots\b|user-insights-lab|userscan|/\.?hermes-[\w-]+)", re.I)
+
+
+def lp(id, **kw):
+ kw.setdefault("os", OS)
+ return probe(id, **kw)
+
+
+# ---------------------------------------------------------------- helpers
+
+_GUARD = threading.Lock()
+
+
+def _cached(h, key, fn):
+ """Compute once per run and share between probes (L2 probes run on parallel threads)."""
+ with _GUARD:
+ cache = h.__dict__.setdefault("_lx_cache", {})
+ locks = h.__dict__.setdefault("_lx_locks", {})
+ lock = locks.setdefault(key, threading.Lock())
+ with lock:
+ if key not in cache:
+ try:
+ cache[key] = fn()
+ except Exception as e:
+ cache[key] = {"__error__": f"{type(e).__name__}: {e}"}
+ v = cache[key]
+ if isinstance(v, dict) and "__error__" in v:
+ raise RuntimeError(v["__error__"])
+ return v
+
+
+def _fv(facts, pid):
+ """Value of another probe; the runner passes records ({status, value}), the contract says bare values."""
+ r = facts.get(pid)
+ if isinstance(r, dict) and "status" in r and "value" in r:
+ return r["value"] if r["status"] == "ok" else None
+ return r
+
+
+def _read(path, limit=1 << 20):
+ try:
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
+ return f.read(limit)
+ except OSError:
+ return None
+
+
+def _read1(path):
+ t = _read(path, 4096)
+ return t.strip() if t is not None else None
+
+
+def _kv(text):
+ out = {}
+ for line in (text or "").splitlines():
+ line = line.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ k, v = line.split("=", 1)
+ out[k.strip()] = v.strip().strip('"').strip("'")
+ return out
+
+
+def _ini(text):
+ """KDE/GTK ini. Section headers like [Containments][1][General] are kept verbatim."""
+ out, sec = {}, ""
+ for line in (text or "").splitlines():
+ s = line.strip()
+ if not s or s.startswith(("#", ";")):
+ continue
+ if s.startswith("[") and s.endswith("]"):
+ sec = s[1:-1]
+ out.setdefault(sec, {})
+ continue
+ if "=" in s:
+ k, v = s.split("=", 1)
+ out.setdefault(sec, {})[k.strip()] = v.strip()
+ return out
+
+
+def _iso(ts):
+ if ts is None:
+ return None
+ try:
+ return dt.datetime.fromtimestamp(float(ts)).astimezone().isoformat(timespec="seconds")
+ except (OverflowError, OSError, ValueError):
+ return None
+
+
+def _parse_iso(s):
+ try:
+ return dt.datetime.fromisoformat(str(s).replace("Z", "+00:00"))
+ except ValueError:
+ return None
+
+
+def _days_ago(ts):
+ return None if ts is None else round((time.time() - float(ts)) / 86400.0, 1)
+
+
+def _which(name, extra=()):
+ for d in ("/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin", "/snap/bin", *extra):
+ p = os.path.join(d, name)
+ if os.path.isfile(p) and os.access(p, os.X_OK):
+ return p
+ return None
+
+
+def _run(h, args, timeout_ms=3000):
+ """h.run under env(1) with LC_ALL=C so parsers see stable English output."""
+ return h.run(["env", "LC_ALL=C", "LANG=C", *args], timeout_ms=timeout_ms)
+
+
+class _Statx(ctypes.Structure):
+ _fields_ = [("mask", ctypes.c_uint32), ("blksize", ctypes.c_uint32), ("attributes", ctypes.c_uint64),
+ ("nlink", ctypes.c_uint32), ("uid", ctypes.c_uint32), ("gid", ctypes.c_uint32),
+ ("mode", ctypes.c_uint16), ("_pad1", ctypes.c_uint16), ("ino", ctypes.c_uint64),
+ ("size", ctypes.c_uint64), ("blocks", ctypes.c_uint64), ("attributes_mask", ctypes.c_uint64),
+ ("atime_s", ctypes.c_int64), ("atime_ns", ctypes.c_uint32), ("_p2", ctypes.c_int32),
+ ("btime_s", ctypes.c_int64), ("btime_ns", ctypes.c_uint32), ("_p3", ctypes.c_int32),
+ ("_rest", ctypes.c_uint8 * 160)]
+
+
+_LIBC = None
+
+
+def _birth(path):
+ """File birth time (epoch s) via statx(2); None when the filesystem does not record it."""
+ global _LIBC
+ try:
+ if _LIBC is None:
+ _LIBC = ctypes.CDLL(None, use_errno=True)
+ fn = getattr(_LIBC, "statx", None)
+ if fn is None:
+ return None
+ buf = _Statx()
+ if fn(-100, os.fsencode(path), 0, 0x800, ctypes.byref(buf)) != 0:
+ return None
+ if not buf.mask & 0x800 or buf.btime_s <= 0:
+ return None
+ return int(buf.btime_s)
+ except Exception:
+ return None
+
+
+def _mtime(path):
+ try:
+ return os.stat(path).st_mtime
+ except OSError:
+ return None
+
+
+def _me():
+ try:
+ return pwd.getpwuid(os.getuid())
+ except KeyError:
+ return None
+
+
+def _passwd_rows():
+ rows = []
+ for line in (_read("/etc/passwd") or "").splitlines()[:5000]:
+ p = line.split(":")
+ if len(p) >= 7:
+ try:
+ rows.append({"name": p[0], "uid": int(p[2]), "gid": int(p[3]), "home": p[5], "shell": p[6]})
+ except ValueError:
+ continue
+ return rows
+
+
+_NOLOGIN = ("nologin", "false", "sync", "halt", "shutdown")
+
+
+def _human(r):
+ return 1000 <= r["uid"] < 60000 and not r["shell"].endswith(_NOLOGIN)
+
+
+def _enabled_units():
+ """Unit names enabled through *.wants/ symlinks under /etc/systemd (no subprocess)."""
+ out = set()
+ for d in glob.glob("/etc/systemd/system/*.wants")[:100]:
+ for n in os.listdir(d)[:500] if os.path.isdir(d) else []:
+ out.add(n)
+ return out
+
+
+def _dpkg_names(h):
+ """Installed package names from /var/lib/dpkg/info/*.list (a directory listing, no file reads)."""
+ def load():
+ names = set()
+ try:
+ with os.scandir("/var/lib/dpkg/info") as it:
+ for i, e in enumerate(it):
+ if i > 60000:
+ break
+ if e.name.endswith(".list"):
+ names.add(e.name[:-5].split(":")[0])
+ except OSError:
+ pass
+ return names
+ return _cached(h, "dpkg_names", load)
+
+
+def _os_release():
+ return _kv(_read("/etc/os-release") or _read("/usr/lib/os-release") or "")
+
+
+def _bcp47(loc):
+ if not loc:
+ return None
+ base = loc.split(".")[0].split("@")[0]
+ if base in ("C", "POSIX"):
+ return base
+ return base.replace("_", "-")
+
+
+# ================================================================ host
+
+@lp("os.edition", level="L1", family="host")
+def os_edition(h, facts):
+ """Distribution name, version and codename from /etc/os-release."""
+ r = _os_release()
+ if not r:
+ return None
+ return {"present": True, "marketing_name": r.get("PRETTY_NAME"), "edition_id": r.get("ID"),
+ "id_like": r.get("ID_LIKE"), "version_id": r.get("VERSION_ID"), "codename": r.get("VERSION_CODENAME"),
+ "variant": r.get("VARIANT_ID"), "lts": "LTS" in (r.get("VERSION") or "")}
+
+
+@lp("os.build", level="L1", family="host")
+def os_build(h, facts):
+ """Kernel release and build string (uname)."""
+ u = os.uname()
+ flavour = u.release.split("-")[-1] if "-" in u.release else None
+ return {"present": True, "build": u.release, "kernel": u.release, "kernel_version": u.version,
+ "kernel_flavour": flavour, "display_version": _os_release().get("VERSION_ID")}
+
+
+_ARCH = {"x86_64": "x64", "amd64": "x64", "aarch64": "arm64", "arm64": "arm64", "i686": "x86", "i386": "x86"}
+
+
+@lp("host.native_arch", level="L1", family="host")
+def native_arch(h, facts):
+ """Machine architecture (uname -m), normalised to the Windows spelling."""
+ m = os.uname().machine.lower()
+ return {"present": True, "arch": _ARCH.get(m, m), "machine": m}
+
+
+def _elf_machine(path):
+ try:
+ with open(path, "rb") as f:
+ hdr = f.read(20)
+ if hdr[:4] != b"\x7fELF":
+ return ""
+ (em,) = __import__("struct").unpack("<H" if hdr[5] == 1 else ">H", hdr[18:20])
+ return {0x3E: "x64", 0xB7: "arm64", 0x03: "x86", 0x28: "arm"}.get(em, hex(em))
+ except OSError:
+ return ""
+
+
+@lp("host.python_emulated", level="L1", family="host")
+def python_emulated(h, facts):
+ """Interpreter ELF machine vs kernel machine (qemu-user/box64 emulation makes timings untrustworthy)."""
+ import sys
+ py = _elf_machine(os.path.realpath(sys.executable))
+ nat = _ARCH.get(os.uname().machine.lower(), os.uname().machine.lower())
+ return {"present": True, "python_arch": py, "native_arch": nat, "emulated": bool(py and nat and py != nat),
+ "python": platform.python_version()}
+
+
+_VIRT_VENDORS = (("qemu", "kvm"), ("kvm", "kvm"), ("vmware", "vmware"), ("virtualbox", "virtualbox"),
+ ("innotek", "virtualbox"), ("microsoft corporation", "hyperv"), ("xen", "xen"),
+ ("amazon ec2", "aws"), ("google", "gce"), ("parallels", "parallels"), ("bochs", "bochs"))
+
+
+@lp("host.virtualization", level="L1", family="host")
+def host_virtualization(h, facts):
+ """VM / container / WSL detection from DMI vendor, the cpuinfo hypervisor flag and marker files."""
+ vend = " ".join(filter(None, (_read1("/sys/class/dmi/id/sys_vendor"), _read1("/sys/class/dmi/id/product_name"),
+ _read1("/sys/class/dmi/id/bios_vendor")))).lower()
+ kind = next((k for w, k in _VIRT_VENDORS if w in vend), None)
+ cpu = _read("/proc/cpuinfo", 8192) or ""
+ hyper = bool(re.search(r"^flags\s*:.*\bhypervisor\b", cpu, re.M))
+ osrel = (_read1("/proc/sys/kernel/osrelease") or "").lower()
+ container = None
+ if os.path.exists("/.dockerenv"):
+ container = "docker"
+ elif os.path.exists("/run/.containerenv"):
+ container = "podman"
+ return {"present": True, "virtual": bool(kind or hyper), "kind": kind or ("unknown" if hyper else None),
+ "hypervisor_flag": hyper, "container": container, "wsl": "microsoft" in osrel}
+
+
+@lp("host.systemd", level="L1", family="host")
+def host_systemd(h, facts):
+ """systemd is PID 1 (gate for systemctl/journalctl probes)."""
+ if not os.path.isdir("/run/systemd/system"):
+ return None
+ return {"present": True, "journal_persistent": os.path.isdir("/var/log/journal"),
+ "enabled_unit_links": len(_enabled_units())}
+
+
+# ================================================================ identity
+
+@lp("host.name", level="L1", family="identity")
+def host_name(h, facts):
+ """Hostname. local_only: identifies the machine, never send off-host."""
+ n = os.uname().nodename
+ static = _read1("/etc/hostname")
+ return {"present": bool(n), "name": n, "local_only": True,
+ "pending_rename": bool(static and n and static.lower() != n.lower())}
+
+
+@lp("host.name_default", level="L1", family="identity")
+def host_name_default(h, facts):
+ """Hostname still an installer/cloud default (ubuntu, localhost, ip-10-..., a MAC-like id)."""
+ n = os.uname().nodename.lower()
+ default = bool(re.fullmatch(r"(ubuntu|debian|localhost|fedora|archlinux|raspberrypi|ubuntu-server|"
+ r"ip-\d+-\d+-\d+-\d+.*|[0-9a-f]{12})", n))
+ return {"present": True, "default": default}
+
+
+@lp("acct.account_type", level="L1", family="identity")
+def account_type(h, facts):
+ """Local vs directory account: invoking user in /etc/passwd or served by sssd/ldap/winbind (nsswitch)."""
+ me = _me()
+ if me is None:
+ return None
+ local = any(r["uid"] == me.pw_uid for r in _passwd_rows())
+ nss = _kv("\n".join(l.replace(":", "=", 1) for l in (_read("/etc/nsswitch.conf") or "").splitlines()))
+ pw_src = nss.get("passwd", "")
+ kind = "local" if local else ("sssd" if "sss" in pw_src else "ldap" if "ldap" in pw_src else
+ "winbind" if "winbind" in pw_src else "directory")
+ return {"present": True, "type": kind, "uid": me.pw_uid, "nss_passwd": pw_src.split(),
+ "sssd_configured": os.path.exists("/etc/sssd/sssd.conf"), "realm_joined": os.path.exists("/etc/krb5.keytab")}
+
+
+@lp("profile.count", level="L1", family="identity")
+def profile_count(h, facts):
+ """Human accounts (uid >= 1000 with a login shell) from /etc/passwd; home dirs are never opened."""
+ rows = _passwd_rows()
+ humans = [r for r in rows if _human(r)]
+ real = [r for r in humans if not OPERATOR_RX.search(r["home"])]
+ me = _me()
+ return {"present": True, "nonsystem": len(real), "operator_excluded": len(humans) - len(real),
+ "passwd_rows": len(rows), "home_dirs": sum(1 for r in real if r["home"].startswith("/home/")),
+ "current_found": bool(me and any(r["uid"] == me.pw_uid for r in rows))}
+
+
+@lp("profile.username_default", level="L1", family="identity")
+def profile_username_default(h, facts):
+ """Account name is an image default (ubuntu, pi, user, admin, ec2-user)."""
+ me = _me()
+ if me is None:
+ return None
+ return {"present": True, "default": me.pw_name.lower() in ("ubuntu", "pi", "user", "admin", "ec2-user", "debian",
+ "fedora", "vagrant", "live")}
+
+
+@lp("acct.local_users", level="L2", family="identity", tier="T1", collect="extended", gate="profile.count")
+def local_users(h, facts):
+ """Account counts by kind from /etc/passwd plus live-process owners (ps): names never emitted."""
+ rows = _passwd_rows()
+ me = _me()
+ kinds = collections.Counter()
+ for r in rows:
+ if me and r["uid"] == me.pw_uid:
+ kinds["current"] += 1
+ elif r["uid"] == 0:
+ kinds["root"] += 1
+ elif _human(r):
+ kinds["other_human"] += 1
+ elif r["uid"] < 1000:
+ kinds["system"] += 1
+ else:
+ kinds["other"] += 1
+ procs = collections.Counter()
+ try:
+ for pid in os.listdir("/proc")[:20000]:
+ if pid.isdigit():
+ try:
+ procs[os.stat("/proc/" + pid).st_uid] += 1
+ except OSError:
+ pass
+ except OSError:
+ pass
+ humans_uids = {r["uid"] for r in rows if _human(r)}
+ active_humans = sum(1 for u in procs if u in humans_uids and not (me and u == me.pw_uid))
+ return {"present": True, "total": len(rows), "kinds": dict(kinds),
+ "other_humans_with_processes": active_humans, "uids_with_processes": len(procs)}
+
+
+# ================================================================ install_age
+
+def _install_candidates():
+ c = {}
+ for label, p in (("installer_dir", "/var/log/installer"), ("root_fs", "/"), ("lost_found", "/lost+found"),
+ ("machine_id", "/etc/machine-id")):
+ b = _birth(p)
+ if b:
+ c[label] = b
+ if "installer_dir" not in c and os.path.isdir("/var/log/installer"):
+ m = [x for x in (_mtime(os.path.join("/var/log/installer", n)) for n in os.listdir("/var/log/installer")[:50]) if x]
+ if m:
+ c["installer_files_mtime"] = min(m)
+ return c
+
+
+@lp("os.install_date", level="L1", family="install_age")
+def os_install_date(h, facts):
+ """OS install date: birth of /var/log/installer, else the root filesystem birth."""
+ c = _install_candidates()
+ for k in ("installer_dir", "installer_files_mtime", "root_fs", "lost_found", "machine_id"):
+ if k in c:
+ return {"present": True, "install_date": _iso(c[k]), "days_ago": _days_ago(c[k]), "source": k,
+ "candidates": {a: _iso(b) for a, b in c.items()}}
+ return None
+
+
+@lp("profile.created", level="L1", family="install_age")
+def profile_created(h, facts):
+ """Birth of the invoking user's home and ~/.config: user-tenure anchor."""
+ folder = _birth(_home())
+ cfg = _birth(os.path.join(_home(), ".config"))
+ first = min([t for t in (folder, cfg) if t], default=None)
+ if first is None:
+ return None
+ return {"present": True, "created": _iso(first), "folder": _iso(folder), "config_dir": _iso(cfg),
+ "days_ago": _days_ago(first)}
+
+
+def _dpkg_logs():
+ """dpkg.log files oldest first."""
+ fs = glob.glob("/var/log/dpkg.log*")
+
+ def order(p):
+ m = re.search(r"\.(\d+)(\.gz)?$", p)
+ return -int(m.group(1)) if m else 0
+ return sorted(fs, key=order)
+
+
+def _first_line(path):
+ try:
+ opener = gzip.open if path.endswith(".gz") else open
+ with opener(path, "rt", encoding="utf-8", errors="replace") as f:
+ return f.readline().strip()
+ except (OSError, EOFError):
+ return None
+
+
+@lp("setup.image_date", level="L1", family="install_age")
+def setup_image_date(h, facts):
+ """Install media build stamp (media-info) and oldest dpkg.log line; image_date only for cloned/OEM images."""
+ media = _read1("/var/log/installer/media-info")
+ build = None
+ if media:
+ m = re.search(r"\((\d{8})(?:\.\d+)?\)", media)
+ if m:
+ build = f"{m.group(1)[:4]}-{m.group(1)[4:6]}-{m.group(1)[6:]}"
+ logs = _dpkg_logs()
+ first = _first_line(logs[0]) if logs else None
+ dpkg_first = first[:19] if first and re.match(r"\d{4}-\d\d-\d\d", first) else None
+ if not build and not dpkg_first:
+ return None
+ cloned = os.path.isdir("/var/lib/cloud/instance") and not os.path.isdir("/var/log/installer") \
+ or os.path.exists("/var/lib/oem-config")
+ # An installer-media build date predates every install by months; only a cloned/OEM image carries its build
+ # date into the install lineage, so image_date is set for those alone.
+ return {"present": True, "image_date": (build or (dpkg_first or "")[:10]) if cloned else None,
+ "media_build": build, "dpkg_log_first": dpkg_first, "installer_media": media, "cloned_image": cloned}
+
+
+@lp("setup.oem", level="L1", family="install_age")
+def setup_oem(h, facts):
+ """Install method: OEM preload (oem-config) vs subiquity/curtin/ubiquity/autoinstall/cloud image."""
+ d = "/var/log/installer"
+ names = set(os.listdir(d)[:200]) if os.path.isdir(d) else set()
+ oem = any(os.path.exists(p) for p in ("/var/lib/oem-config", "/var/log/oem-config.log", "/usr/sbin/oem-config-firstboot"))
+ if "autoinstall-user-data" in names:
+ method = "subiquity-autoinstall"
+ elif "curtin-install.log" in names or "subiquity-server-debug.log" in names:
+ method = "subiquity"
+ elif "syslog" in names and "casper.log" in names:
+ method = "ubiquity"
+ elif os.path.isdir("/var/lib/cloud/instance") and not names:
+ method = "cloud-image"
+ elif names:
+ method = "installer"
+ else:
+ method = "unknown"
+ return {"present": True, "oem_image": oem, "install_method": method,
+ "cloud_init": os.path.isdir("/var/lib/cloud/instances")}
+
+
+@lp("setup.oobe_done", level="L1", family="install_age")
+def setup_oobe_done(h, facts):
+ """First-login setup finished: GNOME ~/.config/gnome-initial-setup-done birth (KDE has no marker)."""
+ p = os.path.join(_home(), ".config/gnome-initial-setup-done")
+ t = _birth(p) or _mtime(p)
+ if not t:
+ return None
+ return {"present": True, "date": _iso(t), "source": "gnome-initial-setup-done"}
+
+
+@lp("setup.source_os_lineage", level="L1", family="install_age")
+def setup_source_os_lineage(h, facts):
+ """Release upgrades since install: /var/log/dist-upgrade runs and installer release vs current release."""
+ runs, oldest = 0, None
+ du = "/var/log/dist-upgrade"
+ if os.path.isdir(du):
+ for n in os.listdir(du)[:200]:
+ p = os.path.join(du, n)
+ if n == "main.log" or (os.path.isdir(p) and os.path.exists(os.path.join(p, "main.log"))):
+ runs += 1
+ m = _mtime(os.path.join(p, "main.log") if os.path.isdir(p) else p)
+ oldest = m if oldest is None or (m and m < oldest) else oldest
+ media = _read1("/var/log/installer/media-info") or ""
+ mv = re.search(r"\b(\d\d\.\d\d)", media)
+ cur = _os_release().get("VERSION_ID")
+ installed = mv.group(1) if mv else None
+ upgraded = bool(installed and cur and installed != cur)
+ return {"present": True, "count": runs + (1 if upgraded and not runs else 0), "dist_upgrade_runs": runs,
+ "installed_release": installed, "current_release": cur, "oldest": _iso(oldest)}
+
+
+def _xbel_count(path, cap=8 << 20):
+ try:
+ with open(path, "rb") as f:
+ return f.read(cap).count(b"<bookmark ")
+ except OSError:
+ return None
+
+
+@lp("age.footprint_counts", level="L1", family="install_age")
+def footprint_counts(h, facts):
+ """Lived-in counts: dpkg packages, snaps, flatpaks, user .desktop entries, recent-files entries, dot-dirs."""
+ snaps = [n for n in (os.listdir("/snap") if os.path.isdir("/snap") else []) if n not in ("bin", "README")]
+ fl_sys = h.count_dir("/var/lib/flatpak/app", 5000)
+ fl_user = h.count_dir(os.path.join(_home(), ".local/share/flatpak/app"), 5000)
+ dots = [n for n in h.list_dir(_home(), 2000) if n.startswith(".")]
+ return {"present": True, "dpkg_packages": len(_dpkg_names(h)), "snaps": len(snaps),
+ "flatpaks": max(fl_sys, 0) + max(fl_user, 0),
+ "user_desktop_entries": max(h.count_dir(os.path.join(_home(), ".local/share/applications"), 5000), 0),
+ "recent": _xbel_count(os.path.join(_home(), ".local/share/recently-used.xbel")),
+ "home_dot_entries": len(dots)}
+
+
+def _nm_profiles(h):
+ """NetworkManager profiles via nmcli: (type, autoconnect, last-used epoch). Names are never requested."""
+ def load():
+ if not _which("nmcli"):
+ return None
+ out = _run(h, ["nmcli", "-t", "-f", "TYPE,AUTOCONNECT,TIMESTAMP", "connection", "show"], 3000)
+ if out is None:
+ return None
+ rows = []
+ for line in out.splitlines()[:2000]:
+ p = line.split(":")
+ if len(p) >= 3:
+ try:
+ ts = int(p[2])
+ except ValueError:
+ ts = 0
+ rows.append({"type": p[0], "autoconnect": p[1] == "yes", "last": ts or None})
+ return rows
+ return _cached(h, "nm_profiles", load)
+
+
+def _nm_kind(t):
+ t = t.lower()
+ if "wireless" in t or t == "wifi":
+ return "wireless"
+ if "ethernet" in t:
+ return "wired"
+ if t in ("vpn", "wireguard"):
+ return t
+ if t in ("bridge", "loopback", "tun", "bond", "vlan"):
+ return "virtual"
+ if "gsm" in t or "cdma" in t:
+ return "mobile"
+ return t or "other"
+
+
+@lp("net.history", level="L2", family="install_age", tier="T1", gate="os.install_date")
+def net_history(h, facts):
+ """NetworkManager profile counts by type, first-created (profile file birth) and last-used dates. No names."""
+ rows = _nm_profiles(h) or []
+ d = "/etc/NetworkManager/system-connections"
+ births = [b for b in (_birth(os.path.join(d, n)) for n in h.list_dir(d, 1000)) if b]
+ if not rows and not births:
+ return None
+ by_type = collections.Counter(_nm_kind(r["type"]) for r in rows)
+ last = [r["last"] for r in rows if r["last"]]
+ return {"present": True, "networks": len(rows), "wireless": by_type.get("wireless", 0), "by_type": dict(by_type),
+ "first_created": _iso(min(births)) if births else None, "last_created": _iso(max(births)) if births else None,
+ "last_connected": _iso(max(last)) if last else None}
+
+
+@lp("setup.system_log_oldest", level="L2", family="install_age", gate="os.install_date", collect="extended")
+def setup_system_log_oldest(h, facts):
+ """Oldest system record: first journal boot, wtmp start and oldest dpkg.log line after the image build."""
+ out = {}
+ if _which("journalctl"):
+ txt = _run(h, ["journalctl", "--list-boots", "-q", "--no-pager", "-n", "1000"], 4000) or ""
+ lines = [l for l in txt.splitlines() if l.strip()]
+ if lines:
+ m = re.search(r"(\w{3} \d{4}-\d\d-\d\d \d\d:\d\d:\d\d)", lines[0])
+ out["journal_first_boot"] = m.group(1)[4:] if m else None
+ out["journal_boots"] = len(lines)
+ w = _wtmp(h)
+ if w and w.get("begins"):
+ out["wtmp_begins"] = w["begins"]
+ dates = [v for k, v in out.items() if k in ("journal_first_boot", "wtmp_begins") and v]
+ if not out:
+ return None
+ out["present"] = True
+ out["oldest"] = min(dates)[:19] if dates else None
+ return out
+
+
+def _dpkg_log_lines(max_bytes=12 << 20):
+ total = 0
+ for p in _dpkg_logs():
+ try:
+ opener = gzip.open if p.endswith(".gz") else open
+ with opener(p, "rt", encoding="utf-8", errors="replace") as f:
+ for line in f:
+ total += len(line)
+ if total > max_bytes:
+ return
+ yield line
+ except (OSError, EOFError):
+ continue
+
+
+def _apt_history(max_bytes=8 << 20):
+ """(month, requested_by_uid, action) per apt run from /var/log/apt/history.log*. Package names never kept."""
+ runs, total = [], 0
+ me = os.getuid()
+ for p in sorted(glob.glob("/var/log/apt/history.log*"), reverse=True):
+ try:
+ opener = gzip.open if p.endswith(".gz") else open
+ with opener(p, "rt", encoding="utf-8", errors="replace") as f:
+ cur = {}
+ for line in f:
+ total += len(line)
+ if total > max_bytes:
+ break
+ if line.startswith("Start-Date:"):
+ cur = {"month": line[12:19], "by_me": False, "by_other": False, "action": None}
+ runs.append(cur)
+ elif line.startswith("Requested-By:"):
+ m = re.search(r"\((\d+)\)", line)
+ if m:
+ cur["by_me" if int(m.group(1)) == me else "by_other"] = True
+ elif line.startswith("Commandline:"):
+ m = re.search(r"\b(install|remove|purge|upgrade|full-upgrade|dist-upgrade|autoremove)\b", line)
+ cur["action"] = m.group(1) if m else "other"
+ elif not cur.get("action") and line.startswith(("Install:", "Upgrade:", "Remove:")):
+ cur["action"] = line.split(":", 1)[0].lower()
+ except (OSError, EOFError):
+ continue
+ return runs
+
+
+@lp("setup.dpkg_history", level="L2", family="install_age", tier="T1", gate="os.install_date", collect="extended")
+def setup_dpkg_history(h, facts):
+ """Package install/upgrade/remove counts per month from dpkg.log* and apt runs by requester (me vs other)."""
+ by_month = collections.defaultdict(collections.Counter)
+ first = last = None
+ for line in _dpkg_log_lines():
+ m = re.match(r"(\d{4}-\d\d)-\d\d \d\d:\d\d:\d\d (install|upgrade|remove|purge) ", line)
+ if not m:
+ continue
+ by_month[m.group(1)][m.group(2)] += 1
+ ts = line[:19]
+ first = ts if first is None or ts < first else first
+ last = ts if last is None or ts > last else last
+ apt = _apt_history()
+ if not by_month and not apt:
+ return None
+ apt_month = collections.defaultdict(collections.Counter)
+ for r in apt:
+ apt_month[r["month"]][r["action"] or "other"] += 1
+ cand = _install_candidates()
+ inst = cand.get("installer_dir") or cand.get("root_fs")
+ inst_month = time.strftime("%Y-%m", time.localtime(inst)) if inst else ""
+ installs_months = sorted(k for k, c in by_month.items() if c.get("install") and k >= inst_month)
+ return {"present": True, "first": first, "last": last,
+ "image_build_entries": sum(sum(c.values()) for k, c in by_month.items() if inst_month and k < inst_month),
+ "dpkg_by_month": {k: dict(v) for k, v in sorted(by_month.items())},
+ "installs_since_os_install": sum(c.get("install", 0) for k, c in by_month.items() if k >= inst_month),
+ "months_spread": len(installs_months),
+ "apt_runs": len(apt), "apt_runs_by_me": sum(1 for r in apt if r["by_me"]),
+ "apt_runs_by_other_user": sum(1 for r in apt if r["by_other"]),
+ "apt_runs_unattended": sum(1 for r in apt if not r["by_me"] and not r["by_other"]),
+ "apt_by_month": {k: dict(v) for k, v in sorted(apt_month.items())}}
+
+
+# ================================================================ locale
+
+def _plasma_locale():
+ return _ini(_read(os.path.join(_home(), ".config/plasma-localerc")) or "")
+
+
+def _user_locale():
+ pl = _plasma_locale()
+ cfg = (pl.get("Formats") or {}).get("LANG")
+ sysd = _kv(_read("/etc/default/locale") or _read("/etc/locale.conf") or "")
+ env = os.environ.get("LC_ALL") or os.environ.get("LC_TIME") or os.environ.get("LANG")
+ chosen = cfg or sysd.get("LC_TIME") or sysd.get("LANG") or env
+ return chosen, {"plasma_formats": cfg, "system_default": sysd.get("LANG"), "env": env}
+
+
+_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 _locale
+ chosen, src = _user_locale()
+ if not chosen:
+ return None
+ d = {"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
+ tf = d.get("time_format") or ""
+ d["clock_24h"] = ("%H" in tf or "%T" in tf) if tf else None
+ country = (d["locale"] or "").split("-")[-1]
+ d["metric"] = country not in _IMPERIAL if "-" in (d["locale"] or "") else None
+ d["utf8"] = "utf-8" in chosen.lower() or "utf8" in chosen.lower()
+ return d
+
+
+@lp("locale.system", level="L1", family="locale")
+def locale_system(h, facts):
+ """System default locale (/etc/default/locale) and generated locales."""
+ sysd = _kv(_read("/etc/default/locale") or _read("/etc/locale.conf") or "")
+ gen = [l.split()[0] for l in (_read("/etc/locale.gen") or "").splitlines() if l.strip() and not l.startswith("#")]
+ supported = _read("/var/lib/locales/supported.d/en") or ""
+ if not sysd and not gen:
+ return None
+ return {"present": True, "lang": sysd.get("LANG"), "locale": _bcp47(sysd.get("LANG")),
+ "overrides": sorted(k for k in sysd if k.startswith("LC_")), "generated": len(gen) or None,
+ "supported_d_lines": len(supported.splitlines()) or None}
+
+
+@lp("lang.ui", level="L1", family="locale")
+def lang_ui(h, facts):
+ """UI language: LANGUAGE / Plasma Translations / LANG; installed language packs from dpkg."""
+ pl = _plasma_locale()
+ tr = (pl.get("Translations") or {}).get("LANGUAGE")
+ env_lang = os.environ.get("LANGUAGE")
+ chosen = (tr or env_lang or "").split(":")[0] or _user_locale()[0]
+ if not chosen:
+ return None
+ packs = sorted({n.replace("language-pack-", "").split("-base")[0] for n in _dpkg_names(h)
+ if n.startswith("language-pack-") and not n.startswith("language-pack-gnome")
+ and not n.startswith("language-pack-kde")})
+ return {"present": True, "language": _bcp47(chosen), "user": _bcp47(chosen),
+ "system": _bcp47(_kv(_read("/etc/default/locale") or "").get("LANG")), "packs": packs,
+ "source": "plasma" if tr else "LANGUAGE" if env_lang else "LANG"}
+
+
+@lp("lang.user_list", level="L1", family="locale")
+def lang_user_list(h, facts):
+ """Ordered UI language preference list (LANGUAGE or Plasma Translations)."""
+ pl = _plasma_locale()
+ raw = (pl.get("Translations") or {}).get("LANGUAGE") or os.environ.get("LANGUAGE") or ""
+ langs = [_bcp47(x) for x in raw.split(":") if x]
+ if not langs:
+ return None
+ return {"present": True, "languages": langs, "count": len(langs)}
+
+
+def _xkb():
+ sysk = _kv(_read("/etc/default/keyboard") or "")
+ kx = _ini(_read(os.path.join(_home(), ".config/kxkbrc")) or "").get("Layout") or {}
+ return sysk, kx
+
+
+@lp("kbd.layouts", level="L1", family="locale")
+def kbd_layouts(h, facts):
+ """Keyboard layouts: Plasma kxkbrc LayoutList, else /etc/default/keyboard XKBLAYOUT; IME frameworks."""
+ sysk, kx = _xkb()
+ user = [x for x in (kx.get("LayoutList") or "").split(",") if x] if kx.get("Use", "true") != "false" else []
+ system = [x for x in (sysk.get("XKBLAYOUT") or "").split(",") if x]
+ variants = [x for x in (kx.get("VariantList") or sysk.get("XKBVARIANT") or "").split(",")]
+ lays = user or system
+ if not lays:
+ return None
+ out = [{"klid": l, "name": l + (f"({variants[i]})" if i < len(variants) and variants[i] else "")}
+ for i, l in enumerate(lays)]
+ ime = [n for n, p in (("fcitx5", "/usr/bin/fcitx5"), ("ibus", "/usr/bin/ibus-daemon"), ("fcitx", "/usr/bin/fcitx"))
+ if os.path.exists(p)]
+ return {"present": True, "layouts": out, "count": len(out), "source": "kxkbrc" if user else "etc_default_keyboard",
+ "model": kx.get("Model") or sysk.get("XKBMODEL"), "ime": bool(ime), "ime_frameworks": ime}
+
+
+@lp("kbd.scancode_map", level="L1", family="locale")
+def kbd_scancode_map(h, facts):
+ """Key remaps: XKB options (ctrl:nocaps, caps:escape, ...) in kxkbrc or /etc/default/keyboard, keyd/interception."""
+ sysk, kx = _xkb()
+ opts = [o for o in ((kx.get("Options") or "") + "," + (sysk.get("XKBOPTIONS") or "")).split(",") if o]
+ opts = sorted(set(o for o in opts if not o.startswith("grp_led")))
+ tools = [n for n, p in (("keyd", "/etc/keyd"), ("interception", "/etc/interception"), ("kmonad", "/usr/bin/kmonad"),
+ ("xremap", "/usr/bin/xremap"), ("hwdb", "/etc/udev/hwdb.d")) if os.path.exists(p)
+ and (n != "hwdb" or any(f.endswith(".hwdb") for f in os.listdir(p)))]
+ remapped = bool([o for o in opts if not o.startswith(("grp:", "terminate:"))] or tools)
+ return {"present": remapped, "remapped": remapped, "options": opts, "tools": tools}
+
+
+@lp("tz.zone", level="L1", family="locale")
+def tz_zone(h, facts):
+ """Time zone from /etc/localtime (or /etc/timezone) and the current UTC offset."""
+ z = None
+ try:
+ tgt = os.readlink("/etc/localtime")
+ m = re.search(r"zoneinfo/(.+)$", tgt)
+ z = m.group(1) if m else None
+ except OSError:
+ pass
+ z = z or _read1("/etc/timezone") or os.environ.get("TZ")
+ off = time.localtime().tm_gmtoff // 60
+ if not z:
+ return None
+ return {"present": True, "zone": z, "utc_offset_min": off, "bias_min": -off,
+ "abbrev": time.strftime("%Z"), "rtc_local": "LOCAL" in (_read("/etc/adjtime") or "")}
+
+
+@lp("tz.auto", level="L1", family="locale")
+def tz_auto(h, facts):
+ """Automatic time: NTP service enabled (timesyncd/chrony/ntpd) and Plasma ktimezoned; no auto time zone source."""
+ en = _enabled_units()
+ svc = [s for s in ("systemd-timesyncd.service", "chrony.service", "chronyd.service", "ntp.service", "ntpsec.service")
+ if s in en]
+ return {"present": True, "ntp": bool(svc), "ntp_services": [s.split(".")[0] for s in svc],
+ "auto_time_zone": None, "geoclue": os.path.exists("/usr/libexec/geoclue")}
+
+
+# ================================================================ shell_prefs
+
+def _kdeglobals():
+ return _ini(_read(os.path.join(_home(), ".config/kdeglobals")) or "")
+
+
+def _appletsrc():
+ return _ini(_read(os.path.join(_home(), ".config/plasma-org.kde.plasma.desktop-appletsrc"), 2 << 20) or "")
+
+
+@lp("theme.dark", level="L1", family="shell_prefs")
+def theme_dark(h, facts):
+ """Dark mode: KDE colour scheme / look-and-feel, GTK prefer-dark, GNOME color-scheme (dconf not parsed)."""
+ kg = _kdeglobals()
+ scheme = (kg.get("General") or {}).get("ColorScheme") or ""
+ laf = (kg.get("KDE") or {}).get("LookAndFeelPackage") or ""
+ gtk = _ini(_read(os.path.join(_home(), ".config/gtk-3.0/settings.ini")) or "").get("Settings") or {}
+ gtk_dark = gtk.get("gtk-application-prefer-dark-theme") in ("1", "true")
+ gtk_theme = gtk.get("gtk-theme-name") or ""
+ kde = bool(kg)
+ if not kde and not gtk:
+ return None
+ dark = "dark" in (scheme + laf).lower() or gtk_dark or "dark" in gtk_theme.lower()
+ return {"present": True, "apps_dark": dark, "system_dark": dark, "kde_color_scheme": scheme or ("Breeze (default)" if kde else None),
+ "kde_look_and_feel": laf or None, "gtk_prefer_dark": gtk_dark, "gtk_theme": gtk_theme or None,
+ "icon_theme": (kg.get("Icons") or {}).get("Theme") or gtk.get("gtk-icon-theme-name")}
+
+
+@lp("theme.wallpaper", level="L1", family="shell_prefs")
+def theme_wallpaper(h, facts):
+ """Plasma desktop wallpaper: stock (/usr/share/wallpapers or unset) vs custom. Path never emitted."""
+ ap = _appletsrc()
+ imgs = [v.get("Image") for s, v in ap.items() if s.endswith("[Wallpaper][org.kde.image][General]") and v.get("Image")]
+ plugins = [v.get("wallpaperplugin") for s, v in ap.items() if v.get("wallpaperplugin")]
+ if not ap:
+ return None
+ stock = all(i.replace("file://", "").startswith(("/usr/share/wallpapers", "/usr/share/backgrounds")) for i in imgs)
+ return {"present": True, "default": stock and all(p in (None, "org.kde.image") for p in plugins),
+ "stock": stock, "custom_images": sum(1 for i in imgs if not i.replace("file://", "").startswith("/usr/share")),
+ "plugins": sorted(set(p for p in plugins if p))}
+
+
+@lp("pins.taskbar", level="L1", family="shell_prefs")
+def pins_taskbar(h, facts):
+ """Plasma task manager pinned launchers (application ids)."""
+ ap = _appletsrc()
+ pins = []
+ for s, v in ap.items():
+ if "launchers" in v and v["launchers"]:
+ pins += [x.replace("applications:", "").replace("preferred://", "pref:").replace(".desktop", "")
+ for x in v["launchers"].split(",") if x]
+ if not ap:
+ return None
+ return {"present": True, "count": len(pins), "pins": pins[:30]}
+
+
+@lp("shell.explorer_prefs", level="L1", family="shell_prefs")
+def explorer_prefs(h, facts):
+ """File manager and dialog prefs: hidden files shown (kdeglobals/dolphinrc), single-click, Dolphin customised."""
+ kg = _kdeglobals()
+ dr = _ini(_read(os.path.join(_home(), ".config/dolphinrc")) or "")
+ fd = kg.get("KFileDialog Settings") or {}
+ kde = kg.get("KDE") or {}
+ if not kg and not dr:
+ return None
+ return {"present": True, "show_hidden_dialog": fd.get("Show hidden files") == "true",
+ "single_click": kde.get("SingleClick", "true" if kg else None),
+ "dolphin_sections": len(dr), "dolphin_show_full_path": (dr.get("General") or {}).get("ShowFullPath")}
+
+
+@lp("shell.login_shell", level="L1", family="shell_prefs")
+def login_shell(h, facts):
+ """Login shell from /etc/passwd for the invoking user; zsh/fish framework and prompt presence."""
+ me = _me()
+ if me is None:
+ return None
+ fw = [n for n, p in (("oh-my-zsh", ".oh-my-zsh"), ("powerlevel10k", ".p10k.zsh"), ("prezto", ".zprezto"),
+ ("zinit", ".local/share/zinit"), ("starship", ".config/starship.toml"),
+ ("oh-my-bash", ".oh-my-bash"), ("fish", ".config/fish"), ("tmux", ".tmux.conf"))
+ if os.path.exists(os.path.join(_home(), p))]
+ return {"present": True, "shell": os.path.basename(me.pw_shell), "frameworks": fw,
+ "changed_from_default": os.path.basename(me.pw_shell) not in ("bash", "sh")}
+
+
+@lp("shell.desktop_env", level="L1", family="shell_prefs")
+def desktop_env(h, facts):
+ """Desktop environment: installed X11/Wayland sessions, display manager, current session type env."""
+ xs = [n[:-8] for n in h.list_dir("/usr/share/xsessions", 50) if n.endswith(".desktop")]
+ ws = [n[:-8] for n in h.list_dir("/usr/share/wayland-sessions", 50) if n.endswith(".desktop")]
+ dm = os.path.basename(_read1("/etc/X11/default-display-manager") or "") or None
+ if not xs and not ws and not dm:
+ return {"present": False, "headless": True}
+ return {"present": True, "x11_sessions": xs, "wayland_sessions": ws, "display_manager": dm,
+ "current_desktop": os.environ.get("XDG_CURRENT_DESKTOP"), "session_type": os.environ.get("XDG_SESSION_TYPE"),
+ "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]}
+
+
+# ================================================================ health
+
+def _crash_app(mangled):
+ """apport names encode the executable path with '/' -> '_': _usr_bin_kwin_x11 -> kwin_x11."""
+ for sep in ("_libexec_", "_sbin_", "_bin_", "_games_"):
+ if sep in mangled:
+ return mangled.rsplit(sep, 1)[1]
+ return mangled.rsplit("_", 1)[-1]
+
+
+def _crash_files():
+ rows = []
+ for n in os.listdir("/var/crash")[:2000] if os.path.isdir("/var/crash") else []:
+ p = os.path.join("/var/crash", n)
+ m = re.match(r"(.+)\.(\d+)\.crash$", n)
+ if m:
+ rows.append({"app": _crash_app(m.group(1)), "uid": int(m.group(2)), "mtime": _mtime(p)})
+ return rows
+
+
+def _kdump_dirs():
+ out = []
+ for n in os.listdir("/var/crash")[:2000] if os.path.isdir("/var/crash") else []:
+ if re.match(r"\d{12}$", n) and os.path.isdir(os.path.join("/var/crash", n)):
+ out.append(_mtime(os.path.join("/var/crash", n)))
+ return out
+
+
+def _coredumps():
+ rows = []
+ for n in os.listdir("/var/lib/systemd/coredump")[:5000] if os.path.isdir("/var/lib/systemd/coredump") else []:
+ m = re.match(r"core\.(.+?)\.(\d+)\.[0-9a-f]+\.\d+\.(\d+)", n)
+ if m:
+ rows.append({"app": m.group(1), "uid": int(m.group(2)), "mtime": int(m.group(3)) / 1e6})
+ return rows
+
+
+@lp("health.journal", level="L1", family="health")
+def health_journal(h, facts):
+ """System journal readable by the invoking user (root, adm or systemd-journal group): gate for journal probes."""
+ if not _which("journalctl"):
+ return None
+ try:
+ groups = {grp.getgrgid(g).gr_name for g in os.getgroups()}
+ except KeyError:
+ groups = set()
+ system = os.geteuid() == 0 or bool(groups & {"adm", "systemd-journal", "wheel"})
+ return {"present": True, "system_journal_readable": system, "persistent": os.path.isdir("/var/log/journal")}
+
+
+@lp("health.dumps", level="L1", family="health", tier="T1")
+def health_dumps(h, facts):
+ """Crash records: kernel dumps (kdump dirs, pstore), apport .crash and systemd-coredump files; counts and dates."""
+ now = time.time()
+ me = os.getuid()
+ cr = _crash_files()
+ cd = _coredumps()
+ kd = [m for m in _kdump_dirs() if m]
+ pstore = len(h.list_dir("/var/lib/systemd/pstore", 500))
+ apps = cr + cd
+ if not apps and not kd and not os.path.isdir("/var/crash"):
+ return None
+ recent = [r for r in apps if r["mtime"] and now - r["mtime"] <= 30 * 86400]
+ return {"present": True, "count_30d": sum(1 for m in kd if now - m <= 30 * 86400), "kernel_dumps": len(kd),
+ "pstore_records": pstore, "app_crash_files": len(cr), "coredumps": len(cd),
+ "app_crashes_30d": len(recent), "mine_30d": sum(1 for r in recent if r["uid"] == me),
+ "other_users_30d": sum(1 for r in recent if r["uid"] != me),
+ "newest": _iso(max([r["mtime"] for r in apps if r["mtime"]] + kd, default=None)),
+ "apport_enabled": _kv(_read("/etc/default/apport") or "").get("enabled") == "1"}
+
+
+@lp("health.wer", level="L2", family="health", tier="T1", gate="health.dumps", collect="extended")
+def health_wer(h, facts):
+ """Per-app crashes for the invoking user (apport + systemd-coredump file names); other users counted only."""
+ me = os.getuid()
+ rows = _crash_files() + _coredumps()
+ mine = [r for r in rows if r["uid"] == me]
+ by = collections.Counter(r["app"] for r in mine)
+ last = {}
+ for r in mine:
+ last[r["app"]] = max(last.get(r["app"]) or 0, r["mtime"] or 0)
+ top = [[a, n, _iso(last.get(a))] for a, n in by.most_common(10)]
+ return {"present": bool(rows), "total": len(rows), "mine": len(mine), "other_users": len(rows) - len(mine),
+ "crashes_by_app": top, "max_repeat": top[0][1] if top else 0}
+
+
+_HW_ERR = [("mce", r"mce: \[Hardware Error\]|Machine check"), ("nvidia_xid", r"NVRM: Xid"),
+ ("amdgpu", r"amdgpu.*(ring .* timeout|GPU reset|page fault)"), ("i915", r"i915.*(GPU HANG|reset)"),
+ ("pcie_aer", r"AER: .*error"), ("edac", r"EDAC .*(CE|UE)"), ("disk_io", r"I/O error, dev|blk_update_request"),
+ ("oops_panic", r"Oops|Kernel panic|BUG: |general protection fault"), ("oom_kill", r"Out of memory: Killed process")]
+
+
+def _kernel_errs(h):
+ def load():
+ if not _which("journalctl"):
+ return None
+ pat = "|".join(p for _, p in _HW_ERR)
+ out = _run(h, ["journalctl", "-k", "-q", "--no-pager", "-S", "-30d", "-n", "500", "-o", "short-unix",
+ "-g", pat], 5000)
+ if out is None:
+ return None
+ c = collections.Counter()
+ for line in out.splitlines():
+ for k, p in _HW_ERR:
+ if re.search(p, line):
+ c[k] += 1
+ break
+ return c
+ return _cached(h, "kernel_errs", load)
+
+
+@lp("health.whea_gpu", level="L2", family="health", tier="T1", gate="health.journal", collect="extended")
+def health_whea_gpu(h, facts):
+ """Kernel hardware/GPU errors in 30 d (journalctl -k): MCE, NVIDIA Xid, amdgpu/i915 resets, PCIe AER, EDAC."""
+ c = _kernel_errs(h)
+ if c is None:
+ return None
+ hw = sum(c.get(k, 0) for k in ("mce", "nvidia_xid", "amdgpu", "i915", "pcie_aer", "edac"))
+ return {"present": True, "count_30d": hw, "by_class_30d": dict(c), "window": "30d", "cap": 500}
+
+
+@lp("health.journal_errors", level="L2", family="health", tier="T1", gate="health.journal", collect="extended")
+def journal_errors(h, facts):
+ """System journal in 30 d: error-priority count (capped), top 5 identifiers, OOM kills, kernel oops, failed units."""
+ idout = _run(h, ["journalctl", "-q", "--no-pager", "-S", "-30d", "-p", "3", "-n", "5000", "-o", "short"], 5000)
+ if idout is None:
+ return None
+ ids = collections.Counter()
+ for line in (idout or "").splitlines():
+ m = re.match(r"\S+\s+\d+\s+[\d:]+\s+\S+\s+([^\[:\s]+)", line) or re.match(r"\S+\s+\S+\s+([^\[:\s]+)", line)
+ if m:
+ ids[m.group(1)] += 1
+ c = _kernel_errs(h) or {}
+ failed = _run(h, ["systemctl", "list-units", "--no-legend", "--no-pager", "--state=failed", "--plain"], 3000) or ""
+ n = sum(ids.values())
+ return {"present": True, "errors_30d": n, "capped": n >= 5000, "top_identifiers": ids.most_common(5),
+ "oom_kills_30d": c.get("oom_kill", 0), "kernel_oops_30d": c.get("oops_panic", 0),
+ "disk_io_errors_30d": c.get("disk_io", 0), "failed_units": sum(1 for l in failed.splitlines() if l.strip())}
+
+
+# ================================================================ usage
+
+@lp("boot.uptime", level="L1", family="usage")
+def boot_uptime(h, facts):
+ """Uptime from /proc/uptime and boot time; sleep-vs-shutdown habit input."""
+ t = (_read1("/proc/uptime") or "").split()
+ if not t:
+ return None
+ up = float(t[0])
+ return {"present": True, "uptime_h": round(up / 3600, 1), "boot_time": _iso(time.time() - up),
+ "idle_ratio": round(float(t[1]) / up / (os.cpu_count() or 1), 2) if len(t) > 1 and up else None}
+
+
+def _last(h, args):
+ if not _which("last"):
+ return None
+ return _run(h, ["last", "-w", "--time-format", "iso", *args], 4000)
+
+
+_ISO_RX = r"(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d[+-]\d\d:?\d\d)"
+
+
+def _wtmp(h):
+ """System boot/shutdown records from wtmp via last -x: newest first."""
+ def load():
+ out = _last(h, ["-x", "-n", "5000", "reboot", "shutdown"])
+ if out is None:
+ return None
+ recs = []
+ begins = None
+ for line in out.splitlines():
+ if line.startswith("wtmp begins"):
+ m = re.search(_ISO_RX, line)
+ begins = m.group(1) if m else line[12:].strip()
+ continue
+ m = re.match(r"(reboot|shutdown)\s+system (?:boot|down)\s+(\S+)\s+" + _ISO_RX + r"(?:\s+-\s+(\S+))?", line)
+ if m:
+ recs.append({"kind": m.group(1), "kernel": m.group(2), "t": m.group(3), "end": m.group(4)})
+ return {"records": recs, "begins": begins}
+ return _cached(h, "wtmp", load)
+
+
+def _power(h):
+ """Boot history + unclean-shutdown split shared by eventlog.power_history and l3.power_event_split."""
+ def load():
+ w = _wtmp(h)
+ if not w:
+ return None
+ recs = w["records"]
+ now = dt.datetime.now().astimezone()
+ boots = [r for r in recs if r["kind"] == "reboot"]
+ hours = [0] * 24
+ boots30 = 0
+ unclean = []
+ for i, r in enumerate(recs):
+ if r["kind"] != "reboot":
+ continue
+ t = _parse_iso(r["t"])
+ if t:
+ hours[t.hour] += 1
+ boots30 += (now - t).days < 30
+ older = recs[i + 1] if i + 1 < len(recs) else None
+ if older is not None and older["kind"] == "reboot":
+ unclean.append(r["t"])
+ elif r.get("end") == "crash":
+ unclean.append(r["t"])
+ kernels = collections.Counter(r["kernel"] for r in boots)
+ resumes = None
+ if _which("journalctl"):
+ out = _run(h, ["journalctl", "-k", "-q", "--no-pager", "-S", "-30d", "-n", "2000", "-o", "short-unix",
+ "-g", "PM: suspend exit|PM: hibernation exit"], 4000)
+ resumes = len([l for l in (out or "").splitlines() if l.strip()]) if out is not None else None
+ kd = [m for m in _kdump_dirs() if m]
+ pstore = len(h.list_dir("/var/lib/systemd/pstore", 500))
+ crash = min(len(unclean), len(kd) + pstore)
+ return {"boots": len(boots), "shutdowns": sum(1 for r in recs if r["kind"] == "shutdown"), "boots_30d": boots30,
+ "resumes_30d": resumes, "hours": hours, "unclean": unclean, "crash": crash,
+ "span": [recs[-1]["t"] if recs else None, recs[0]["t"] if recs else None], "begins": w["begins"],
+ "kernels_booted": len(kernels)}
+ return _cached(h, "power", load)
+
+
+@lp("eventlog.power_history", level="L2", family="usage", tier="T1", gate="boot.uptime", collect="extended")
+def eventlog_power_history(h, facts):
+ """wtmp boots/shutdowns (last -x), boots in 30 d, boot-hour histogram, unclean shutdowns, suspend resumes (journal -k)."""
+ p = _power(h)
+ if not p:
+ return None
+ n_unclean = len(p["unclean"])
+ return {"present": bool(p["boots"]), "boots": p["boots"], "shutdowns": p["shutdowns"], "boots_30d": p["boots_30d"],
+ "resumes_30d": p["resumes_30d"], "os_start_hour_hist": p["hours"], "span": p["span"],
+ "system_log_oldest": p["begins"], "unclean_shutdowns": n_unclean, "kernels_booted": p["kernels_booted"],
+ "kp41_split": {"crash": p["crash"], "button_held": 0, "power_removed": n_unclean - p["crash"]}}
+
+
+@lp("l3.power_event_split", level="L2", family="usage", tier="T1", gate="boot.uptime", collect="extended")
+def power_event_split(h, facts):
+ """Unclean shutdowns (reboot record with no shutdown before it) split into crash (kdump/pstore evidence) vs
+ power_removed (no crash record: switch-off, hard reset or VM kill). Linux records no button-held marker."""
+ p = _power(h)
+ if not p:
+ return None
+ now = dt.datetime.now().astimezone()
+ ages = [(now - t).days for t in (_parse_iso(x) for x in p["unclean"]) if t]
+ crash = p["crash"]
+ removed = len(p["unclean"]) - crash
+ r30 = sum(1 for a in ages if a <= 30)
+ return {"present": True, "via": "wtmp", "events": len(p["unclean"]), "crash": crash, "button_held": 0,
+ "power_removed": removed, "crash_30d": min(crash, r30), "button_held_30d": 0,
+ "power_removed_30d": max(0, r30 - crash), "health_flag_crash_30d": crash > 0 and r30 > 0,
+ "power_off_habit_hint": removed >= 3, "timeline": [x[:10] for x in p["unclean"][:60]],
+ "note": "linux: cause of an unclean shutdown is not recorded; crash needs a kdump/pstore record"}
+
+
+def _my_logins(h):
+ def load():
+ me = _me()
+ if me is None:
+ return None
+ out = _last(h, ["-n", "5000", me.pw_name])
+ if out is None:
+ return None
+ rows = []
+ for line in out.splitlines():
+ m = re.match(r"(\S+)\s+(\S+)\s+(?:(?!\d{4}-)(\S+)\s+)?" + _ISO_RX + r"\s+(?:-\s+(\S+)(?:\s+\(([^)]+)\))?|(still logged in|gone - no logout))?", line)
+ if not m or m.group(1) != me.pw_name:
+ continue
+ rows.append({"tty": m.group(2), "from": m.group(3) or "", "t": m.group(4), "end": m.group(5), "dur": m.group(6)})
+ return rows
+ return _cached(h, "my_logins", load)
+
+
+def _src_kind(frm):
+ if re.fullmatch(r":\d+(\.\d+)?", frm):
+ return "x_display_terminal"
+ if frm in ("-", "0.0.0.0"):
+ return "local_tty"
+ if frm.startswith("tty") or frm == "login":
+ return "local_tty"
+ m = re.fullmatch(r"(\d+)\.(\d+)\.\d+\.\d+", frm)
+ if m:
+ a, b = int(m.group(1)), int(m.group(2))
+ if a == 100 and 64 <= b <= 127:
+ return "remote_tailscale"
+ if a == 10 or (a == 172 and 16 <= b <= 31) or (a == 192 and b == 168):
+ return "remote_lan"
+ return "remote_public"
+ if ":" in frm:
+ return "remote_ipv6"
+ return "remote_other"
+
+
+@lp("eventlog.security_logons", level="L2", family="usage", tier="T1", gate="boot.uptime", collect="extended")
+def security_logons(h, facts):
+ """Invoking user's logins from wtmp (last USER): sessions by source kind, 30 d count, hour histogram, lastlog.
+ IP addresses and hostnames are never emitted. x_display_terminal = terminal on an X display (local or VNC)."""
+ rows = _my_logins(h)
+ if rows is None:
+ return None
+ now = dt.datetime.now().astimezone()
+ kinds, hours = collections.Counter(), [0] * 24
+ n30 = 0
+ for r in rows:
+ k = "local_tty" if r["tty"].startswith("tty") and r["from"] in ("", "-") else _src_kind(r["from"] or "-")
+ kinds[k] += 1
+ t = _parse_iso(r["t"])
+ if t:
+ hours[t.hour] += 1
+ n30 += (now - t).days < 30
+ ll = None
+ me = _me()
+ if me and _which("lastlog"):
+ out = _run(h, ["lastlog", "-u", me.pw_name], 2000) or ""
+ lines = out.strip().splitlines()
+ if len(lines) >= 2:
+ ll = "never" if "Never logged in" in lines[1] else lines[1][-31:].strip()
+ return {"present": bool(rows), "events": len(rows), "sessions_30d": n30, "by_source": dict(kinds),
+ "interactive_unlock": kinds.get("local_tty", 0), "x_display_terminals": kinds.get("x_display_terminal", 0),
+ "remote_interactive": sum(v for k, v in kinds.items() if k.startswith("remote")),
+ "hours": hours,
+ "span": [rows[-1]["t"] if rows else None, rows[0]["t"] if rows else None], "lastlog": ll}
+
+
+@lp("lsm.sessions", level="L2", family="usage", tier="T1", gate="boot.uptime", collect="extended")
+def lsm_sessions(h, facts):
+ """First and latest login of the invoking user in wtmp, wtmp start, and the user's live logind sessions."""
+ rows = _my_logins(h)
+ w = _wtmp(h)
+ if rows is None and not w:
+ return None
+ live = []
+ me = _me()
+ if me and _which("loginctl"):
+ out = _run(h, ["loginctl", "list-sessions", "--no-legend"], 2000) or ""
+ for line in out.splitlines():
+ p = line.split()
+ if len(p) >= 3 and p[1] == str(me.pw_uid):
+ live.append(p[0])
+ types = collections.Counter()
+ for sid in live[:10]:
+ kv = _kv(_run(h, ["loginctl", "show-session", sid, "-p", "Type", "-p", "Remote"], 1500) or "")
+ types[(kv.get("Type") or "?") + ("/remote" if kv.get("Remote") == "yes" else "")] += 1
+ return {"present": True, "first": rows[-1]["t"] if rows else None, "last": rows[0]["t"] if rows else None,
+ "wtmp_begins": (w or {}).get("begins"), "live_sessions": len(live), "live_by_type": dict(types)}
+
+
+@lp("usage.scheduled_jobs", level="L2", family="usage", tier="T1", gate="boot.uptime", collect="extended")
+def scheduled_jobs(h, facts):
+ """Scheduled work: own crontab lines, own systemd user timers/enabled services, system timers (counts only)."""
+ cron = None
+ if _which("crontab"):
+ out = _run(h, ["crontab", "-l"], 2000)
+ if out is not None:
+ lines = [l for l in out.splitlines() if l.strip() and not l.lstrip().startswith("#")]
+ cron = {"lines": len(lines), "operator_excluded": sum(1 for l in lines if OPERATOR_RX.search(l)),
+ "reboot_jobs": sum(1 for l in lines if l.startswith("@reboot"))}
+ cron["lines"] -= cron["operator_excluded"]
+ ut = _run(h, ["systemctl", "--user", "list-timers", "--all", "--no-legend", "--no-pager"], 2000)
+ uu = _run(h, ["systemctl", "--user", "list-unit-files", "--state=enabled", "--no-legend", "--no-pager"], 2000)
+ st = _run(h, ["systemctl", "list-timers", "--all", "--no-legend", "--no-pager"], 2000)
+ own_units = [n for n in h.list_dir(os.path.join(_home(), ".config/systemd/user"), 200) if n.endswith((".service", ".timer"))]
+ local_timers = [n for n in h.list_dir("/etc/systemd/system", 1000) if n.endswith(".timer")]
+ cnt = lambda o: None if o is None else sum(1 for l in o.splitlines() if l.strip())
+ return {"present": True, "crontab": cron, "user_timers": cnt(ut), "user_enabled_units": cnt(uu),
+ "user_custom_unit_files": len([n for n in own_units if not OPERATOR_RX.search(n)]),
+ "system_timers": cnt(st), "system_local_timers": len(local_timers),
+ "cron_d_files": len([n for n in h.list_dir("/etc/cron.d", 200) if not n.startswith(".")])}
+
+
+def _kam():
+ return os.path.join(_home(), ".local/share/kactivitymanagerd/resources/database")
+
+
+@lp("usage.kde_activity_db", level="L1", family="usage")
+def kde_activity_db(h, facts):
+ """KDE activity manager usage database present (resource open events per app)."""
+ m = h.meta(_kam())
+ if not m.get("present"):
+ return None
+ w = h.meta(_kam() + "-wal")
+ return {"present": True, "bytes": m["bytes"], "wal_bytes": w.get("bytes"), "mtime": m["mtime"]}
+
+
+@lp("usage.kde_activity", level="L2", family="usage", tier="T1", gate="usage.kde_activity_db", collect="extended")
+def kde_activity(h, facts):
+ """KDE ResourceEvent aggregates per initiating app: events, open hours, 30 d events, hour histogram. Paths never read out."""
+ rows = h.sqlite(_kam(), "SELECT initiatingAgent, start, end FROM ResourceEvent ORDER BY start DESC LIMIT 200000")
+ if rows is None:
+ return {"present": False, "error": "unreadable"}
+ now = time.time()
+ by, hrs, n30 = collections.Counter(), collections.Counter(), 0
+ hours = [0] * 24
+ first = last = None
+ for agent, s, e in rows:
+ if not s:
+ continue
+ by[agent] += 1
+ if e and e > s:
+ hrs[agent] += min(e - s, 12 * 3600)
+ hours[time.localtime(s).tm_hour] += 1
+ n30 += now - s <= 30 * 86400
+ first = s if first is None or s < first else first
+ last = s if last is None or s > last else last
+ return {"present": bool(by), "events": sum(by.values()), "events_30d": n30, "apps": len(by),
+ "top_apps": [[a, n, round(hrs[a] / 3600, 1)] for a, n in by.most_common(10)], "hours": hours,
+ "first": _iso(first), "last": _iso(last), "via": h.last_via}
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.py
new file mode 100644
index 00000000000..53104d56fcb
--- /dev/null
+++ b/optional-skills/productivity/initiate-setup/scripts/userscan/userscan/specs/usage_gaming.py
@@ -0,0 +1,2332 @@
+"""Usage habits, gaming, media, hardware and health probes (Windows).
+
+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.
+"""
+from __future__ import annotations
+
+import collections
+import datetime as dt
+import json
+import os
+import re
+import struct
+import sys
+import threading
+import time
+
+from userscan.registry import probe, ps_probe
+
+_T0 = time.time()
+_LOCK = threading.Lock()
+_CACHE: dict = {}
+
+_NOISE = re.compile(r"(?i)(\\hn-e2e(\\|$)|\\ns960(\\|$)|\\ns923[^\\]*(\\|$)|\\lhm(\\|$)|\\shots(\\|$)|user-insights-lab|"
+ r"\\hermes-(?!agent)[^\\]*\\|\\userscan\\|\\uv\\python\\|\\cache\\scratch\\)")
+_DOW = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
+_FT_EPOCH = dt.datetime(1601, 1, 1, tzinfo=dt.timezone.utc)
+
+
+# ----------------------------------------------------------------- helpers
+
+def _noise(path: str) -> bool:
+ return bool(path) and bool(_NOISE.search(path))
+
+
+def _base(p):
+ if not p:
+ return p
+ return p.replace("/", "\\").rstrip("\\").rsplit("\\", 1)[-1]
+
+
+def _ft(ft):
+ if not ft or ft <= 0 or ft > 0x7FFFFFFFFFFFFFFF:
+ return None
+ try:
+ return (_FT_EPOCH + dt.timedelta(microseconds=ft // 10)).astimezone()
+ except (OverflowError, ValueError):
+ return None
+
+
+def _iso(d):
+ if d is None:
+ return None
+ if isinstance(d, (int, float)):
+ if d <= 0:
+ return None
+ d = dt.datetime.fromtimestamp(d).astimezone()
+ return d.isoformat(timespec="seconds")
+
+
+def _days_ago(ts):
+ return None if not ts else round((time.time() - ts) / 86400, 1)
+
+
+def _grid():
+ return [[0] * 24 for _ in range(7)]
+
+
+def _grid_out(g, scale=1.0, nd=1):
+ return {_DOW[i]: [round(v / scale, nd) for v in g[i]] for i in range(7)}
+
+
+def _env(name, default=""):
+ return os.environ.get(name, default)
+
+
+def _paths():
+ home = os.path.expanduser("~")
+ return {
+ "HOME": home, "LAD": _env("LOCALAPPDATA", os.path.join(home, "AppData", "Local")),
+ "RAD": _env("APPDATA", os.path.join(home, "AppData", "Roaming")),
+ "PD": _env("ProgramData", r"C:\ProgramData"), "PF": _env("ProgramFiles", r"C:\Program Files"),
+ "PF86": _env("ProgramFiles(x86)", r"C:\Program Files (x86)"), "WIN": _env("SystemRoot", r"C:\Windows"),
+ }
+
+
+def _ex(p):
+ try:
+ return os.path.exists(p)
+ except (OSError, ValueError):
+ return False
+
+
+def _mtime(p):
+ try:
+ return int(os.path.getmtime(p))
+ except OSError:
+ return None
+
+
+def _read(p, limit=8_000_000):
+ try:
+ with open(p, "rb") as f:
+ raw = f.read(limit)
+ except OSError:
+ return None
+ for enc in ("utf-8-sig", "utf-16", "mbcs", "latin-1"):
+ try:
+ return raw.decode(enc)
+ except (UnicodeDecodeError, LookupError):
+ continue
+ return raw.decode("utf-8", "replace")
+
+
+def _winreg():
+ import winreg
+ return winreg
+
+
+def _hive(path):
+ w = _winreg()
+ return {"HKLM": w.HKEY_LOCAL_MACHINE, "HKCU": w.HKEY_CURRENT_USER}[path[:4]], path[5:]
+
+
+def _reg_values(path, max_values=5000):
+ """{name: value} for one key, or {} on miss."""
+ w = _winreg()
+ root, sub = _hive(path)
+ out = {}
+ try:
+ with w.OpenKey(root, sub) as k:
+ i = 0
+ while i < max_values:
+ try:
+ n, v, _ = w.EnumValue(k, i)
+ except OSError:
+ break
+ out[n] = v
+ i += 1
+ except OSError:
+ return {}
+ return out
+
+
+def _reg_keys(h, path, limit=5000):
+ return (h.reg(path) or [])[:limit]
+
+
+def _cached(key, fn):
+ with _LOCK:
+ if key not in _CACHE:
+ _CACHE[key] = {"lock": threading.Lock(), "done": False, "value": None}
+ slot = _CACHE[key]
+ with slot["lock"]:
+ if not slot["done"]:
+ try:
+ slot["value"] = fn()
+ except Exception as e:
+ slot["value"] = {"error": f"{type(e).__name__}: {e}"}
+ slot["done"] = True
+ return slot["value"]
+
+
+def _uninstall(h):
+ def load():
+ out = []
+ for base in (r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
+ r"HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall",
+ r"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"):
+ for sk in _reg_keys(h, base, 3000):
+ v = _reg_values(base + "\\" + sk, 60)
+ if v.get("DisplayName"):
+ out.append({"name": str(v["DisplayName"]), "version": str(v.get("DisplayVersion") or ""),
+ "date": str(v.get("InstallDate") or "")})
+ return out
+ return _cached(("uninstall", h.l0.get("run_id")), load) or []
+
+
+def _unmatch(h, pattern):
+ rx = re.compile(pattern, re.I)
+ seen, out = set(), []
+ idx = _uninstall(h)
+ for e in idx if isinstance(idx, list) else []:
+ if rx.search(e["name"]) and e["name"] not in seen:
+ seen.add(e["name"])
+ out.append({"name": e["name"], "version": e["version"] or None, "install_date": e["date"] or None})
+ return out
+
+
+# ================================================================= USAGE (L1, registry + files)
+
+@probe(id="boot.uptime", level="L1", family="usage", tier="T0", collect="core")
+def boot_uptime(h, facts):
+ """Uptime from GetTickCount64 and derived boot time; sleep-vs-shutdown habit input."""
+ import ctypes
+ k32 = ctypes.WinDLL("kernel32")
+ k32.GetTickCount64.restype = ctypes.c_ulonglong
+ ms = int(k32.GetTickCount64())
+ boot = dt.datetime.now().astimezone() - dt.timedelta(milliseconds=ms)
+ return {"present": True, "uptime_h": round(ms / 3.6e6, 1), "boot_time": _iso(boot)}
+
+
+@probe(id="wu.active_hours", level="L1", family="usage", tier="T0", collect="core")
+def wu_active_hours(h, facts):
+ """Windows Update active hours (user-set or learned): the hours the machine expects to be in use."""
+ v = _reg_values(r"HKLM\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings", 200)
+ if not v:
+ return None
+ keys = ("ActiveHoursStart", "ActiveHoursEnd", "SmartActiveHoursState", "SmartActiveHoursStart", "SmartActiveHoursEnd")
+ out = {k: v.get(k) for k in keys if k in v}
+ if not out:
+ return None
+ return {"present": True, **out}
+
+
+@probe(id="srum.present", level="L1", family="usage", tier="T0", collect="core")
+def srum_present(h, facts):
+ """SRUM database presence and size; gates the SRUM subtree."""
+ m = h.meta(r"C:\Windows\System32\sru\SRUDB.dat")
+ return m if m.get("present") else None
+
+
+@probe(id="userassist.focus", level="L1", family="usage", tier="T1", collect="core")
+def userassist_focus(h, facts):
+ """Lifetime per-app run count and focus time from UserAssist (ROT13 names); cheapest screen-time source."""
+ import codecs
+ w = _winreg()
+ root = r"Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist"
+ apps = collections.defaultdict(lambda: [0, 0, 0, None])
+ noise = 0
+ try:
+ w.OpenKey(w.HKEY_CURRENT_USER, root).Close()
+ except OSError:
+ return None
+ for g in _reg_keys(h, "HKCU\\" + root, 50):
+ for name, data in _reg_values("HKCU\\" + root + "\\" + g + "\\Count", 3000).items():
+ name = codecs.decode(name, "rot13")
+ if not isinstance(data, bytes) or len(data) < 68 or name.startswith("UEME_"):
+ continue
+ if _noise(name):
+ noise += 1
+ continue
+ runc, focc, focms = struct.unpack_from("<III", data, 4)
+ last = _ft(struct.unpack_from("<Q", data, 60)[0])
+ a = apps[_base(name)]
+ a[0] += runc
+ a[1] += focc
+ a[2] += focms
+ if last and (a[3] is None or last > a[3]):
+ a[3] = last
+ if not apps:
+ return None
+ lasts = [a[3] for a in apps.values() if a[3]]
+ by_focus = sorted(apps.items(), key=lambda kv: -kv[1][2])
+ by_run = sorted(apps.items(), key=lambda kv: -kv[1][0])
+ return {"present": True, "entries": len(apps), "noise_filtered": noise,
+ "total_focus_h": round(sum(a[2] for a in apps.values()) / 3.6e6, 1),
+ "top_focus_h": [[n, round(a[2] / 3.6e6, 2)] for n, a in by_focus[:15] if a[2]],
+ "top_runs": [[n, a[0]] for n, a in by_run[:10] if a[0]],
+ "oldest_last_run": _iso(min(lasts)) if lasts else None,
+ "newest_last_run": _iso(max(lasts)) if lasts else None}
+
+
+@probe(id="featureusage.appswitched", level="L1", family="usage", tier="T1", collect="core")
+def featureusage_appswitched(h, facts):
+ """Taskbar switch/launch counts per app (lifetime) from Explorer FeatureUsage."""
+ root = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FeatureUsage"
+ out = {}
+ for sub in ("AppSwitched", "AppLaunch", "ShowJumpView"):
+ c = collections.Counter()
+ for n, v in _reg_values(root + "\\" + sub, 3000).items():
+ if isinstance(v, int) and not _noise(n):
+ c[_base(n)] += v
+ if c:
+ out[sub] = {"entries": len(c), "total": sum(c.values()), "top": c.most_common(10)}
+ return {"present": True, **out} if out else None
+
+
+@probe(id="bam.last_run", level="L1", family="usage", tier="T1", collect="core")
+def bam_last_run(h, facts):
+ """Background Activity Moderator: last-run time per exe across SIDs; counts in 24 h / 7 d."""
+ root = r"HKLM\SYSTEM\CurrentControlSet\Services\bam\State\UserSettings"
+ sids = _reg_keys(h, root, 100)
+ if not sids:
+ return None
+ rows = {}
+ noise = 0
+ own = _base(sys.executable).lower()
+ for sid in sids:
+ for n, v in _reg_values(root + "\\" + sid, 2000).items():
+ if not isinstance(v, bytes) or len(v) < 8:
+ continue
+ t = _ft(struct.unpack_from("<Q", v, 0)[0])
+ if not t:
+ continue
+ if _noise(n) or t.timestamp() >= _T0 - 5 and _base(n).lower() in (own, "uv.exe", "conhost.exe", "sshd.exe"):
+ noise += 1
+ continue
+ b = _base(n)
+ if b not in rows or t > rows[b]:
+ rows[b] = t
+ if not rows:
+ return None
+ now = dt.datetime.now().astimezone()
+ srt = sorted(rows.items(), key=lambda kv: kv[1], reverse=True)
+ return {"present": True, "sids": len(sids), "exes": len(rows), "noise_filtered": noise,
+ "used_24h": sum(1 for _, t in srt if now - t < dt.timedelta(days=1)),
+ "used_7d": sum(1 for _, t in srt if now - t < dt.timedelta(days=7)),
+ "oldest": _iso(srt[-1][1]), "recent": [[a, _iso(t)] for a, t in srt[:10]]}
+
+
+@probe(id="pca.launchdic", level="L1", family="usage", tier="T1", collect="core")
+def pca_launchdic(h, facts):
+ """Program Compatibility Assistant launch dictionary: distinct exes launched with last-launch dates."""
+ txt = _read(os.path.join(_paths()["WIN"], r"appcompat\pca\PcaAppLaunchDic.txt"), 2_000_000)
+ if not txt:
+ return None
+ rows, noise = [], 0
+ for line in txt.splitlines()[:20000]:
+ if "|" not in line:
+ continue
+ path, ts = line.rsplit("|", 1)
+ if _noise(path):
+ noise += 1
+ continue
+ try:
+ t = dt.datetime.strptime(ts.strip()[:19], "%Y-%m-%d %H:%M:%S").replace(tzinfo=dt.timezone.utc).astimezone()
+ except ValueError:
+ continue
+ rows.append((_base(path), t))
+ if not rows:
+ return None
+ rows.sort(key=lambda r: r[1], reverse=True)
+ now = dt.datetime.now().astimezone()
+ return {"present": True, "entries": len(rows), "noise_filtered": noise,
+ "oldest": _iso(rows[-1][1]), "newest": _iso(rows[0][1]),
+ "launched_30d": sum(1 for _, t in rows if now - t < dt.timedelta(days=30)),
+ "recent": [[a, _iso(t)] for a, t in rows[:10]]}
+
+
+@probe(id="prefetch.stat", level="L1", family="usage", tier="T0", collect="core")
+def prefetch_stat(h, facts):
+ """Prefetch directory stat (admin): file count, distinct exes, oldest and newest mtime."""
+ d = os.path.join(_paths()["WIN"], "Prefetch")
+ n, exes, oldest, newest = 0, set(), None, None
+ try:
+ with os.scandir(d) as it:
+ for e in it:
+ if n >= 5000:
+ break
+ if not e.name.lower().endswith(".pf"):
+ continue
+ n += 1
+ exes.add(e.name.rsplit("-", 1)[0])
+ try:
+ m = e.stat().st_mtime
+ except OSError:
+ continue
+ oldest = m if oldest is None or m < oldest else oldest
+ newest = m if newest is None or m > newest else newest
+ except OSError:
+ return None
+ if not n:
+ return None
+ return {"present": True, "files": n, "distinct_exes": len(exes), "oldest": _iso(oldest), "newest": _iso(newest)}
+
+
+def _mam(data):
+ import ctypes
+ from ctypes import byref, c_ulong
+ ntdll = ctypes.WinDLL("ntdll")
+ sig, usize = struct.unpack_from("<II", data, 0)
+ fmt = (sig >> 24) & 0x0F
+ wsa, wsb = c_ulong(0), c_ulong(0)
+ ntdll.RtlGetCompressionWorkSpaceSize(ctypes.c_ushort(fmt), byref(wsa), byref(wsb))
+ ws = ctypes.create_string_buffer(wsa.value)
+ out = ctypes.create_string_buffer(usize)
+ fin = c_ulong(0)
+ src = data[8:]
+ rc = ntdll.RtlDecompressBufferEx(ctypes.c_ushort(fmt), out, c_ulong(usize), src, c_ulong(len(src)), byref(fin), ws)
+ if rc != 0:
+ raise OSError(f"RtlDecompressBufferEx 0x{rc & 0xffffffff:x}")
+ return out.raw[: fin.value]
+
+
+@probe(id="prefetch.run_counts", level="L2", family="usage", tier="T1", collect="deep", gate="prefetch.stat",
+ timeout_ms=20000)
+def prefetch_run_counts(h, facts):
+ """Per-exe run counts and last-8 run times from every .pf (MAM decompress); launch-hour grid."""
+ d = os.path.join(_paths()["WIN"], "Prefetch")
+ runs, errors = collections.Counter(), 0
+ grid = _grid()
+ files = [e.path for e in os.scandir(d) if e.name.lower().endswith(".pf")][:3000]
+ for f in files:
+ try:
+ with open(f, "rb") as fh:
+ data = fh.read(4_000_000)
+ if data[:3] == b"MAM":
+ data = _mam(data)
+ ver = struct.unpack_from("<I", data, 0)[0]
+ if data[4:8] != b"SCCA":
+ errors += 1
+ continue
+ exe = data[0x10:0x10 + 60].decode("utf-16-le", "replace").split("\0")[0]
+ if ver >= 26:
+ metrics_off = struct.unpack_from("<I", data, 0x54)[0]
+ rc_off = 0xD0 if (ver == 26 or metrics_off >= 0x130) else 0xC8
+ times = [struct.unpack_from("<Q", data, 0x80 + 8 * i)[0] for i in range(8)]
+ else:
+ rc_off = 0x98
+ times = [struct.unpack_from("<Q", data, 0x80)[0]]
+ runs[exe] += struct.unpack_from("<I", data, rc_off)[0]
+ for x in times:
+ t = _ft(x)
+ if t:
+ grid[t.weekday()][t.hour] += 1
+ except Exception:
+ errors += 1
+ if not runs:
+ return None
+ return {"present": True, "files": len(files), "parse_errors": errors, "total_runs": sum(runs.values()),
+ "top_run_counts": runs.most_common(20), "launch_grid": _grid_out(grid, 1, 0)}
+
+
+# ----------------------------------------------------------------- SRUM (deep): one shared load, many probes
+
+_SRUM_TABLES = {
+ "timeline": ("{5C8CF1C7-7257-4F13-B223-970EF5939312}",
+ ["AppId", "UserId", "EndTime", "DurationMS", "InFocusS", "UserInputS", "KeyboardInputS", "AudioOutS"]),
+ "resource": ("{D10CA2FE-6FCF-4F6D-848E-B2E99266FA89}", ["TimeStamp", "AppId", "UserId", "ForegroundCycleTime"]),
+ "network": ("{973F5D5C-1D90-4944-BE8E-24B94231A174}", ["AppId", "BytesSent", "BytesRecvd"]),
+}
+
+
+class _Ese:
+ MOVE_FIRST = -2147483648
+
+ def __init__(self, path, tmpdir, tag):
+ import ctypes
+ from ctypes import byref, c_size_t, c_ulong
+ self.ct = ctypes
+ self.e = ctypes.WinDLL("esent.dll")
+ self.path = path.encode("mbcs")
+ with open(path, "rb") as f:
+ hdr = f.read(512)
+ self.page_size = struct.unpack_from("<I", hdr, 236)[0]
+ self.inst, self.ses, self.db = c_size_t(0), c_size_t(0), c_ulong(0)
+ os.makedirs(tmpdir, exist_ok=True)
+ tmp = (tmpdir.rstrip("\\") + "\\").encode("mbcs")
+ e = self.e
+ self._chk(e.JetCreateInstanceA(byref(self.inst), tag.encode()), "CreateInstance")
+ for pid, s, n in ((0, tmp, 0), (1, tmp, 0), (2, tmp, 0), (34, b"Off", 0), (64, None, self.page_size)):
+ self._chk(e.JetSetSystemParameterA(byref(self.inst), c_size_t(0), c_ulong(pid), c_size_t(n), s), f"Param{pid}")
+ self._chk(e.JetInit(byref(self.inst)), "Init")
+ self._chk(e.JetBeginSessionA(self.inst, byref(self.ses), None, None), "BeginSession")
+ self._chk(e.JetAttachDatabaseA(self.ses, self.path, c_ulong(1)), "Attach")
+ self._chk(e.JetOpenDatabaseA(self.ses, self.path, None, byref(self.db), c_ulong(1)), "OpenDb")
+
+ @staticmethod
+ def _chk(rc, what):
+ if rc < 0:
+ raise OSError(f"ESE {what} rc={rc}")
+
+ def _retrieve(self, t, colid, size=64):
+ ct = self.ct
+ buf = ct.create_string_buffer(size)
+ act = ct.c_ulong(0)
+ rc = self.e.JetRetrieveColumn(self.ses, t, ct.c_ulong(colid), buf, ct.c_ulong(size), ct.byref(act), ct.c_ulong(0), None)
+ if rc == 1004:
+ return None
+ if rc == 1006:
+ return self._retrieve(t, colid, act.value)
+ if rc < 0:
+ raise OSError(f"Retrieve rc={rc}")
+ return buf.raw[: act.value]
+
+ def _columns(self, t):
+ ct = self.ct
+
+ class COLLIST(ct.Structure):
+ _fields_ = [("cbStruct", ct.c_ulong), ("tableid", ct.c_size_t), ("cRecord", ct.c_ulong)] + [
+ (n, ct.c_ulong) for n in (
+ "idPres", "idName", "idColid", "idColtyp", "idCountry", "idLangid", "idCp", "idCollate",
+ "idCbMax", "idGrbit", "idDefault", "idBaseTable", "idBaseColumn", "idDefName")]
+ cl = COLLIST()
+ cl.cbStruct = ct.sizeof(cl)
+ self._chk(self.e.JetGetTableColumnInfoA(self.ses, t, None, ct.byref(cl), ct.c_ulong(ct.sizeof(cl)), ct.c_ulong(1)), "ColInfo")
+ cols = {}
+ tt = ct.c_size_t(cl.tableid)
+ rc = self.e.JetMove(self.ses, tt, ct.c_long(self.MOVE_FIRST), ct.c_ulong(0))
+ while rc >= 0:
+ name = self._retrieve(tt, cl.idName, 256).split(b"\0")[0].decode("mbcs")
+ cid = struct.unpack("<I", self._retrieve(tt, cl.idColid))[0]
+ typ = struct.unpack("<I", self._retrieve(tt, cl.idColtyp))[0]
+ cols[name] = (cid, typ)
+ rc = self.e.JetMove(self.ses, tt, ct.c_long(1), ct.c_ulong(0))
+ self.e.JetCloseTable(self.ses, tt)
+ return cols
+
+ @staticmethod
+ def _decode(raw, typ):
+ if raw is None:
+ return None
+ if typ in (1, 2):
+ return raw[0]
+ fmt = {3: "<h", 17: "<H", 4: "<i", 14: "<I", 5: "<q", 15: "<q", 6: "<f", 7: "<d"}.get(typ)
+ if fmt:
+ return struct.unpack(fmt, raw)[0]
+ if typ == 8:
+ return dt.datetime(1899, 12, 30, tzinfo=dt.timezone.utc) + dt.timedelta(days=struct.unpack("<d", raw)[0])
+ return raw
+
+ def rows(self, name, want, max_rows=400000):
+ ct = self.ct
+ t = ct.c_size_t(0)
+ if self.e.JetOpenTableA(self.ses, self.db, name.encode(), None, ct.c_ulong(0), ct.c_ulong(4), ct.byref(t)) < 0:
+ return None
+ cols = self._columns(t)
+ use = [(c, cols[c]) for c in want if c in cols]
+ out = []
+ rc = self.e.JetMove(self.ses, t, ct.c_long(self.MOVE_FIRST), ct.c_ulong(0))
+ while rc >= 0 and len(out) < max_rows:
+ out.append({c: self._decode(self._retrieve(t, cid, 64), typ) for c, (cid, typ) in use})
+ rc = self.e.JetMove(self.ses, t, ct.c_long(1), ct.c_ulong(0))
+ self.e.JetCloseTable(self.ses, t)
+ return out
+
+ def close(self):
+ ct = self.ct
+ self.e.JetCloseDatabase(self.ses, self.db, ct.c_ulong(0))
+ self.e.JetDetachDatabaseA(self.ses, self.path)
+ self.e.JetEndSession(self.ses, ct.c_ulong(0))
+ self.e.JetTerm(self.inst)
+
+
+def _sid_str(b):
+ try:
+ rev, n = b[0], b[1]
+ auth = int.from_bytes(b[2:8], "big")
+ subs = struct.unpack_from("<%dI" % n, b, 8)
+ return "S-%d-%d-" % (rev, auth) + "-".join(str(x) for x in subs)
+ except Exception:
+ return "?"
+
+
+def _srum_name(blob, idtype):
+ if blob is None:
+ return None
+ if idtype == 3:
+ return _sid_str(blob)
+ try:
+ s = blob.decode("utf-16-le").rstrip("\0")
+ except UnicodeDecodeError:
+ return blob.hex()[:16]
+ if "!" in s:
+ parts = s.split("!")
+ if s.startswith("!!") and len(parts) > 2:
+ return parts[2]
+ if len(parts) > 2 and parts[2]:
+ return parts[0].split("_")[0] + "/" + parts[2]
+ return _base(s) if "\\" in s else s
+
+
+def _srum(h):
+ """Copy (ladder incl. VSS when allowed), open with esent.dll, read idmap + 3 tables once per run."""
+ def load():
+ res = {"t": {}}
+ t = time.perf_counter()
+ allow = bool(h.l0.get("allow_vss", "--allow-vss" in sys.argv))
+ dst, rung = h.copy_locked(r"C:\Windows\System32\sru\SRUDB.dat", "SRUDB.dat", allow_vss=allow)
+ res["copy"] = {"rung": rung, "allow_vss": allow, "bytes": os.path.getsize(dst) if dst else None,
+ "ms": round((time.perf_counter() - t) * 1000, 1)}
+ if not dst:
+ return res
+ t = time.perf_counter()
+ tmp = os.path.join(h.scratch(), "esetmp")
+ ese = _Ese(dst, tmp, "userscan_" + h.l0.get("run_id", "x"))
+ res["open"] = {"page_size": ese.page_size, "ms": round((time.perf_counter() - t) * 1000, 1)}
+ try:
+ t = time.perf_counter()
+ idm = ese.rows("SruDbIdMapTable", ["IdType", "IdIndex", "IdBlob"]) or []
+ res["idmap"] = {r["IdIndex"]: _srum_name(r.get("IdBlob"), r.get("IdType")) for r in idm}
+ users = {r["IdIndex"]: _srum_name(r.get("IdBlob"), 3) for r in idm if r.get("IdType") == 3}
+ res["human"] = {k for k, v in users.items() if (v or "").startswith("S-1-5-21-")}
+ res["t"]["idmap_ms"] = round((time.perf_counter() - t) * 1000, 1)
+ res["idmap_rows"] = len(idm)
+ for key, (tbl, cols) in _SRUM_TABLES.items():
+ t = time.perf_counter()
+ res[key] = ese.rows(tbl, cols)
+ res["t"][key + "_ms"] = round((time.perf_counter() - t) * 1000, 1)
+ finally:
+ ese.close()
+ import shutil
+ shutil.rmtree(tmp, ignore_errors=True)
+ try:
+ os.remove(dst)
+ except OSError:
+ pass
+ return res
+ return _cached(("srum", h.l0.get("run_id")), load)
+
+
+@probe(id="srum.copy", level="L2", family="usage", tier="T0", collect="deep", gate="srum.present", timeout_ms=60000)
+def srum_copy(h, facts):
+ """SRUM copy ladder result: shutil, esentutl, esentutl /vss (only with --allow-vss)."""
+ s = _srum(h)
+ c = s.get("copy") or {}
+ if "error" in s:
+ return {"present": False, "error": s["error"], **c}
+ return {"present": c.get("rung") not in (None, "failed"), **c}
+
+
+@probe(id="srum.open", level="L2", family="usage", tier="T0", collect="deep", gate="srum.present", timeout_ms=60000)
+def srum_open(h, facts):
+ """esent.dll attach of the SRUM copy (read-only, recovery off)."""
+ s = _srum(h)
+ if "error" in s or "open" not in s:
+ return {"present": False, "error": s.get("error")}
+ return {"present": True, **s["open"]}
+
+
+@probe(id="srum.idmap", level="L2", family="usage", tier="T0", collect="deep", gate="srum.present", timeout_ms=60000)
+def srum_idmap(h, facts):
+ """SRUM id map: app/user id counts; the join table for every SRUM extractor."""
+ s = _srum(h)
+ if "idmap" not in s:
+ return {"present": False, "error": s.get("error")}
+ return {"present": True, "ids": s["idmap_rows"], "human_sids": len(s["human"]), "ms": s["t"].get("idmap_ms")}
+
+
+def _spread(grid, days, start, end, amount):
+ total = (end - start).total_seconds()
+ if total <= 0:
+ grid[start.weekday()][start.hour] += amount
+ days[start.date().isoformat()] += amount
+ return
+ cur = start
+ while cur < end:
+ nxt = min(end, cur.replace(minute=0, second=0, microsecond=0) + dt.timedelta(hours=1))
+ share = amount * (nxt - cur).total_seconds() / total
+ grid[cur.weekday()][cur.hour] += share
+ days[cur.date().isoformat()] += share
+ cur = nxt
+
+
+_NOT_FOCUS = re.compile(r"(?i)^(LogonUI\.exe|.*LockApp\.exe|.*\.scr|csrss\.exe)$")
+
+
+@probe(id="srum.app_timeline", level="L2", family="usage", tier="T1", collect="deep", gate="srum.present", timeout_ms=60000)
+def srum_app_timeline(h, facts):
+ """7 days of per-app focus and input seconds for human SIDs: screen time, input/focus ratio, hour grid."""
+ s = _srum(h)
+ rows = s.get("timeline")
+ if not rows:
+ return {"present": False, "error": s.get("error")}
+ idmap, human = s["idmap"], s["human"]
+ focus, inp, kbd, audio, idle = (collections.Counter() for _ in range(5))
+ gf, gi = _grid(), _grid()
+ df, di = collections.Counter(), collections.Counter()
+ tmin = tmax = None
+ for r in rows:
+ if r.get("UserId") not in human:
+ continue
+ app = idmap.get(r.get("AppId")) or "<unmapped>"
+ f = r.get("InFocusS") or 0
+ u = r.get("UserInputS") or 0
+ if _NOT_FOCUS.match(app):
+ idle[app] += f
+ f = 0
+ focus[app] += f
+ inp[app] += u
+ kbd[app] += r.get("KeyboardInputS") or 0
+ audio[app] += r.get("AudioOutS") or 0
+ end = _ft(r.get("EndTime"))
+ if end is None:
+ continue
+ start = end - dt.timedelta(milliseconds=r.get("DurationMS") or 0)
+ tmin = start if tmin is None or start < tmin else tmin
+ tmax = end if tmax is None or end > tmax else tmax
+ if f:
+ _spread(gf, df, start, end, f)
+ if u:
+ _spread(gi, di, start, end, u)
+ tf, ti = sum(focus.values()), sum(inp.values())
+ return {"present": True, "rows": len(rows), "span": [_iso(tmin), _iso(tmax)],
+ "total_focus_h": round(tf / 3600, 1), "total_input_h": round(ti / 3600, 2),
+ "input_focus_ratio": round(ti / tf, 3) if tf else None,
+ "top_focus_h": [[a, round(v / 3600, 2)] for a, v in focus.most_common(15) if v],
+ "top_input_min": [[a, round(v / 60, 1)] for a, v in inp.most_common(10) if v],
+ "top_keyboard_min": [[a, round(v / 60, 1)] for a, v in kbd.most_common(5) if v],
+ "top_audio_h": [[a, round(v / 3600, 2)] for a, v in audio.most_common(5) if v],
+ "lock_screensaver_h": round(sum(idle.values()) / 3600, 1),
+ "focus_grid_h": _grid_out(gf, 3600, 2), "input_grid_min": _grid_out(gi, 60, 1),
+ "focus_h_per_day": {d: round(v / 3600, 1) for d, v in sorted(df.items())},
+ "ms": s["t"].get("timeline_ms")}
+
+
+@probe(id="srum.app_resource", level="L2", family="usage", tier="T1", collect="deep", gate="srum.present", timeout_ms=60000)
+def srum_app_resource(h, facts):
+ """30 days of hourly foreground cycles per app: machine-on hours grid, days used, top apps by share."""
+ s = _srum(h)
+ rows = s.get("resource")
+ if not rows:
+ return {"present": False, "error": s.get("error")}
+ idmap, human = s["idmap"], s["human"]
+ fg = collections.Counter()
+ on_hours, user_hours = set(), set()
+ for r in rows:
+ ts = r.get("TimeStamp")
+ lt = ts.astimezone().replace(minute=0, second=0, microsecond=0) if isinstance(ts, dt.datetime) else None
+ if lt:
+ on_hours.add(lt)
+ if r.get("UserId") not in human:
+ continue
+ c = r.get("ForegroundCycleTime") or 0
+ fg[idmap.get(r.get("AppId")) or "<unmapped>"] += c
+ if lt and c > 0:
+ user_hours.add(lt)
+ g_on, g_user = _grid(), _grid()
+ for x in on_hours:
+ g_on[x.weekday()][x.hour] += 1
+ for x in user_hours:
+ g_user[x.weekday()][x.hour] += 1
+ tot = max(1, sum(fg.values()))
+ return {"present": True, "rows": len(rows),
+ "span": [_iso(min(on_hours)) if on_hours else None, _iso(max(on_hours)) if on_hours else None],
+ "record_hours": len(on_hours), "user_foreground_hours": len(user_hours),
+ "days_with_records": len({x.date() for x in on_hours}),
+ "days_with_user_foreground": len({x.date() for x in user_hours}),
+ "top_foreground_pct": [[a, round(c / tot * 100, 1)] for a, c in fg.most_common(15)],
+ "hours": [sum(g_user[d][hr] for d in range(7)) for hr in range(24)],
+ "record_hours_grid": _grid_out(g_on, 1, 0), "user_hours_grid": _grid_out(g_user, 1, 0),
+ "ms": s["t"].get("resource_ms")}
+
+
+_SENSITIVE_NET = re.compile(r"(?i)(torrent|qbit|utorrent|bittorrent|transmission|deluge|tixati|vuze|frostwire|"
+ r"aria2|jdownloader|warp|wireguard|openvpn|nordvpn|expressvpn|protonvpn|mullvad|surfshark)")
+
+
+@probe(id="srum.network_usage", level="L2", family="usage", tier="T1", collect="deep", gate="srum.present", timeout_ms=60000)
+def srum_network_usage(h, facts):
+ """30-day bytes per app; torrent and VPN clients are folded into one filtered total."""
+ s = _srum(h)
+ rows = s.get("network")
+ if not rows:
+ return {"present": False, "error": s.get("error")}
+ net = collections.Counter()
+ filtered = unmapped = 0
+ for r in rows:
+ app = s["idmap"].get(r.get("AppId"))
+ b = (r.get("BytesSent") or 0) + (r.get("BytesRecvd") or 0)
+ if not app:
+ unmapped += b
+ elif _SENSITIVE_NET.search(app):
+ filtered += b
+ else:
+ net[app] += b
+ return {"present": True, "rows": len(rows), "total_gb": round((sum(net.values()) + filtered + unmapped) / 1e9, 1),
+ "unmapped_gb": round(unmapped / 1e9, 1),
+ "filtered_sensitive_gb": round(filtered / 1e9, 1),
+ "top_gb": [[a, round(b / 1e9, 2)] for a, b in net.most_common(10)], "ms": s["t"].get("network_ms")}
+
+
+# ----------------------------------------------------------------- usage: event logs (PS sidecar)
+
+_EVT_NS = "{http://schemas.microsoft.com/win/2004/08/events/event}"
+
+
+def _wevt(h, log, xpath, count, newest_first=False, timeout_ms=20000):
+ """wevtutil qe as XML (no message rendering), parsed into ElementTree events. None when the query fails."""
+ import xml.etree.ElementTree as ET
+ args = ["wevtutil", "qe", log, "/q:" + xpath, "/f:xml", f"/c:{count}"]
+ if newest_first:
+ args.append("/rd:true")
+ out = h.run(args, timeout_ms=timeout_ms, text=False)
+ if out is None:
+ return None
+ try:
+ return list(ET.fromstring("<r>" + re.sub(r"<\?xml[^>]*\?>", "", out) + "</r>"))
+ except ET.ParseError:
+ return None
+
+
+def _evt_fields(ev):
+ sysn = ev.find(_EVT_NS + "System")
+ prov = sysn.find(_EVT_NS + "Provider").get("Name", "")
+ eid = int(sysn.find(_EVT_NS + "EventID").text)
+ ts = sysn.find(_EVT_NS + "TimeCreated").get("SystemTime", "")
+ try:
+ t = dt.datetime.fromisoformat(ts.rstrip("Z")[:26]).replace(tzinfo=dt.timezone.utc).astimezone()
+ except ValueError:
+ t = None
+ data = {}
+ ed = ev.find(_EVT_NS + "EventData")
+ if ed is not None:
+ for d in ed:
+ data[d.get("Name")] = d.text
+ return prov, eid, t, data
+
+
+_POWER_PROV = {"Microsoft-Windows-Kernel-General", "Microsoft-Windows-Kernel-Power", "EventLog", "User32"}
+
+
+@probe(id="eventlog.power_history", level="L2", family="usage", tier="T1", collect="extended", gate="boot.uptime",
+ timeout_ms=20000)
+def eventlog_power_history(h, facts):
+ """System-log boots, shutdowns, sleep/resume; each Kernel-Power 41 classed crash / button_held / power_removed."""
+ ids = (12, 13, 41, 42, 107, 506, 507, 1074, 6005, 6006, 6008)
+ evs = _wevt(h, "System", "*[System[(" + " or ".join(f"EventID={i}" for i in ids) + ")]]", 20000)
+ if evs is None:
+ return {"present": False, "error": "wevtutil failed"}
+ counts = collections.Counter()
+ hours = [0] * 24
+ kp = []
+ now = dt.datetime.now().astimezone()
+ boots30 = res30 = 0
+ first = last = None
+ for ev in evs:
+ try:
+ prov, eid, t, data = _evt_fields(ev)
+ except (AttributeError, ValueError):
+ continue
+ if prov not in _POWER_PROV or t is None:
+ continue
+ counts[prov.replace("Microsoft-Windows-", "") + "/" + str(eid)] += 1
+ first = t if first is None or t < first else first
+ last = t if last is None or t > last else last
+ recent = (now - t).days < 30
+ if prov == "Microsoft-Windows-Kernel-General" and eid == 12:
+ hours[t.hour] += 1
+ boots30 += recent
+ if prov == "Microsoft-Windows-Kernel-Power" and eid in (107, 507):
+ res30 += recent
+ if prov == "Microsoft-Windows-Kernel-Power" and eid == 41:
+ bc = int(data.get("BugcheckCode") or 0)
+ pb = int(data.get("PowerButtonTimestamp") or 0)
+ cls = "crash" if bc else "button_held" if pb else "power_removed"
+ kp.append({"t": _iso(t), "class": cls, "bugcheck": f"0x{bc:X}"})
+ kp.sort(key=lambda x: x["t"])
+ split = collections.Counter(x["class"] for x in kp)
+ return {"present": bool(counts), "events": sum(counts.values()), "counts": dict(counts),
+ "span": [_iso(first), _iso(last)], "boots_30d": boots30, "resumes_30d": res30,
+ "os_start_hour_hist": hours,
+ "kp41_split": {k: split.get(k, 0) for k in ("crash", "button_held", "power_removed")}, "kp41": kp[-40:]}
+
+
+@probe(id="eventlog.security_logons", level="L2", family="usage", tier="T1", collect="deep", gate="boot.uptime",
+ needs_admin=True, timeout_ms=20000)
+def eventlog_security_logons(h, facts):
+ """Security-log logons by type (2/11 console, 7 unlock, 10 RDP); 4800/4801 only if audited."""
+ evs = _wevt(h, "Security", "*[System[(EventID=4624 or EventID=4800 or EventID=4801)]]", 5000, newest_first=True)
+ if evs is None:
+ return {"present": False, "error": "wevtutil failed"}
+ by, types = collections.Counter(), collections.Counter()
+ first = last = None
+ for ev in evs:
+ try:
+ _prov, eid, t, data = _evt_fields(ev)
+ except (AttributeError, ValueError):
+ continue
+ by[str(eid)] += 1
+ if eid == 4624:
+ types[str(data.get("LogonType"))] += 1
+ if t:
+ first = t if first is None or t < first else first
+ last = t if last is None or t > last else last
+ 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).")