acrionix-cli 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2026 Acrionix Inc.
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: acrionix-cli
3
+ Version: 0.4.0
4
+ Summary: AI-native AOSP, Embedded Android, and Linux Kernel log triage & git patch synthesizer
5
+ Author-email: "Acrionix Inc." <founder@acrionix.cloud>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://acrionix.cloud
8
+ Project-URL: Documentation, https://docs.acrionix.net
9
+ Project-URL: Repository, https://github.com/acrionix-labs/acrionix-cli
10
+ Project-URL: Issues, https://github.com/acrionix-labs/acrionix-cli/issues
11
+ Keywords: android,aosp,selinux,vintf,logcat,dmesg,bsp,embedded-linux,kernel
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Debuggers
22
+ Classifier: Topic :: System :: Operating System Kernels :: Linux
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Dynamic: license-file
27
+
28
+ # acrionix-cli
29
+
30
+ **AOSP, Embedded Android, and Linux Kernel log triage & git patch synthesizer.**
31
+
32
+ Zero-dependency Python 3.10+ CLI that ingests `adb logcat`, `dmesg`, `tombstones`, SELinux (`avc: denied`), VINTF HAL errors, and DSU/GSI boot failures, maps them against your local device tree, and generates verified unified `git diff` `.patch` files.
33
+
34
+ [Website](https://acrionix.cloud) · [Live Sandbox](https://acrionix.cloud/#sandbox) · [Documentation](https://docs.acrionix.net)
35
+
36
+ ---
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ pip install acrionix-cli
42
+ ```
43
+
44
+ Or run directly from source:
45
+
46
+ ```bash
47
+ git clone https://github.com/acrionix-labs/acrionix-cli.git
48
+ cd acrionix-cli
49
+ PYTHONPATH=src python3 -m acrionix --help
50
+ ```
51
+
52
+ ## Commands
53
+
54
+ ### 1. Triage offline logs and generate a `.patch`
55
+
56
+ ```bash
57
+ acrionix triage ./boot_failure.log --tree ./device/oem/common --out fix.patch
58
+ git apply --check fix.patch
59
+ ```
60
+
61
+ Supports stdin piping too:
62
+
63
+ ```bash
64
+ adb logcat -d | acrionix triage - --out denials.patch
65
+ ```
66
+
67
+ ### 2. Inspect a live connected device (`doctor`)
68
+
69
+ ```bash
70
+ acrionix doctor --adb
71
+ # With root access (also scans dmesg, latest tombstone & SYSTEM_LAST_KMSG):
72
+ acrionix doctor --adb --root
73
+ ```
74
+
75
+ ### 3. Stream live ADB logs (`watch`)
76
+
77
+ ```bash
78
+ acrionix watch --adb --tree ./device/oem/sm8650 --out-dir ./.acrionix
79
+ ```
80
+
81
+ ### 4. Audit vendor SELinux policies for `permissive` domains
82
+
83
+ ```bash
84
+ acrionix sepolicy audit --strict ./device/oem/common/sepolicy --log ./audit.log --out enforce.patch
85
+ ```
86
+
87
+ ## Capabilities
88
+
89
+ - **Least-Privilege SELinux Synthesizer** - Converts raw `avc: denied` audits into idiomatic AOSP `.te` rules and macros (`binder_call`, `r_file_perms`, `rw_file_perms`, `r_dir_perms`) with built-in AOSP `neverallow` risk checks.
90
+ - **VINTF & HAL Compatibility Resolver** - Detects missing HIDL/AIDL entries from `hwservicemanager` / `VintfObject` and emits `manifest.xml` patches.
91
+ - **Init, Firmware & Native Tombstone Triage** - Correlates `init` exit codes, kernel `Direct firmware load ... failed with error -2` logs, and C/C++ `SIGSEGV` stack traces.
92
+ - **DSU / GSI Boot Diagnostics** - Identifies `invalid AVB footer` warnings and OEM first-boot reboot traps such as `opex_incremental_disable` under `one_shot_boot=1`.
93
+
94
+ ## Running Tests
95
+
96
+ ```bash
97
+ PYTHONPATH=src python3 -m unittest discover -s tests -v
98
+ ```
99
+
100
+ ## License
101
+
102
+ Apache-2.0 - Copyright 2026 Acrionix Inc.
@@ -0,0 +1,75 @@
1
+ # acrionix-cli
2
+
3
+ **AOSP, Embedded Android, and Linux Kernel log triage & git patch synthesizer.**
4
+
5
+ Zero-dependency Python 3.10+ CLI that ingests `adb logcat`, `dmesg`, `tombstones`, SELinux (`avc: denied`), VINTF HAL errors, and DSU/GSI boot failures, maps them against your local device tree, and generates verified unified `git diff` `.patch` files.
6
+
7
+ [Website](https://acrionix.cloud) · [Live Sandbox](https://acrionix.cloud/#sandbox) · [Documentation](https://docs.acrionix.net)
8
+
9
+ ---
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install acrionix-cli
15
+ ```
16
+
17
+ Or run directly from source:
18
+
19
+ ```bash
20
+ git clone https://github.com/acrionix-labs/acrionix-cli.git
21
+ cd acrionix-cli
22
+ PYTHONPATH=src python3 -m acrionix --help
23
+ ```
24
+
25
+ ## Commands
26
+
27
+ ### 1. Triage offline logs and generate a `.patch`
28
+
29
+ ```bash
30
+ acrionix triage ./boot_failure.log --tree ./device/oem/common --out fix.patch
31
+ git apply --check fix.patch
32
+ ```
33
+
34
+ Supports stdin piping too:
35
+
36
+ ```bash
37
+ adb logcat -d | acrionix triage - --out denials.patch
38
+ ```
39
+
40
+ ### 2. Inspect a live connected device (`doctor`)
41
+
42
+ ```bash
43
+ acrionix doctor --adb
44
+ # With root access (also scans dmesg, latest tombstone & SYSTEM_LAST_KMSG):
45
+ acrionix doctor --adb --root
46
+ ```
47
+
48
+ ### 3. Stream live ADB logs (`watch`)
49
+
50
+ ```bash
51
+ acrionix watch --adb --tree ./device/oem/sm8650 --out-dir ./.acrionix
52
+ ```
53
+
54
+ ### 4. Audit vendor SELinux policies for `permissive` domains
55
+
56
+ ```bash
57
+ acrionix sepolicy audit --strict ./device/oem/common/sepolicy --log ./audit.log --out enforce.patch
58
+ ```
59
+
60
+ ## Capabilities
61
+
62
+ - **Least-Privilege SELinux Synthesizer** - Converts raw `avc: denied` audits into idiomatic AOSP `.te` rules and macros (`binder_call`, `r_file_perms`, `rw_file_perms`, `r_dir_perms`) with built-in AOSP `neverallow` risk checks.
63
+ - **VINTF & HAL Compatibility Resolver** - Detects missing HIDL/AIDL entries from `hwservicemanager` / `VintfObject` and emits `manifest.xml` patches.
64
+ - **Init, Firmware & Native Tombstone Triage** - Correlates `init` exit codes, kernel `Direct firmware load ... failed with error -2` logs, and C/C++ `SIGSEGV` stack traces.
65
+ - **DSU / GSI Boot Diagnostics** - Identifies `invalid AVB footer` warnings and OEM first-boot reboot traps such as `opex_incremental_disable` under `one_shot_boot=1`.
66
+
67
+ ## Running Tests
68
+
69
+ ```bash
70
+ PYTHONPATH=src python3 -m unittest discover -s tests -v
71
+ ```
72
+
73
+ ## License
74
+
75
+ Apache-2.0 - Copyright 2026 Acrionix Inc.
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "acrionix-cli"
7
+ version = "0.4.0"
8
+ description = "AI-native AOSP, Embedded Android, and Linux Kernel log triage & git patch synthesizer"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ authors = [
13
+ { name = "Acrionix Inc.", email = "founder@acrionix.cloud" }
14
+ ]
15
+ keywords = ["android", "aosp", "selinux", "vintf", "logcat", "dmesg", "bsp", "embedded-linux", "kernel"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Environment :: Console",
19
+ "Intended Audience :: Developers",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Topic :: Software Development :: Debuggers",
27
+ "Topic :: System :: Operating System Kernels :: Linux"
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://acrionix.cloud"
32
+ Documentation = "https://docs.acrionix.net"
33
+ Repository = "https://github.com/acrionix-labs/acrionix-cli"
34
+ Issues = "https://github.com/acrionix-labs/acrionix-cli/issues"
35
+
36
+ [project.scripts]
37
+ acrionix = "acrionix.cli:main"
38
+
39
+ [tool.setuptools.packages.find]
40
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """Acrionix CLI - AOSP, Embedded Android & Linux Kernel log triage and patch synthesis."""
2
+
3
+ __version__ = "0.4.0"
@@ -0,0 +1,4 @@
1
+ from acrionix.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,136 @@
1
+ from __future__ import annotations
2
+
3
+ import shutil
4
+ import subprocess
5
+ from dataclasses import dataclass
6
+ from typing import Iterator
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class AdbDevice:
11
+ serial: str
12
+ state: str
13
+ model: str = ""
14
+ device: str = ""
15
+
16
+
17
+ class AdbError(RuntimeError):
18
+ pass
19
+
20
+
21
+ def build_adb_cmd(
22
+ args: list[str],
23
+ serial: str | None = None,
24
+ port: int | None = None,
25
+ ) -> list[str]:
26
+ adb_bin = shutil.which("adb")
27
+ if not adb_bin:
28
+ raise AdbError("adb binary not found on PATH. Install Android platform-tools.")
29
+ cmd = [adb_bin]
30
+ if port is not None:
31
+ cmd.extend(["-P", str(port)])
32
+ if serial:
33
+ cmd.extend(["-s", serial])
34
+ cmd.extend(args)
35
+ return cmd
36
+
37
+
38
+ def list_devices(port: int | None = None) -> list[AdbDevice]:
39
+ cmd = build_adb_cmd(["devices", "-l"], port=port)
40
+ proc = subprocess.run(cmd, capture_output=True, text=True, check=False)
41
+ if proc.returncode != 0:
42
+ raise AdbError(proc.stderr.strip() or "Failed to query adb devices.")
43
+
44
+ devices: list[AdbDevice] = []
45
+ for line in proc.stdout.splitlines()[1:]:
46
+ line = line.strip()
47
+ if not line:
48
+ continue
49
+ parts = line.split()
50
+ if len(parts) < 2:
51
+ continue
52
+ serial, state = parts[0], parts[1]
53
+ model = ""
54
+ device = ""
55
+ for token in parts[2:]:
56
+ if token.startswith("model:"):
57
+ model = token.split(":", 1)[1]
58
+ elif token.startswith("device:"):
59
+ device = token.split(":", 1)[1]
60
+ devices.append(AdbDevice(serial=serial, state=state, model=model, device=device))
61
+ return devices
62
+
63
+
64
+ def pick_device(serial: str | None = None, port: int | None = None) -> tuple[str, int | None]:
65
+ devices = list_devices(port=port)
66
+ online = [d for d in devices if d.state == "device"]
67
+ if serial:
68
+ return (serial, port)
69
+ if online:
70
+ return (online[0].serial, port)
71
+ raise AdbError(
72
+ "No online ADB devices found. Check USB debugging or pass --port / --serial."
73
+ )
74
+
75
+
76
+ def run_shell(shell_cmd: str, serial: str, port: int | None = None, timeout: int = 15) -> str:
77
+ cmd = build_adb_cmd(["shell", shell_cmd], serial=serial, port=port)
78
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
79
+ return proc.stdout
80
+
81
+
82
+ def capture_snapshot(serial: str, port: int | None = None, root: bool = False) -> tuple[dict[str, str], list[str]]:
83
+ """Collect read-only device metadata + recent logcat, dmesg, and DSU status."""
84
+ prop_script = (
85
+ "echo model=$(getprop ro.product.model);"
86
+ "echo device=$(getprop ro.product.device);"
87
+ "echo android=$(getprop ro.build.version.release);"
88
+ "echo sdk=$(getprop ro.build.version.sdk);"
89
+ "echo display=$(getprop ro.build.display.id);"
90
+ "echo selinux=$(getenforce 2>/dev/null);"
91
+ "echo kernel=$(uname -r);"
92
+ "echo slot=$(getprop ro.boot.slot_suffix);"
93
+ "echo verity=$(getprop ro.boot.veritymode);"
94
+ )
95
+ raw_props = run_shell(prop_script, serial=serial, port=port)
96
+ props: dict[str, str] = {}
97
+ for line in raw_props.splitlines():
98
+ if "=" in line:
99
+ k, v = line.split("=", 1)
100
+ props[k.strip()] = v.strip()
101
+
102
+ lines: list[str] = []
103
+ logcat_out = run_shell("logcat -d -t 500 2>/dev/null", serial=serial, port=port, timeout=20)
104
+ lines.extend(logcat_out.splitlines())
105
+
106
+ if root:
107
+ dmesg_out = run_shell("su -c 'dmesg | tail -n 300' 2>/dev/null", serial=serial, port=port, timeout=20)
108
+ lines.extend(dmesg_out.splitlines())
109
+ last_kmsg = run_shell(
110
+ "su -c 'f=$(ls -t /data/system/dropbox/SYSTEM_LAST_KMSG*.gz 2>/dev/null | head -n 1); [ -n \"$f\" ] && zcat \"$f\" | tail -n 120' 2>/dev/null",
111
+ serial=serial,
112
+ port=port,
113
+ timeout=20,
114
+ )
115
+ lines.extend(last_kmsg.splitlines())
116
+ tombstone = run_shell(
117
+ "su -c 'f=$(ls -t /data/tombstones/tombstone_* 2>/dev/null | grep -v \"\\.pb$\" | head -n 1); [ -n \"$f\" ] && head -n 45 \"$f\"' 2>/dev/null",
118
+ serial=serial,
119
+ port=port,
120
+ timeout=20,
121
+ )
122
+ lines.extend(tombstone.splitlines())
123
+
124
+ return (props, lines)
125
+
126
+
127
+ def stream_logcat(serial: str, port: int | None = None) -> Iterator[str]:
128
+ cmd = build_adb_cmd(["logcat", "-v", "threadtime"], serial=serial, port=port)
129
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
130
+ assert proc.stdout is not None
131
+ try:
132
+ for line in proc.stdout:
133
+ yield line.rstrip("\n")
134
+ finally:
135
+ proc.terminate()
136
+ proc.wait(timeout=3)
@@ -0,0 +1,281 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ import time
7
+ from pathlib import Path
8
+
9
+ from acrionix import __version__
10
+ from acrionix.adb import AdbError, capture_snapshot, pick_device, stream_logcat
11
+ from acrionix.models import AnalysisReport
12
+ from acrionix.parsers import (
13
+ DeviceTreeIndex,
14
+ audit_sepolicy_dir,
15
+ parse_crashes,
16
+ parse_selinux_denials,
17
+ parse_vintf_mismatches,
18
+ )
19
+ from acrionix.patcher import format_patch_bundle, generate_patches
20
+
21
+ USE_COLOR = sys.stdout.isatty()
22
+
23
+
24
+ def _c(text: str, code: str) -> str:
25
+ if not USE_COLOR:
26
+ return text
27
+ return f"\033[{code}m{text}\033[0m"
28
+
29
+
30
+ def analyze_lines(lines: list[str], source: str, tree_root: Path | None = None) -> AnalysisReport:
31
+ tree = DeviceTreeIndex(tree_root)
32
+ findings = []
33
+ findings.extend(parse_selinux_denials(lines))
34
+ findings.extend(parse_vintf_mismatches(lines))
35
+ findings.extend(parse_crashes(lines))
36
+
37
+ patches = generate_patches(findings, tree)
38
+ warnings = [
39
+ f"{f.title}: {f.metadata['neverallow_warning']}"
40
+ for f in findings
41
+ if f.metadata.get("neverallow_warning")
42
+ ]
43
+ return AnalysisReport(
44
+ source=source,
45
+ lines_scanned=len(lines),
46
+ findings=findings,
47
+ patches=patches,
48
+ warnings=warnings,
49
+ )
50
+
51
+
52
+ def _print_report(report: AnalysisReport, elapsed_ms: int) -> None:
53
+ print(_c("Acrionix", "1;32") + f" v{__version__} - analyzed {report.lines_scanned} lines from {report.source} ({elapsed_ms}ms)")
54
+ print()
55
+
56
+ if not report.findings:
57
+ print(_c("No critical SELinux, VINTF, init, firmware, tombstone, or DSU failures detected.", "32"))
58
+ return
59
+
60
+ print(_c(f"Findings ({len(report.findings)}):", "1;36"))
61
+ for idx, f in enumerate(report.findings, 1):
62
+ sev_color = "31" if f.severity == "critical" else ("33" if f.severity == "high" else "36")
63
+ print(f" {idx}. [{_c(f.severity.upper(), sev_color)}] {f.title}")
64
+ print(f" {f.summary}")
65
+ print(f" target: {f.target_file} ({f.partition}, {int(f.confidence * 100)}% confidence)")
66
+ if f.security_note:
67
+ print(f" note: {_c(f.security_note, '32')}")
68
+ print()
69
+
70
+ if report.warnings:
71
+ print(_c("Neverallow / Safety Warnings:", "1;33"))
72
+ for w in report.warnings:
73
+ print(f" ! {w}")
74
+ print()
75
+
76
+ if report.patches:
77
+ print(_c(f"Synthesized Git Diffs ({len(report.patches)}):", "1;32"))
78
+ for p in report.patches:
79
+ print(_c(f"--- {p.file_path} (+{p.added} -{p.removed}) ---", "1"))
80
+ for line in p.unified_diff.splitlines():
81
+ if line.startswith("+") and not line.startswith("+++"):
82
+ print(_c(line, "32"))
83
+ elif line.startswith("-") and not line.startswith("---"):
84
+ print(_c(line, "31"))
85
+ elif line.startswith("@@"):
86
+ print(_c(line, "36"))
87
+ else:
88
+ print(line)
89
+ print()
90
+
91
+
92
+ def cmd_triage(args: argparse.Namespace) -> int:
93
+ start = time.monotonic()
94
+ if args.log == "-":
95
+ lines = sys.stdin.read().splitlines()
96
+ source = "stdin"
97
+ else:
98
+ log_path = Path(args.log)
99
+ if not log_path.exists():
100
+ print(f"error: log file not found: {log_path}", file=sys.stderr)
101
+ return 2
102
+ lines = log_path.read_text(encoding="utf-8", errors="ignore").splitlines()
103
+ source = str(log_path)
104
+
105
+ tree_root = Path(args.tree) if args.tree else None
106
+ report = analyze_lines(lines, source=source, tree_root=tree_root)
107
+ elapsed_ms = int((time.monotonic() - start) * 1000)
108
+
109
+ if args.out and report.patches:
110
+ out_path = Path(args.out)
111
+ out_path.parent.mkdir(parents=True, exist_ok=True)
112
+ out_path.write_text(format_patch_bundle(report.patches), encoding="utf-8")
113
+
114
+ if args.json:
115
+ print(json.dumps(report.to_dict(), indent=2))
116
+ else:
117
+ _print_report(report, elapsed_ms)
118
+ if args.out and report.patches:
119
+ print(_c(f"Wrote unified patch -> {args.out}", "1;32"))
120
+ print(f"Verify with: git apply --check {args.out}")
121
+ return 0
122
+
123
+
124
+ def cmd_sepolicy_audit(args: argparse.Namespace) -> int:
125
+ start = time.monotonic()
126
+ sepolicy_dir = Path(args.sepolicy_dir)
127
+ if not sepolicy_dir.exists():
128
+ print(f"error: directory not found: {sepolicy_dir}", file=sys.stderr)
129
+ return 2
130
+
131
+ findings = audit_sepolicy_dir(sepolicy_dir)
132
+ if args.log:
133
+ log_path = Path(args.log)
134
+ if log_path.exists():
135
+ log_lines = log_path.read_text(encoding="utf-8", errors="ignore").splitlines()
136
+ findings.extend(parse_selinux_denials(log_lines))
137
+
138
+ tree = DeviceTreeIndex(sepolicy_dir.parent if sepolicy_dir.name == "sepolicy" else sepolicy_dir)
139
+ patches = generate_patches(findings, tree)
140
+ report = AnalysisReport(
141
+ source=str(sepolicy_dir),
142
+ lines_scanned=len(findings),
143
+ findings=findings,
144
+ patches=patches,
145
+ )
146
+ elapsed_ms = int((time.monotonic() - start) * 1000)
147
+
148
+ if args.out and patches:
149
+ Path(args.out).write_text(format_patch_bundle(patches, "Enforce vendor sepolicy"), encoding="utf-8")
150
+
151
+ if args.json:
152
+ print(json.dumps(report.to_dict(), indent=2))
153
+ else:
154
+ _print_report(report, elapsed_ms)
155
+
156
+ if args.strict and any(f.metadata.get("remove_permissive") for f in findings):
157
+ return 1
158
+ return 0
159
+
160
+
161
+ def cmd_doctor(args: argparse.Namespace) -> int:
162
+ start = time.monotonic()
163
+ try:
164
+ serial, port = pick_device(serial=args.serial, port=args.port)
165
+ except AdbError as exc:
166
+ print(f"error: {exc}", file=sys.stderr)
167
+ return 2
168
+
169
+ props, lines = capture_snapshot(serial=serial, port=port, root=args.root)
170
+ tree_root = Path(args.tree) if args.tree else None
171
+ report = analyze_lines(lines, source=f"adb:{serial}", tree_root=tree_root)
172
+ elapsed_ms = int((time.monotonic() - start) * 1000)
173
+
174
+ if args.out and report.patches:
175
+ Path(args.out).write_text(format_patch_bundle(report.patches), encoding="utf-8")
176
+
177
+ if args.json:
178
+ out = report.to_dict()
179
+ out["device"] = {"serial": serial, "props": props}
180
+ print(json.dumps(out, indent=2))
181
+ else:
182
+ print(
183
+ _c("Device:", "1;36"),
184
+ f"{props.get('model', 'unknown')} ({props.get('device', '?')}) · "
185
+ f"Android {props.get('android', '?')} (SDK {props.get('sdk', '?')}) · "
186
+ f"Kernel {props.get('kernel', '?')} · SELinux {props.get('selinux', '?')}",
187
+ )
188
+ print()
189
+ _print_report(report, elapsed_ms)
190
+ if args.out and report.patches:
191
+ print(_c(f"Wrote unified patch -> {args.out}", "1;32"))
192
+ return 0
193
+
194
+
195
+ def cmd_watch(args: argparse.Namespace) -> int:
196
+ try:
197
+ serial, port = pick_device(serial=args.serial, port=args.port)
198
+ except AdbError as exc:
199
+ print(f"error: {exc}", file=sys.stderr)
200
+ return 2
201
+
202
+ tree = DeviceTreeIndex(Path(args.tree) if args.tree else None)
203
+ out_dir = Path(args.out_dir)
204
+ print(_c("Acrionix watch", "1;32") + f" streaming adb:{serial} (Ctrl+C to stop)")
205
+ seen_titles: set[str] = set()
206
+ captured_lines: list[str] = []
207
+
208
+ try:
209
+ for line in stream_logcat(serial=serial, port=port):
210
+ captured_lines.append(line)
211
+ if len(captured_lines) > 2000:
212
+ captured_lines = captured_lines[-1000:]
213
+ findings = parse_selinux_denials([line]) + parse_vintf_mismatches([line]) + parse_crashes([line])
214
+ for f in findings:
215
+ if f.title in seen_titles:
216
+ continue
217
+ seen_titles.add(f.title)
218
+ print(f"[{_c(f.category.upper(), '36')}] {f.title}")
219
+ print(f" -> {f.summary}")
220
+ patches = generate_patches([f], tree)
221
+ if patches:
222
+ out_dir.mkdir(parents=True, exist_ok=True)
223
+ slug = f.category + "-" + str(len(seen_titles)).zfill(3) + ".patch"
224
+ patch_file = out_dir / slug
225
+ patch_file.write_text(format_patch_bundle(patches, f.title), encoding="utf-8")
226
+ print(f" -> synthesized {_c(str(patch_file), '32')}")
227
+ except KeyboardInterrupt:
228
+ print("\nStopped watching.")
229
+ return 0
230
+
231
+
232
+ def build_parser() -> argparse.ArgumentParser:
233
+ parser = argparse.ArgumentParser(
234
+ prog="acrionix",
235
+ description="Acrionix CLI - AOSP, Embedded Android & Linux Kernel log triage and git patch synthesizer",
236
+ )
237
+ parser.add_argument("--version", action="version", version=f"acrionix-cli {__version__}")
238
+ sub = parser.add_subparsers(dest="command", required=True)
239
+
240
+ p_triage = sub.add_parser("triage", help="Analyze a log file (or stdin '-') and generate git patches")
241
+ p_triage.add_argument("log", help="Path to logcat/dmesg/tombstone file, or '-' for stdin")
242
+ p_triage.add_argument("--tree", help="Path to local AOSP device/vendor tree for exact file patching")
243
+ p_triage.add_argument("--out", help="Write synthesized unified .patch file to this path")
244
+ p_triage.add_argument("--json", action="store_true", help="Output structured JSON report")
245
+ p_triage.set_defaults(func=cmd_triage)
246
+
247
+ p_doc = sub.add_parser("doctor", help="Inspect a connected ADB device (props, denials, crashes, DSU)")
248
+ p_doc.add_argument("--adb", action="store_true", help="Connect over ADB (default)")
249
+ p_doc.add_argument("--serial", help="Target ADB device serial")
250
+ p_doc.add_argument("--port", type=int, help="Custom ADB server port (e.g. 5038)")
251
+ p_doc.add_argument("--root", action="store_true", help="Use su to also inspect dmesg, tombstones & last_kmsg")
252
+ p_doc.add_argument("--tree", help="Path to local AOSP device tree")
253
+ p_doc.add_argument("--out", help="Write synthesized unified .patch file")
254
+ p_doc.add_argument("--json", action="store_true", help="Output JSON")
255
+ p_doc.set_defaults(func=cmd_doctor)
256
+
257
+ p_watch = sub.add_parser("watch", help="Stream live ADB logcat and synthesize patches on the fly")
258
+ p_watch.add_argument("--adb", action="store_true", help="Stream over ADB")
259
+ p_watch.add_argument("--serial", help="Target ADB device serial")
260
+ p_watch.add_argument("--port", type=int, help="Custom ADB server port")
261
+ p_watch.add_argument("--tree", help="Path to local AOSP device tree")
262
+ p_watch.add_argument("--out-dir", default=".acrionix", help="Directory for generated .patch files")
263
+ p_watch.set_defaults(func=cmd_watch)
264
+
265
+ p_sep = sub.add_parser("sepolicy", help="SELinux policy auditing tools")
266
+ sep_sub = p_sep.add_subparsers(dest="sepolicy_cmd", required=True)
267
+ p_audit = sep_sub.add_parser("audit", help="Scan .te policies for permissive domains and synthesize strict rules")
268
+ p_audit.add_argument("sepolicy_dir", help="Path to vendor sepolicy directory")
269
+ p_audit.add_argument("--log", help="Optional runtime audit log to synthesize replacement allow rules")
270
+ p_audit.add_argument("--strict", action="store_true", help="Exit with code 1 if any permissive domain is found")
271
+ p_audit.add_argument("--out", help="Write cleanup .patch file")
272
+ p_audit.add_argument("--json", action="store_true", help="Output JSON")
273
+ p_audit.set_defaults(func=cmd_sepolicy_audit)
274
+
275
+ return parser
276
+
277
+
278
+ def main(argv: list[str] | None = None) -> int:
279
+ parser = build_parser()
280
+ args = parser.parse_args(argv)
281
+ return int(args.func(args))