#!/bin/zsh # ============================================================================= # Odd$ Tune for Mac - performance, storage and health check for macOS. # # Measures why a Mac is slow: processor and memory use sampled over time, swap, disk activity, energy, # startup helpers that are actually running, storage (large files, old downloads and installers, # verified duplicates, rebuildable developer folders), battery, heat, backups, updates and drive health. # Writes a plain-English HTML report and a JSON file to ./Reports next to this script. # # Read-only unless you approve a change. After the scan, the Odd$ Tune Optimization Engine lists safe # actions (move old installers, duplicates or old downloads to the Trash, ask busy apps to quit, open # the right System Settings page) and advanced ones (rebuildable developer folders, Xcode DerivedData, # leftover startup helpers). Each needs your yes. Files go to the Trash, where you can put them back. # Then it measures again and shows what changed. It never empties the Trash, never deletes anything # itself, never force-quits, never touches system files and never needs your password. # # Run it from Terminal: zsh OddsTune.zsh # (Developers: this is src/OddsTune.zsh plus src/lib/*.zsh; the published file is built from them.) # --demo Build a sample report with example findings, without scanning. # --scan-only Never offer to change anything. # --no-open Do not open the report when the scan finishes. # --output DIR Folder for the report (default: Reports next to this script). # --sample SECONDS How long to measure activity (default 10, 4 to 120). # --compare FILE Compare with an earlier Odd$ Tune .json report (for example, before a restart). # --no-duplicates Skip the duplicate-file search. # --login-items Also list Login Items by name (macOS asks once whether Terminal can use System Events). # # Favorable Odds Tech Solutions - https://favorableodds.io # Built for macOS 13 Ventura and later (zsh 5.8+). Older versions may skip checks. # ============================================================================= emulate -R zsh setopt NULL_GLOB EXTENDED_GLOB NO_NOMATCH PIPE_FAIL zmodload zsh/datetime zmodload zsh/mathfunc zmodload -F zsh/stat b:zstat export LC_NUMERIC=C # "1.5 GB", not "1,5 GB", whatever the Mac's region BRAND='Odd$ Tune' COMPANY='Favorable Odds Tech Solutions' WEBSITE='https://favorableodds.io' VERSION='0.2.0' # Every file this script reads is prefixed with $R. It is empty on a real Mac; the automated # tests point it at a folder of sample files so the scan can be checked without a Mac. R=${ODDS_TUNE_ROOT:-} QUIT_WAIT=10; SETTLE_SECONDS=5 # seconds to wait for an app to quit, and before measuring again if [[ -n $R ]]; then QUIT_WAIT=${ODDS_TUNE_QUIT_WAIT:-10}; SETTLE_SECONDS=${ODDS_TUNE_SETTLE:-5}; fi SCRIPT_PATH=${0:A} SCRIPT_DIR=${SCRIPT_PATH:h} DEMO=0; NO_OPEN=0; SCAN_ONLY=0; OUTPUT_DIR=''; SAMPLE_SECONDS=10; COMPARE_FILE=''; NO_DUPLICATES=0; LOGIN_ITEMS=0 usage() { print -r -- "Usage: zsh OddsTune.zsh [--demo] [--scan-only] [--no-open] [--output DIR] [--sample SECONDS] [--compare FILE.json] [--no-duplicates] [--login-items]" } while (( $# )); do case $1 in --demo) DEMO=1 ;; --no-open) NO_OPEN=1 ;; --scan-only) SCAN_ONLY=1 ;; --output) shift; OUTPUT_DIR=${1:-} ;; --sample) shift; SAMPLE_SECONDS=${1:-} ;; --compare) shift; COMPARE_FILE=${1:-} ;; --no-duplicates) NO_DUPLICATES=1 ;; --login-items) LOGIN_ITEMS=1 ;; --version) print -r -- "$BRAND for Mac $VERSION"; exit 0 ;; --help|-h) usage; exit 0 ;; *) print -r -- "Unknown option: $1 (try --help)"; exit 2 ;; esac shift done [[ -z $OUTPUT_DIR ]] && OUTPUT_DIR="$SCRIPT_DIR/Reports" if [[ -n $R && $SAMPLE_SECONDS == <->.<-> ]] && (( SAMPLE_SECONDS >= 0.2 )); then : # tests may sample for a fraction of a second elif [[ $SAMPLE_SECONDS != <-> ]] || (( SAMPLE_SECONDS < 4 || SAMPLE_SECONDS > 120 )); then print -r -- "--sample needs a whole number of seconds from 4 to 120."; exit 2 fi if [[ -n $COMPARE_FILE ]]; then [[ $COMPARE_FILE == /* ]] || COMPARE_FILE=$PWD/$COMPARE_FILE fi # ----------------------------------------------------------------------------- # Who is running this, and on what # ----------------------------------------------------------------------------- IS_MAC=0; [[ $(uname -s 2>/dev/null) == Darwin ]] && IS_MAC=1 if (( ! IS_MAC && ! DEMO )); then print -r -- "$BRAND for Mac checks Macs only. On Windows, use Odd$ Tune for Windows. Use --demo to preview a sample report." exit 1 fi if [[ $(id -u 2>/dev/null) == 0 ]] && (( ! DEMO )); then print -r -- "Please run $BRAND without sudo. It checks your own account and never needs your password." exit 1 fi if (( ! DEMO )) && [[ -z ${HOME:-} || ! -d $R$HOME ]]; then print -r -- "Could not find your home folder, so there is nothing to check." exit 1 fi # A private scratch folder, or stop: falling back to a shared folder would let the clean-up below remove more than ours. if ! TMP=$(mktemp -d "${TMPDIR:-/tmp}/oddstune.XXXXXX") || [[ -z $TMP || ! -d $TMP ]]; then print -r -- 'Odd$ Tune could not create a temporary folder, so it stopped without checking anything. Restart the Mac and try again.' >&2 exit 1 fi trap 'rm -rf -- "$TMP"' EXIT # ---- Modules, bundled by scripts/build-tune-mac.py from desktop/odds-tune-mac/src/lib/ ---- # ==== lib/core.zsh ==== # ============================================================================= # Odd$ Tune for Mac - core: helpers, the result model and path safety. # Sourced by OddsTune.zsh. Nothing in this file reads the Mac or changes it. # ============================================================================= US=$'\x1f' # separates a key from its value RS=$'\x1e' # separates one key/value pair (or table cell) from the next GB=1000000000 # ----------------------------------------------------------------------------- # Small helpers (unchanged from v0.1.0 unless noted) # ----------------------------------------------------------------------------- step() { print -r -- " - $1" } plural() { (( $1 == 1 )) && print -rn -- "$1 $2" || print -rn -- "$1 $3" } trim() { local s=$1; s=${s##[[:space:]]#}; s=${s%%[[:space:]]#}; print -rn -- $s } h() { # HTML-encode everything that came from the Mac before it goes into the report local s=$1 s=${s//&/&}; s=${s///>}; s=${s//\"/"}; s=${s//\'/'} print -rn -- $s } j() { # JSON string, quotes included local s=$1 s=${s//\\/\\\\}; s=${s//\"/\\\"}; s=${s//$'\n'/\\n}; s=${s//$'\r'/\\r}; s=${s//$'\t'/\\t} s=${s//[[:cntrl:]]/} print -rn -- "\"$s\"" } jn() { # JSON number, or null when the value is missing or not a number local v=${1:-} if [[ $v == (|-)<->(|.<->) ]]; then print -rn -- $v; else print -rn -- null; fi } jb() { (( ${1:-0} )) && print -rn -- true || print -rn -- false } # Sizes the way Finder shows them (1 GB = 1,000,000,000 bytes). size() { local b=${1:-0} b=${b%%.*} if (( b >= GB )); then printf '%.1f GB' $(( b / 1e9 )) elif (( b >= 1000000 )); then printf '%.0f MB' $(( b / 1e6 )) elif (( b >= 1000 )); then printf '%.0f KB' $(( b / 1e3 )) else print -rn -- "$b bytes"; fi } ramsize() { printf '%.0f GB' $(( ${1:-0} / 1073741824.0 )) } # memory is sold in binary GB (16 GB = 16 x 2^30) f1() { printf '%.1f' ${1:-0} } # one decimal place f0() { printf '%.0f' ${1:-0} } # whole number isnum() { [[ ${1:-} == (|-)<->(|.<->) ]] } # Read one value from a property list (or JSON) file. Empty, and false, when missing. # On macOS 15, plutil prints "Could not extract value..." to standard output (not the error stream) when a key is # missing, so the exit status and that text are both checked: otherwise the error text is read as the value. pl() { local v v=$(plutil -extract "$2" raw -o - "$1" 2>/dev/null) || return 1 [[ $v == *'Could not extract value'* || $v == *'No value at that key path'* ]] && return 1 print -rn -- $v } # A path as the person knows it: ~/Downloads/x.dmg rather than /Users/sam/Downloads/x.dmg. nice() { local p=${1#$R}; [[ $p == $HOME/* ]] && p="~/${p#$HOME/}"; print -rn -- $p } day() { strftime '%b %f, %Y' $1 } bytes_of() { local -a s; zstat -A s +size -- "$1" 2>/dev/null && print -rn -- ${s[1]} || print -rn -- 0 } mtime_of() { local -a s; zstat -A s +mtime -- "$1" 2>/dev/null && print -rn -- ${s[1]} || print -rn -- 0 } sum_sizes() { local t=0 f; for f in "$@"; do (( t += $(bytes_of $f) )); done; print -rn -- $t } # Folder size in bytes from du. Prints nothing when macOS would not let Terminal read it at all. FOLDER_PARTIAL=0 folder_bytes() { local out rc k local -a lines FOLDER_PARTIAL=0 out=$(du -sk -- "$1" 2>/dev/null); rc=$? lines=(${(f)out}) # an array first: on a one-line string, [-1] would be the last character, not the last line k=${lines[-1]%%[[:space:]]*} [[ $k == <-> ]] || return 1 if (( rc )); then (( k <= 8 )) && return 1 # nothing readable: blocked by macOS privacy settings FOLDER_PARTIAL=1 fi print -rn -- $(( k * 1024 )) } # Median and spread of a list of numbers. Sets STAT_MEDIAN, STAT_Q1, STAT_Q3, STAT_MEAN, STAT_SD, STAT_N. stats() { local -a v; v=(${(n)@}) local n=${#v} i typeset -gF STAT_MEDIAN=0 STAT_Q1=0 STAT_Q3=0 STAT_MEAN=0 STAT_SD=0 typeset -gi STAT_N=$n (( n )) || return 1 # numeric sort on floats: (n) sorts integers properly but not "10.5" vs "9.2", so sort explicitly v=(${(f)"$(print -l -- $@ | sort -g)"}) local -F sum=0 sq=0 for i in $v; do (( sum += i )); done STAT_MEAN=$(( sum / n )) for i in $v; do (( sq += (i - STAT_MEAN) ** 2 )); done (( n > 1 )) && STAT_SD=$(( sqrt(sq / (n - 1)) )) if (( n % 2 )); then STAT_MEDIAN=${v[$(( (n + 1) / 2 ))]} else STAT_MEDIAN=$(( (v[n / 2] + v[n / 2 + 1]) / 2.0 )); fi STAT_Q1=${v[$(( (n + 3) / 4 ))]} STAT_Q3=${v[$(( (3 * n + 1) / 4 ))]} } # ----------------------------------------------------------------------------- # Results # ----------------------------------------------------------------------------- # Findings: v0.1 fields (level, area, title, why, action, details) plus, from v0.2, the kind of finding, # how sure the evidence is, what fixing it is expected to do, a ranking score and a one-line summary. typeset -a F_LEVEL F_AREA F_TITLE F_WHY F_ACTION F_DETAILS F_KIND F_CONF F_BENEFIT F_SCORE F_SUMMARY typeset -a C_AREA C_NAME C_RESULT C_STATUS typeset -a T_SPACE T_LARGE T_DOWNLOADS T_INSTALLERS T_STARTUP T_MOVED T_CPU T_MEM T_DUPES T_DEV T_ARCHIVES T_ENERGY T_SPACE_COLS=(Folder Size Note) T_LARGE_COLS=(File Size 'Last changed' Type) T_DOWNLOADS_COLS=(File Size 'Last modified') T_INSTALLERS_COLS=(Installer Size 'Last changed') T_STARTUP_COLS=(Item 'Installed for' State 'CPU (avg)' Memory) T_MOVED_COLS=(File Size Result) T_CPU_COLS=(Process Type 'CPU (avg, of one core)' 'CPU (peak)' 'Busy in samples') T_MEM_COLS=(Process Type 'Memory (resident)') T_DUPES_COLS=('Identical copies' 'Size each' 'Could free') T_DEV_COLS=(Folder Kind Size 'Project last changed' 'Rebuild with') T_ARCHIVES_COLS=(Archive Size 'Last changed') T_ENERGY_COLS=(Process 'Energy impact') typeset -a INSTALLER_PATHS # eligible for the optional move to the Trash # Numeric measurements, keyed "base:name" for the first measurement and "after:name" for the re-measurement. typeset -A M add_finding() { # LEVEL AREA TITLE WHY ACTION [key value]... (v0.1 signature, unchanged) local d='' k v F_LEVEL+=("$1"); F_AREA+=("$2"); F_TITLE+=("$3"); F_WHY+=("$4"); F_ACTION+=("$5"); shift 5 while (( $# >= 2 )); do k=$1; v=$2; shift 2; d+="$k$US$v$RS"; done F_DETAILS+=("$d") F_KIND+=(health); F_CONF+=(''); F_BENEFIT+=(''); F_SUMMARY+=('') [[ ${F_LEVEL[-1]} == Urgent ]] && F_SCORE+=(70) || F_SCORE+=(30) } # A performance bottleneck: like a finding, plus confidence, expected benefit, a ranking score (0-100) # and the one-sentence summary used at the top of the report when this is the biggest problem. add_bottleneck() { # LEVEL AREA TITLE WHY ACTION CONFIDENCE BENEFIT SCORE SUMMARY [key value]... local lv=$1 ar=$2 ti=$3 wh=$4 ac=$5 co=$6 be=$7 sc=$8 su=$9; shift 9 add_finding $lv $ar $ti $wh $ac "$@" F_KIND[-1]=bottleneck; F_CONF[-1]=$co; F_BENEFIT[-1]=$be; F_SCORE[-1]=$sc; F_SUMMARY[-1]=$su } # Storage findings carry a benefit and a score too, so they can be ranked next to performance problems. set_last_finding() { # KIND CONFIDENCE BENEFIT SCORE [SUMMARY] F_KIND[-1]=$1; F_CONF[-1]=$2; F_BENEFIT[-1]=$3; F_SCORE[-1]=$4; F_SUMMARY[-1]=${5:-} } add_check() { C_AREA+=("$1"); C_NAME+=("$2"); C_RESULT+=("$3"); C_STATUS+=("${4:-Clear}") } # AREA NAME RESULT [Clear|Flagged|Skipped] row() { local IFS=$RS; print -rn -- "$*" } # Recommended optimizations (the Optimization Engine's catalogue for this Mac). typeset -a R_ID R_TITLE R_RISK R_APPROVAL R_RECLAIM R_COUNT R_WHY R_RECOVERY add_rec() { # ID TITLE RISK(1|2) APPROVAL RECLAIM_BYTES COUNT WHY RECOVERY R_ID+=("$1"); R_TITLE+=("$2"); R_RISK+=("$3"); R_APPROVAL+=("$4"); R_RECLAIM+=("$5"); R_COUNT+=("$6"); R_WHY+=("$7"); R_RECOVERY+=("$8") } rec_index() { local i; for (( i = 1; i <= ${#R_ID}; i++ )); do [[ ${R_ID[$i]} == $1 ]] && { print -rn -- $i; return 0 }; done; return 1 } # What the Optimization Engine did. typeset -a A_TIME A_ACTION A_ITEM A_RESULT A_BYTES A_OK A_RECOVERY add_action() { # ACTION ITEM RESULT OK(1|0) BYTES RECOVERY A_TIME+=("$EPOCHSECONDS"); A_ACTION+=("$1"); A_ITEM+=("$2"); A_RESULT+=("$3"); A_OK+=("$4"); A_BYTES+=("${5:-0}"); A_RECOVERY+=("${6:-}") log_line "$1" "$2" "$3" } # ----------------------------------------------------------------------------- # Change log: one line per change, written as it happens, so an interrupted run still has a record. # ----------------------------------------------------------------------------- LOG_PATH='' log_line() { # ACTION ITEM RESULT [[ -n $LOG_PATH ]] || return 0 if [[ ! -e $LOG_PATH ]]; then { print -r -- "# $BRAND $VERSION change log for ${COMPUTER:-this Mac}" print -r -- '# time | action | item | result. Files moved to the Trash can be put back: open the Trash, right-click, Put Back.' } >> $LOG_PATH 2>/dev/null fi print -r -- "$(strftime '%Y-%m-%dT%H:%M:%S%z' $EPOCHSECONDS) | $1 | ${2//$'\n'/ } | $3" >> $LOG_PATH 2>/dev/null } # ----------------------------------------------------------------------------- # Path safety. Every file or folder the Optimization Engine is about to move is checked again here, # immediately before the move, against what the scan saw. # ----------------------------------------------------------------------------- GUARD_WHY='' # path_guard PATH ROOT TYPE(f|d) [SIZE] [MTIME] # PATH the path recorded by the scan (already fully resolved with :A) # ROOT the folder it must still be inside (for example ~/Downloads) # Fails when: the path has . or .. segments; any part of it is now a symbolic link (the fully resolved # path no longer matches); it is outside ROOT or is ROOT itself; it is the wrong type; or its size or # modification time changed since the scan. path_guard() { local p=$1 root=$2 type=$3 want_size=${4:-} want_mtime=${5:-} rroot GUARD_WHY='' if [[ $p != /* || $p == *'/../'* || $p == *'/./'* || $p == */.. || $p == */. || $p == *'//'* ]]; then GUARD_WHY='unusual path'; return 1 fi rroot=${root:A} [[ -n $rroot && $rroot != / ]] || { GUARD_WHY='no safe folder to check against'; return 1 } if [[ ! -e $p && ! -L $p ]]; then GUARD_WHY='no longer there'; return 1; fi if [[ -L $p || ${p:A} != $p ]]; then GUARD_WHY='part of the path is now a link'; return 1; fi if [[ $p != $rroot/?* ]]; then GUARD_WHY='outside the folder it was found in'; return 1; fi case $type in f) [[ -f $p ]] || { GUARD_WHY='no longer a regular file'; return 1 } ;; d) [[ -d $p ]] || { GUARD_WHY='no longer a folder'; return 1 } ;; *) GUARD_WHY='unknown type'; return 1 ;; esac if [[ -n $want_size && $type == f ]] && (( $(bytes_of $p) != want_size )); then GUARD_WHY='changed since the scan'; return 1; fi if [[ -n $want_mtime ]] && (( $(mtime_of $p) != want_mtime )); then GUARD_WHY='changed since the scan'; return 1; fi return 0 } # Finder moves things to the Trash, so each one can be put back (right-click in the Trash > Put Back). # macOS may ask once whether Terminal may control Finder. The path goes in as an argument, never as script text. to_trash() { osascript -e 'on run argv' -e 'tell application "Finder" to delete (POSIX file (item 1 of argv) as alias)' -e 'end run' -- "$1" >/dev/null 2>&1 } # Move one checked item to the Trash and confirm it left its folder. Prints nothing; returns 0 when moved. trash_checked() { # PATH ROOT TYPE [SIZE] [MTIME] path_guard "$@" || return 2 to_trash ${1#$R} [[ ! -e $1 && ! -L $1 ]] } # ----------------------------------------------------------------------------- # Questions in Terminal. Every answer defaults to "no". # ----------------------------------------------------------------------------- INPUT_CLOSED=0 ask() { # PROMPT -> REPLY (lower case, trimmed). Returns 1 when there is no more input. REPLY='' (( INPUT_CLOSED )) && return 1 print -rn -- "$1" local a if ! read -r a; then INPUT_CLOSED=1; print; return 1; fi REPLY=${(L)$(trim "$a")} return 0 } yes_answer() { [[ $REPLY == (y|yes) ]] } # ==== lib/sampler.zsh ==== # ============================================================================= # Odd$ Tune for Mac - sampler: measures CPU, memory, swap, disk activity and energy over a time window. # # CPU use is measured from each process's accumulated CPU time (ps "time"), read at the start and end of # every interval, so a figure is the real average over that interval, not a one-off reading. The same # routine runs before and after optimizations, with the same window, so the two can be compared. # Odd$ Tune's own processes (this script and anything it starts) are left out of every figure. # ============================================================================= typeset -A G_CPU G_PEAK G_SUST G_RSS G_KIND G_PATH G_PIDS G_ENERGY G_NPROC # keyed "tag:group" typeset -A P_CPU P_RSS P_COMM P_UID P_PPID P_GROUP # keyed "pid", baseline only typeset -a SAMPLE_GROUPS_base SAMPLE_GROUPS_after typeset -a CPU_SERIES_base CPU_SERIES_after SWAP_SERIES_base SWAP_SERIES_after typeset -A GROUP_CACHE MY_UID=$(id -u 2>/dev/null) # "1:02.50" (macOS: minutes:seconds), "01:02:03" or "1-02:03:04" (other systems) -> seconds, in REPLY to_sec() { local t=$1 d=0 local -a p if [[ $t == *-* ]]; then d=${t%%-*}; t=${t#*-}; fi p=(${(s.:.)t}) case ${#p} in 1) REPLY=$(( d * 86400.0 + p[1] )) ;; 2) REPLY=$(( d * 86400.0 + p[1] * 60.0 + p[2] )) ;; 3) REPLY=$(( d * 86400.0 + p[1] * 3600.0 + p[2] * 60.0 + p[3] )) ;; *) REPLY=0 ;; esac } # Which group a process belongs to, and what kind of process it is. # app a user application, and every helper process inside its bundle (Chrome's renderers count as Chrome) # system part of macOS # service a third-party background service or helper not inside an application in Applications # tool a command-line program you (or an app) started, such as node or python # Sets GRP (display name), GKIND and GAPP (the .app bundle path, for apps). classify() { # COMM UID local comm=$1 uid=$2 key="$1$US$2" name app if [[ -n ${GROUP_CACHE[$key]-} ]]; then local -a c; c=("${(@ps:$US:)GROUP_CACHE[$key]}"); GRP=$c[1]; GKIND=$c[2]; GAPP=${c[3]-}; return fi GAPP='' if [[ $comm == *.app/* ]]; then app="${comm%%.app/*}.app"; name=${${app:t}%.app} case $app in /System/Library/*|/System/Applications/Utilities/*|/Library/Apple/*) GRP=$name; GKIND=system ;; /Applications/*|/System/Applications/*|$HOME/Applications/*|/System/Volumes/Preboot/Cryptexes/App/System/Applications/*) GRP=$name; GKIND=app; GAPP=$app ;; *) GRP=$name; GKIND=service ;; esac else name=${comm:t} [[ -z $name ]] && name=$comm case $comm in kernel_task|launchd|/sbin/*|/usr/sbin/*|/usr/libexec/*|/System/*|/usr/bin/*|/bin/*|/Library/Apple/*) GRP=$name; GKIND=system ;; /*) if [[ $uid == $MY_UID ]]; then GRP=$name; GKIND=tool; else GRP=$name; GKIND=service; fi ;; *) GRP=$name; GKIND=system ;; # a bare name with no path is a kernel or early-boot process esac fi GROUP_CACHE[$key]="$GRP$US$GKIND$US$GAPP" } # Parse a vm_stat snapshot into VM (page counts) and VM_PAGE (page size in bytes). typeset -A VM VM_PAGE=4096 vm_parse() { local line key val VM=() while IFS= read -r line; do if [[ $line == *'page size of '<->' bytes'* ]]; then [[ $line =~ 'page size of ([0-9]+) bytes' ]] && VM_PAGE=$match[1]; continue fi [[ $line == *:* ]] || continue key=${line%%:*}; val=${${line#*:}//[^0-9]/} [[ -n $val ]] && VM[$key]=$val done < $1 } # sample_system TAG SECONDS sample_system() { local tag=$1 secs=$2 n k line pid ppid uid tm rss comm local -F interval n=$(( secs >= 6 ? (secs + 1) / 2 : 3 )); (( n > 30 )) && n=30 # about one interval every 2 seconds n=${n%.*} interval=$(( secs * 1.0 / n )) local -a snap_t snap_pl local io_pid='' top_pid='' whole=${$(f0 $secs)} (( whole < 1 )) && whole=1 # Disk throughput and macOS's own energy estimate, measured over the same window, in the background. if command -v iostat >/dev/null 2>&1; then iostat -d -c 2 -w $whole > $TMP/io.$tag 2>/dev/null & io_pid=$!; fi if command -v top >/dev/null 2>&1; then top -l 2 -s $whole -n 30 -o power -stats pid,command,cpu,power > $TMP/top.$tag 2>/dev/null & top_pid=$!; fi for (( k = 0; k <= n; k++ )); do snap_t[$(( k + 1 ))]=$EPOCHREALTIME ps -axo pid=,ppid=,uid=,time=,rss=,comm= > $TMP/ps.$tag.$k 2>/dev/null vm_stat > $TMP/vm.$tag.$k 2>/dev/null snap_pl[$(( k + 1 ))]=$(sysctl -n kern.memorystatus_vm_pressure_level 2>/dev/null) (( k < n )) && sleep $interval done # Let the background measurements finish (they were started for the same length of time). local waited=0 while { [[ -n $io_pid ]] && kill -0 $io_pid 2>/dev/null } || { [[ -n $top_pid ]] && kill -0 $top_pid 2>/dev/null }; do (( waited++ >= 40 )) && { [[ -n $io_pid ]] && kill $io_pid 2>/dev/null; [[ -n $top_pid ]] && kill $top_pid 2>/dev/null; break } sleep 0.1 done # ---- CPU, per interval ------------------------------------------------------ local ncpu=${M[base:logicalCpus]:-1} (( ncpu < 1 )) && ncpu=1 typeset -A prev_t prev_c cur_t cur_c cur_ppid cur_uid cur_rss grp_int local -A gsum gpeak gsust gpids gkind gpath grss gnproc local -F d dt total_d elapsed=0 pct local -a series groups_seen local g for (( k = 0; k <= n; k++ )); do cur_t=(); cur_c=(); cur_ppid=(); cur_uid=(); cur_rss=() [[ -r $TMP/ps.$tag.$k ]] || continue while read -r pid ppid uid tm rss comm; do [[ $pid == <-> ]] || continue to_sec $tm cur_t[$pid]=$REPLY; cur_c[$pid]=$comm; cur_ppid[$pid]=$ppid; cur_uid[$pid]=$uid; cur_rss[$pid]=${rss:-0} done < $TMP/ps.$tag.$k if (( k > 0 )); then dt=$(( snap_t[k + 1] - snap_t[k] )) (( dt <= 0 )) && dt=$interval (( elapsed += dt )) total_d=0; grp_int=() for pid in ${(k)cur_t}; do (( pid == $$ || cur_ppid[$pid] == $$ )) && continue # Odd$ Tune itself if [[ -n ${prev_t[$pid]-} && ${prev_c[$pid]} == ${cur_c[$pid]} ]]; then d=$(( cur_t[$pid] - prev_t[$pid] )) else d=${cur_t[$pid]}; fi # started during this interval (( d < 0 )) && d=0 (( d > dt * ncpu )) && d=$(( dt * ncpu )) # a reused PID cannot claim more than the Mac has (( total_d += d )) classify ${cur_c[$pid]} ${cur_uid[$pid]} (( grp_int[$GRP] += d )) (( gsum[$GRP] += d )) gkind[$GRP]=$GKIND; [[ -n $GAPP ]] && gpath[$GRP]=$GAPP if [[ $tag == base ]]; then (( P_CPU[$pid] += d )); fi done series+=($(( total_d / dt / ncpu * 100 ))) for g in ${(k)grp_int}; do pct=$(( grp_int[$g] / dt * 100 )) (( pct > ${gpeak[$g]:-0} )) && gpeak[$g]=$pct (( pct >= 20 )) && (( gsust[$g]++ )) done fi prev_t=("${(@kv)cur_t}"); prev_c=("${(@kv)cur_c}") done (( elapsed > 0 )) || elapsed=$secs # Memory and the group each process belongs to, from the last snapshot. local nproc=0 nactive=0 nbg_active=0 for pid in ${(k)cur_t}; do (( pid == $$ || cur_ppid[$pid] == $$ )) && continue (( nproc++ )) classify ${cur_c[$pid]} ${cur_uid[$pid]} (( grss[$GRP] += cur_rss[$pid] * 1024 )) (( gnproc[$GRP]++ )) gpids[$GRP]+="$pid " gkind[$GRP]=$GKIND; [[ -n $GAPP ]] && gpath[$GRP]=$GAPP if [[ $tag == base ]]; then P_RSS[$pid]=$(( cur_rss[$pid] * 1024 )); P_COMM[$pid]=${cur_c[$pid]}; P_UID[$pid]=${cur_uid[$pid]}; P_PPID[$pid]=${cur_ppid[$pid]}; P_GROUP[$pid]=$GRP P_CPU[$pid]=$(( ${P_CPU[$pid]:-0} / elapsed * 100 )) fi done for g in ${(k)gsum}; do pct=$(( gsum[$g] / elapsed * 100 )) (( pct >= 1 )) && { (( nactive++ )); [[ ${gkind[$g]} == (service|tool) ]] && (( nbg_active++ )) } done local -a order for g in ${(k)gkind}; do G_CPU[${tag}:$g]=$(( ${gsum[$g]:-0} / elapsed * 100 )) G_PEAK[${tag}:$g]=${gpeak[$g]:-0} G_SUST[${tag}:$g]=$(( ${gsust[$g]:-0} * 100 / n )) G_RSS[${tag}:$g]=${grss[$g]:-0} G_KIND[${tag}:$g]=${gkind[$g]} G_PATH[${tag}:$g]=${gpath[$g]-} G_PIDS[${tag}:$g]=${gpids[$g]-} G_NPROC[${tag}:$g]=${gnproc[$g]:-0} order+=("$(printf '%012.3f' ${G_CPU[${tag}:$g]})$US$g") done order=(${(On)order}) set -A SAMPLE_GROUPS_$tag ${order##*$US} set -A CPU_SERIES_$tag $series stats $series M[${tag}:cpuTotalPctMean]=$(f1 $STAT_MEAN); M[${tag}:cpuTotalPctSd]=$(f1 $STAT_SD) M[${tag}:cpuTotalPctPeak]=$(f1 ${${(On)series}[1]:-0}) local busy=0 v; for v in $series; do (( v >= 80 )) && (( busy++ )); done M[${tag}:cpuBusyIntervals]=$busy M[${tag}:sampleSeconds]=$(f1 $elapsed); M[${tag}:sampleIntervals]=$n M[${tag}:processCount]=$nproc; M[${tag}:activeProcessCount]=$nactive; M[${tag}:backgroundActiveCount]=$nbg_active local la; la=$(sysctl -n vm.loadavg 2>/dev/null) if [[ $la =~ '([0-9.]+) ([0-9.]+) ([0-9.]+)' ]]; then M[${tag}:load1]=$match[1]; M[${tag}:load5]=$match[2]; M[${tag}:load15]=$match[3]; fi # ---- Memory pressure, compression and swap ------------------------------------ local worst=0 warn=0 known=0 p for p in $snap_pl; do [[ $p == <-> ]] || continue (( known++ )); (( p > worst )) && worst=$p; (( p >= 2 )) && (( warn++ )) done if (( known )); then M[${tag}:memPressureWorst]=$worst; M[${tag}:memPressureElevatedPct]=$(( warn * 100 / known )); fi local -a sw_series local -i so0=-1 si0=-1 so1=0 si1=0 po0=-1 po1=0 last_so=-1 local -F t_first=0 t_last=0 t_prev=0 for (( k = 0; k <= n; k++ )); do [[ -s $TMP/vm.$tag.$k ]] || continue vm_parse $TMP/vm.$tag.$k [[ -n ${VM[Swapouts]-} ]] || continue if (( so0 < 0 )); then so0=${VM[Swapouts]}; si0=${VM[Swapins]:-0}; po0=${VM[Pageouts]:-0}; t_first=${snap_t[k + 1]} else local -F tdt=$(( snap_t[k + 1] - t_prev )); (( tdt <= 0 )) && tdt=$interval sw_series+=($(( (VM[Swapouts] - last_so) / tdt ))) fi last_so=${VM[Swapouts]}; t_prev=${snap_t[k + 1]}; t_last=${snap_t[k + 1]} so1=${VM[Swapouts]}; si1=${VM[Swapins]:-0}; po1=${VM[Pageouts]:-0} done if (( so0 >= 0 )); then local -F span=$(( t_last - t_first )); (( span <= 0 )) && span=$elapsed M[${tag}:pageSize]=$VM_PAGE M[${tag}:swapOutPagesPerSec]=$(f1 $(( (so1 - so0) / span ))) M[${tag}:swapInPagesPerSec]=$(f1 $(( (si1 - si0) / span ))) M[${tag}:swapOutBytesDuring]=$(( (so1 - so0) * VM_PAGE )) M[${tag}:swapInBytesDuring]=$(( (si1 - si0) * VM_PAGE )) M[${tag}:pageOutBytesDuring]=$(( (po1 - po0) * VM_PAGE )) M[${tag}:compressedBytes]=$(( ${VM[Pages occupied by compressor]:-0} * VM_PAGE )) M[${tag}:compressedOriginalBytes]=$(( ${VM[Pages stored in compressor]:-0} * VM_PAGE )) M[${tag}:wiredBytes]=$(( ${VM[Pages wired down]:-0} * VM_PAGE )) M[${tag}:fileCacheBytes]=$(( ${VM[File-backed pages]:-0} * VM_PAGE )) M[${tag}:freePagesBytes]=$(( (${VM[Pages free]:-0} + ${VM[Pages speculative]:-0}) * VM_PAGE )) set -A SWAP_SERIES_$tag $sw_series stats $sw_series; M[${tag}:swapOutPagesPerSecSd]=$(f1 $STAT_SD) fi local su; su=$(sysctl -n vm.swapusage 2>/dev/null) if [[ $su =~ 'total = ([0-9.]+)([MG]).*used = ([0-9.]+)([MG])' ]]; then local -F tot=$match[1] used=$match[3] [[ $match[2] == G ]] && (( tot *= 1024 )); [[ $match[4] == G ]] && (( used *= 1024 )) M[${tag}:swapTotalBytes]=$(f0 $(( tot * 1048576 ))); M[${tag}:swapUsedBytes]=$(f0 $(( used * 1048576 ))) fi local mp; mp=$(memory_pressure -Q 2>/dev/null) [[ $mp =~ 'free percentage: ([0-9]+)%' ]] && M[${tag}:memFreePct]=$match[1] # ---- Disk throughput (system-wide: macOS does not show per-app disk use without administrator rights) -- if [[ -s $TMP/io.$tag ]]; then local -a io_lines f; local -F mbs=0; local c io_lines=(${(f)"$(<$TMP/io.$tag)"}) f=(${=io_lines[-1]}) if (( ${#f} >= 3 )) && [[ ${f[3]} == <->(|.<->) ]]; then for (( c = 3; c <= ${#f}; c += 3 )); do [[ ${f[$c]} == <->(|.<->) ]] && (( mbs += f[$c] )); done M[${tag}:diskMBps]=$(f1 $mbs) fi fi # ---- Energy impact (macOS's own estimate, from top) --------------------------- if [[ -s $TMP/top.$tag ]]; then local -a tl; local start=0 i w tl=(${(f)"$(<$TMP/top.$tag)"}) for (( i = 1; i <= ${#tl}; i++ )); do [[ ${tl[$i]} == [[:space:]]#PID[[:space:]]##COMMAND* ]] && start=$i; done if (( start )); then for (( i = start + 1; i <= ${#tl}; i++ )); do w=(${=tl[$i]}) [[ ${w[1]} == <-> && ${w[-1]} == <->(|.<->) ]] || continue pid=${w[1]} if [[ -n ${cur_c[$pid]-} ]]; then classify ${cur_c[$pid]} ${cur_uid[$pid]}; (( G_ENERGY[${tag}:$GRP] += w[-1] )); fi done fi fi return 0 } # A small, repeatable responsiveness check: how long it takes to start a tiny program. Starting programs # slows down when the Mac is starved of processor time or memory. Fifteen rounds of 30 starts are timed # after one warm-up round; the median and the spread are kept. It is reported for reference only: in # testing it varied too much between identical runs to support any before/after claim. (A file-operation # timing was also tried and dropped for the same reason.) bench_responsiveness() { # TAG local tag=$1 i r local -a spawn local -F t0 t1 for (( r = 0; r <= 15; r++ )); do # round 0 warms caches up and is not counted t0=$EPOCHREALTIME for (( i = 1; i <= 30; i++ )); do /usr/bin/true; done t1=$EPOCHREALTIME (( r )) && spawn+=($(( (t1 - t0) * 1000.0 / 30 ))) done stats $spawn M[${tag}:spawnMsMedian]=$(printf '%.3f' $STAT_MEDIAN); M[${tag}:spawnMsQ1]=$(printf '%.3f' $STAT_Q1); M[${tag}:spawnMsQ3]=$(printf '%.3f' $STAT_Q3) return 0 } # Free space, read the same way before and after. measure_disk_free() { # TAG local line; local -a cols lines line=$(df -kP /System/Volumes/Data 2>/dev/null) || line=$(df -kP / 2>/dev/null) lines=(${(f)line}); cols=(${=lines[-1]}) [[ ${cols[2]:-} == <-> && ${cols[4]:-} == <-> ]] || return 1 M[${1}:diskTotalBytes]=$(( cols[2] * 1024 )); M[${1}:diskFreeBytes]=$(( cols[4] * 1024 )) } # Power source at the time of measuring (comparisons are only fair when it is the same). measure_power_source() { # TAG local b; b=$(pmset -g batt 2>/dev/null) if [[ $b == *"'AC Power'"* ]]; then M[${1}:powerSource]=AC elif [[ $b == *"'Battery Power'"* ]]; then M[${1}:powerSource]=Battery fi local lp; lp=$(pmset -g 2>/dev/null) [[ $lp =~ 'lowpowermode[[:space:]]+([01])' ]] && M[${1}:lowPowerMode]=$match[1] return 0 } # ==== lib/diag_storage.zsh ==== # ============================================================================= # Odd$ Tune for Mac - storage diagnostics. # Free space, where it goes, large files and archives, Downloads, installers, the Trash, verified # duplicates and developer build folders. Read-only: candidates are recorded with their size and # modification time so the Optimization Engine can check they are unchanged before touching them. # ============================================================================= DISK_TOTAL=0; DISK_FREE=0 typeset -A CAND_SIZE CAND_MTIME CAND_ROOT # keyed by resolved path typeset -a OLD_DL_PATHS # largest Downloads not modified for 90+ days typeset -a DUP_HASHES; typeset -A DUP_SIZE DUP_FILES typeset -a DEV_PATHS; typeset -A DEV_KIND DEV_BYTES DEV_REBUILD DEV_ELIGIBLE DEV_AGE_DAYS typeset -a DEV_GUIDE # tool-managed caches: guidance only DERIVED_DATA=''; DERIVED_BYTES=0 DUP_RECLAIM=0; DUP_PARTIAL=0; DEV_RECLAIM=0 # Folders the large-file and duplicate searches never enter: app libraries are managed in their apps. PKG_PAT='(Library|*.photoslibrary|*.photolibrary|*.musiclibrary|*.tvlibrary|*.aplibrary|*.fcpbundle|*.app)' DUP_SKIP='(*.app|*.photoslibrary|*.photolibrary|*.musiclibrary|*.tvlibrary|*.aplibrary|*.fcpbundle|node_modules|*.xcodeproj|*.xcworkspace|*.sparsebundle|*.bundle|*.framework|*.rtfd|*.pages|*.numbers|*.key|*.logicx|*.band)' remember() { # PATH ROOT -> records size and modification time for the later safety re-check CAND_SIZE[$1]=$(bytes_of $1); CAND_MTIME[$1]=$(mtime_of $1); CAND_ROOT[$1]=$2 } file_kind() { # PATH -> REPLY case ${(L)1:e} in zip|tar|gz|tgz|bz2|xz|7z|rar|zst|lz4|cpio) REPLY=Archive ;; dmg|iso|img|sparseimage|toast) REPLY='Disk image' ;; pkg|mpkg|xip) REPLY=Installer ;; mov|mp4|m4v|mkv|avi|mts|braw|r3d|prores) REPLY=Video ;; vmdk|vdi|qcow2|hdd|vhdx|utm) REPLY='Virtual machine' ;; *) REPLY=Other ;; esac } scan_storage() { step 'Measuring free space' if ! measure_disk_free base; then add_check 'Storage' 'Free space' 'Could not be read' Skipped; return; fi DISK_TOTAL=${M[base:diskTotalBytes]}; DISK_FREE=${M[base:diskFreeBytes]} local pct=$(( DISK_TOTAL ? DISK_FREE * 100 / DISK_TOTAL : 100 )) local result="$(size $DISK_FREE) free of $(size $DISK_TOTAL) ($pct%)" local action='Start with the largest items in this report. Then open Apple menu > System Settings > General > Storage, where macOS offers to store files in iCloud, empty the Trash automatically and remove things you no longer use.' if (( pct < 5 || DISK_FREE < 10 * GB )); then add_check 'Storage' 'Free space' $result Flagged add_finding Urgent 'Storage' 'Your Mac is almost out of space' \ "Only $(size $DISK_FREE) is free. When the drive is this full, macOS can't install updates, apps slow down and files can fail to save." \ $action 'Free' "$(size $DISK_FREE)" 'Drive size' "$(size $DISK_TOTAL)" set_last_finding storage High 'Freeing space lets macOS install updates and keep room for swap and caches, which it needs to stay responsive.' 90 \ 'Your Mac is almost out of storage, which can slow apps down and stop updates from installing. Freeing space is the most valuable fix.' elif (( pct < 15 || DISK_FREE < 20 * GB )); then add_check 'Storage' 'Free space' $result Flagged add_finding Review 'Storage' 'Storage is getting full' \ "$(size $DISK_FREE) is free. macOS updates need 20 GB or more, and a nearly full drive makes the Mac slower." \ $action 'Free' "$(size $DISK_FREE)" 'Drive size' "$(size $DISK_TOTAL)" set_last_finding storage High 'More free space gives macOS room for updates, swap and caches.' 45 \ 'Storage is getting full. Clearing the items below gives macOS room for updates and keeps the Mac responsive.' else add_check 'Storage' 'Free space' $result fi return 0 } scan_folders() { step 'Measuring your main folders (macOS may ask whether Terminal can open them: choose Allow)' local spec name rel b note blocked=0 for spec in 'Desktop|Desktop' 'Documents|Documents' 'Downloads|Downloads' 'Pictures|Pictures' 'Movies|Movies' 'Music|Music' \ 'App caches|Library/Caches' 'iPhone and iPad backups|Library/Application Support/MobileSync/Backup' \ 'Xcode and developer files|Library/Developer'; do name=${spec%%|*}; rel=${spec#*|} [[ -d $R$HOME/$rel ]] || continue if b=$(folder_bytes "$R$HOME/$rel"); then note='' (( FOLDER_PARTIAL )) && note='Some items could not be read, so it may be larger.' case $name in 'App caches') note='macOS and apps manage these. Clearing them rarely helps; apps rebuild them, which costs time and energy. Odd$ Tune does not clear caches.' ;; 'Downloads') M[base:downloadsBytes]=$b if (( b >= 20 * GB || (DISK_TOTAL && b * 10 >= DISK_TOTAL) )); then add_finding Review 'Storage' "Your Downloads folder holds $(size $b)" \ 'Downloads is meant as a landing spot. Files that stay there for months are usually copies of things you already installed, opened or saved elsewhere.' \ 'Review the old installers, old downloads and duplicate files listed in this report. Odd$ Tune can move the ones you pick to the Trash.' 'Size' "$(size $b)" set_last_finding storage High "Up to $(size $b) could be recovered, depending on what you choose to keep." 35 fi ;; 'iPhone and iPad backups') if (( b >= 5 * GB )); then add_finding Review 'Storage' 'Old iPhone or iPad backups are taking up space' \ "Device backups on this Mac use $(size $b). If a device is gone or now backs up to iCloud, its old backup can go." \ 'In Finder, select your iPhone or iPad in the sidebar (or connect it), click Manage Backups, and delete the ones you no longer need.' 'Size' "$(size $b)" set_last_finding storage High "Up to $(size $b) of storage." 30 fi ;; 'Xcode and developer files') if (( b >= 10 * GB )); then add_finding Review 'Storage' 'Developer files are taking up space' \ "Xcode build files and simulators use $(size $b). Xcode can rebuild most of this." \ 'See "Developer folders" in this report. In Xcode, open Settings > Platforms to remove simulators you no longer use. Odd$ Tune can move DerivedData (Xcode rebuilds it) to the Trash when Xcode is closed.' 'Size' "$(size $b)" set_last_finding storage High 'Storage only. Xcode rebuilds what it needs on the next build, which takes longer once.' 30 fi ;; esac T_SPACE+=("$(row "$name" "$(size $b)" "$note")") else (( blocked++ )) case $name in 'iPhone and iPad backups') note='Private to Finder. See them in Finder: select your device, then Manage Backups.' ;; *) note='Not checked: macOS did not let Terminal open this folder.' ;; esac T_SPACE+=("$(row "$name" '' "$note")") fi done add_check 'Storage' 'Where your space goes' "${#T_SPACE} folders measured$( (( blocked )) && print -rn -- ", $blocked not readable")" return 0 } scan_large_files() { step 'Looking for large files (500 MB or more) and large archives (100 MB or more)' # Everything in your home folder except ~/Library, hidden folders and app libraries such as Photos (manage those in their apps). # v0.1.0 used Lm+499, which works in MiB and missed files between 500 and 523 MB; this threshold is in bytes. local -a big big=( $R$HOME/(^${~PKG_PAT}/)#*(.NL+99999999OL) ) local f b total=0 n=0 d na=0 arch_b=0 local -a blocked for d in Desktop Documents Downloads; do [[ -d $R$HOME/$d ]] && ! ls -- $R$HOME/$d >/dev/null 2>&1 && blocked+=("$d") done local unread=${${(j:, :)blocked}:+"; not checked: ${(j:, :)blocked} (macOS did not let Terminal open them)"} for f in $big; do b=$(bytes_of $f); file_kind $f if [[ $REPLY == Archive ]]; then (( na++ )); (( arch_b += b )) (( na <= 25 )) && T_ARCHIVES+=("$(row "$(nice $f)" "$(size $b)" "$(day $(mtime_of $f))")") fi (( b >= 500000000 )) || continue (( total += b )) (( ++n <= 25 )) && T_LARGE+=("$(row "$(nice $f)" "$(size $b)" "$(day $(mtime_of $f))" "$REPLY")") done M[base:largeFileCount]=$n; M[base:largeFileBytes]=$total if (( n )); then add_check 'Storage' 'Large files' "$n found, $(size $total) in total$unread" Flagged add_finding Review 'Storage' "$(plural $n 'large file uses' 'large files use') $(size $total)" \ 'These are the biggest files in your folders. Old videos, disk images and archives are common ones you may no longer need.' \ 'Look through the list under "Largest files". Move what you no longer need to the Trash, or to an external drive or iCloud if you want to keep it.' \ 'Files' $n 'Total' "$(size $total)" set_last_finding storage High "Up to $(size $total), depending on what you decide to keep. Only you can judge these, so Odd$ Tune does not offer to move them." \ $(( total >= 20 * GB ? 40 : 25 )) elif (( ${#blocked} )); then add_check 'Storage' 'Large files' "None in the folders Terminal could read$unread" Skipped else add_check 'Storage' 'Large files' 'None of 500 MB or more' fi if (( na )); then add_check 'Storage' 'Large archives' "$(plural $na archive archives) of 100 MB or more, $(size $arch_b)" $( (( arch_b >= 2 * GB )) && print Flagged || print Clear) if (( arch_b >= 2 * GB )); then add_finding Review 'Storage' "Archives (.zip, .tar and similar) use $(size $arch_b)" \ 'Archives are often downloaded or made once, opened, and kept by accident next to the files they contain.' \ 'Check the list under "Large archives". If you have already opened one and kept what is inside, the archive itself can go.' 'Archives' $na 'Total' "$(size $arch_b)" set_last_finding storage Medium "Up to $(size $arch_b), if their contents are already kept elsewhere." 20 fi else add_check 'Storage' 'Large archives' 'None of 100 MB or more' fi return 0 } scan_downloads() { step 'Reviewing your Downloads folder' local dl=$R$HOME/Downloads if [[ ! -d $dl ]]; then add_check 'Storage' 'Downloads folder' 'No Downloads folder'; return; fi if ! ls -- $dl >/dev/null 2>&1; then add_check 'Storage' 'Downloads folder' 'Not checked: macOS did not let Terminal open it' Skipped; return; fi local -a all old inst all=( $dl/**/*(.N) ) old=( $dl/**/*(.Nm+90OL) ) inst=( $dl/**/*.(#i)(dmg|pkg|mpkg|xip|iso)(.Nm+6OL) ) # installers at least a week old local f b old_b=0 inst_b=0 rf rdl=${dl:A} for f in $old; do b=$(bytes_of $f); (( old_b += b )) if (( ${#T_DOWNLOADS} < 25 )); then T_DOWNLOADS+=("$(row "$(nice $f)" "$(size $b)" "$(day $(mtime_of $f))")") # Old installers are offered separately, so they are not offered twice. if (( ! ${inst[(Ie)$f]} )); then rf=${f:A}; OLD_DL_PATHS+=("$rf"); remember $rf $rdl; fi fi done for f in $inst; do b=$(bytes_of $f); (( inst_b += b )) rf=${f:A}; INSTALLER_PATHS+=("$rf"); remember $rf $rdl T_INSTALLERS+=("$(row "$(nice $f)" "$(size $b)" "$(day $(mtime_of $f))")") done M[base:installerBytes]=$inst_b; M[base:oldDownloadBytes]=$old_b local total=$(sum_sizes $all) add_check 'Storage' 'Downloads folder' "$(plural ${#all} file files), $(size $total); $(plural ${#old} file files) not modified for 90+ days" if (( ${#inst} )); then add_check 'Storage' 'Old installers in Downloads' "$(plural ${#inst} file files), $(size $inst_b)" Flagged add_finding Review 'Storage' "Old installers in Downloads use $(size $inst_b)" \ 'Disk images (.dmg) and installer packages (.pkg) are only needed while you install an app. Once it is in Applications, the installer can go.' \ 'Delete the installers listed under "Old installers" that you have finished with. Odd$ Tune can move them to the Trash for you when the scan ends; you can put them back from the Trash.' \ 'Files' ${#inst} 'Total' "$(size $inst_b)" set_last_finding storage High "$(size $inst_b) once the Trash is emptied." $(( inst_b >= 5 * GB ? 35 : 20 )) else add_check 'Storage' 'Old installers in Downloads' 'None' fi if (( old_b >= GB )); then add_finding Review 'Storage' "Downloads not modified in 90 days use $(size $old_b)" \ 'Downloads collect over time. Most are one-off files you have already used or saved elsewhere. (Some downloads keep the date the file was made, so a few may be newer than they look.)' \ 'Open Downloads in Finder, choose View > as List and sort by Date Modified. Move what you no longer need to the Trash, or let Odd$ Tune show you the largest ones one at a time.' \ 'Files' ${#old} 'Total' "$(size $old_b)" set_last_finding storage Medium "Up to $(size $old_b), depending on what you keep." 20 fi return 0 } scan_trash() { step 'Checking the Trash' local t=$R$HOME/.Trash b if [[ ! -d $t ]]; then add_check 'Storage' 'Trash' 'Empty'; return; fi if ! ls -A -- $t >/dev/null 2>&1 || ! b=$(folder_bytes $t); then add_check 'Storage' 'Trash' 'Not checked: macOS keeps the Trash private from Terminal. See its size in Finder.' Skipped; return fi M[base:trashBytes]=$b if (( b >= GB )); then add_check 'Storage' 'Trash' "$(size $b)" Flagged add_finding Review 'Storage' "The Trash is holding $(size $b)" \ 'Files in the Trash still use space until the Trash is emptied.' \ 'When you are sure you do not need anything in it, open the Trash in the Dock and click Empty. This cannot be undone, so check it first. Odd$ Tune never empties the Trash.' \ 'Size' "$(size $b)" set_last_finding storage High "$(size $b) as soon as you empty it." 25 else add_check 'Storage' 'Trash' "$(size $b)" fi return 0 } # Duplicates: same size first, then the same SHA-256 of the whole file. Hard links (one file with two names) # are not counted. Files that are only in iCloud are skipped, because reading them would download them. is_dataless() { # PATH: true when the file's contents are in iCloud only local fl; fl=$(stat -f '%Xf' -- "$1" 2>/dev/null) || return 1 [[ $fl == [[:xdigit:]]## ]] || return 1 (( (16#$fl & 16#40000000) != 0 )) } scan_duplicates() { (( NO_DUPLICATES )) && { add_check 'Storage' 'Duplicate files' 'Not checked (--no-duplicates)' Skipped; return } step 'Looking for identical files in Desktop, Documents and Downloads (1 MB or more)' local root f b key inode local -A by_size seen_inode local -a roots files for root in Desktop Documents Downloads; do [[ -d $R$HOME/$root ]] && ls -- $R$HOME/$root >/dev/null 2>&1 && roots+=("$R$HOME/$root") done if (( ! ${#roots} )); then add_check 'Storage' 'Duplicate files' 'Not checked: no readable folders' Skipped; return; fi for root in $roots; do files=( $root/(^${~DUP_SKIP}/)#*(.NL+999999) ) for f in $files; do b=$(bytes_of $f); by_size[$b]+="${f:A}$RS" done done local -a cands; local -A hash_files; local hashed_bytes=0 hashed=0 hsum s for s in ${(k)by_size}; do cands=("${(@ps:$RS:)by_size[$s]}"); cands=(${cands:#}) (( ${#cands} >= 2 )) || continue seen_inode=() for f in $cands; do local -A st; zstat -H st -- $f 2>/dev/null || continue key="${st[device]}:${st[inode]}" [[ -n ${seen_inode[$key]-} ]] && continue # a hard link to a file already counted seen_inode[$key]=1 is_dataless $f && continue if (( hashed >= 4000 || hashed_bytes >= 40 * GB )); then DUP_PARTIAL=1; break 2; fi hsum=$(shasum -a 256 < $f 2>/dev/null); hsum=${hsum%% *} [[ $hsum == [[:xdigit:]](#c64) ]] || continue (( hashed++ )); (( hashed_bytes += s )) hash_files[${s}:$hsum]+="$f$RS" done done local hk n local -a group for hk in ${(k)hash_files}; do group=("${(@ps:$RS:)hash_files[$hk]}"); group=(${group:#}) (( ${#group} >= 2 )) || continue s=${hk%%:*} DUP_HASHES+=("$hk"); DUP_SIZE[$hk]=$s; DUP_FILES[$hk]=${hash_files[$hk]} for f in $group; do remember $f ${${f:h}:A}; done (( DUP_RECLAIM += (${#group} - 1) * s )) done # Biggest savings first local -a order; for hk in $DUP_HASHES; do order+=("$(printf '%015d' $(( (${#${(@ps:$RS:)DUP_FILES[$hk]}} - 1) * DUP_SIZE[$hk] )))$US$hk"); done order=(${(O)order}); DUP_HASHES=(${order##*$US}) for hk in $DUP_HASHES; do group=("${(@ps:$RS:)DUP_FILES[$hk]}"); group=(${group:#}) (( ${#T_DUPES} < 25 )) || continue local -a shown; shown=(); for f in $group; do shown+=("$(nice $f)"); done T_DUPES+=("$(row "${(j:; :)shown}" "$(size ${DUP_SIZE[$hk]})" "$(size $(( (${#group} - 1) * DUP_SIZE[$hk] )))")") done M[base:duplicateGroups]=${#DUP_HASHES}; M[base:duplicateReclaimBytes]=$DUP_RECLAIM local partial=''; (( DUP_PARTIAL )) && partial=' (search stopped early: very many files)' if (( ${#DUP_HASHES} )); then add_check 'Storage' 'Duplicate files' "$(plural ${#DUP_HASHES} set sets) of identical files; up to $(size $DUP_RECLAIM) could be freed$partial" Flagged if (( DUP_RECLAIM >= 100000000 )); then add_finding Review 'Storage' "Identical copies of files use up to $(size $DUP_RECLAIM)" \ 'These files have exactly the same contents (checked with a SHA-256 fingerprint, not just the name). Copies made by Finder on APFS drives can share storage, so the real saving may be smaller.' \ 'Review the sets under "Duplicate files". Odd$ Tune can show you each set and move the copies you pick to the Trash. It always keeps at least one copy and never chooses for you.' \ 'Sets' ${#DUP_HASHES} 'Could free (up to)' "$(size $DUP_RECLAIM)" set_last_finding storage High "Up to $(size $DUP_RECLAIM) once the Trash is emptied." $(( DUP_RECLAIM >= 5 * GB ? 30 : 18 )) fi else add_check 'Storage' 'Duplicate files' "None of 1 MB or more$partial" fi return 0 } # Developer build folders that the project's own tools recreate. Only folders that sit next to the file # that recreates them (package.json, Cargo.toml, Podfile...) count. Global tool folders under hidden # folders (~/.nvm, ~/.npm) are never touched. dev_kind() { # DIR -> sets DK (label), DR (rebuild command), DE (1 if safe to suggest) local d=$1 name=${1:t} p=${1:h} DK=''; DR=''; DE=0 case $name in node_modules) [[ -f $p/package.json ]] || return 1 DK='Node.js packages'; DE=1 if [[ -f $p/pnpm-lock.yaml ]]; then DR='pnpm install'; elif [[ -f $p/yarn.lock ]]; then DR='yarn install'; else DR='npm install'; fi ;; .venv|venv|env) [[ -f $d/pyvenv.cfg ]] || return 1 DK='Python virtual environment' local -a req; req=( $p/requirements*.txt(N) ) if (( ${#req} )) || [[ -f $p/pyproject.toml || -f $p/Pipfile || -f $p/setup.py ]]; then DE=1; DR="python3 -m venv $name, then install from the project's requirements" else DR='No requirements file found: review by hand'; fi ;; target) [[ -f $p/Cargo.toml ]] || return 1; DK='Rust build output'; DR='cargo build'; DE=1 ;; Pods) [[ -f $p/Podfile ]] || return 1; DK='CocoaPods'; DR='pod install'; DE=1 ;; .next) [[ -f $p/package.json ]] || return 1; DK='Next.js build output'; DR='npm run build'; DE=1 ;; *) return 1 ;; esac } scan_dev_artifacts() { step 'Looking for developer build folders that can be rebuilt' local H=$R$HOME d b newest age local -a found found=( ${(0)"$(find "$H" -maxdepth 7 \( -path "$H/Library" -o -path "$H/.Trash" -o -name '*.app' -o -name '*.photoslibrary' \ -o \( -name '.*' ! -name .venv ! -name .next \) \) -prune \ -o -type d \( -name node_modules -o -name .venv -o -name venv -o -name env -o -name target -o -name Pods -o -name .next \) -print0 -prune 2>/dev/null)"} ) local count=0 for d in $found; do [[ -L $d ]] && continue dev_kind $d || continue (( ++count > 200 )) && break b=$(folder_bytes $d) || continue (( b >= 50000000 )) || continue # under 50 MB is not worth anyone's time local -a nw; nw=( ${d:h}/^${d:t}(DNom[1]) ) newest=$(mtime_of ${nw[1]:-${d:h}}) age=$(( (EPOCHSECONDS - newest) / 86400 )) d=${d:A} DEV_PATHS+=("$d"); DEV_KIND[$d]=$DK; DEV_BYTES[$d]=$b; DEV_REBUILD[$d]=$DR; DEV_AGE_DAYS[$d]=$age (( DE && age >= 30 )) && DEV_ELIGIBLE[$d]=1 || DEV_ELIGIBLE[$d]=0 CAND_MTIME[$d]=$(mtime_of $d); CAND_ROOT[$d]=${HOME:A}; [[ -n $R ]] && CAND_ROOT[$d]=${H:A} (( DEV_ELIGIBLE[$d] )) && (( DEV_RECLAIM += b )) done # Biggest first local -a order; for d in $DEV_PATHS; do order+=("$(printf '%015d' ${DEV_BYTES[$d]})$US$d"); done order=(${(O)order}); DEV_PATHS=(${order##*$US}) for d in $DEV_PATHS; do (( ${#T_DEV} < 30 )) && T_DEV+=("$(row "$(nice $d)" "${DEV_KIND[$d]}" "$(size ${DEV_BYTES[$d]})" "$(plural ${DEV_AGE_DAYS[$d]} 'day ago' 'days ago')" "${DEV_REBUILD[$d]}")") done # Xcode's own folders local x=$R$HOME/Library/Developer/Xcode/DerivedData if [[ -d $x ]] && b=$(folder_bytes $x) && (( b >= 1 * GB )); then DERIVED_DATA=${x:A}; DERIVED_BYTES=$b; CAND_MTIME[$DERIVED_DATA]=$(mtime_of $x); CAND_ROOT[$DERIVED_DATA]=${${x:h}:A} T_DEV+=("$(row "$(nice $x)" 'Xcode build data' "$(size $b)" '' 'Xcode rebuilds it on the next build')") fi local spec label rel cmd for spec in 'Xcode device support files|Library/Developer/Xcode/iOS DeviceSupport|Delete folders for iOS versions you no longer test on; Xcode downloads them again if needed' \ 'Simulators|Library/Developer/CoreSimulator|Run: xcrun simctl delete unavailable (removes simulators for versions no longer installed)' \ 'Xcode archives|Library/Developer/Xcode/Archives|Keep these if you publish apps: they are needed to read crash reports' \ 'Homebrew downloads|Library/Caches/Homebrew|Run: brew cleanup' \ 'pip downloads|Library/Caches/pip|Run: pip cache purge' \ 'npm cache|.npm/_cacache|Managed by npm; run npm cache verify to tidy it' \ 'Gradle caches|.gradle/caches|Managed by Gradle; old versions can be removed from inside Gradle' \ 'CocoaPods cache|Library/Caches/CocoaPods|Run: pod cache clean --all'; do label=${spec%%|*}; rel=${${spec#*|}%%|*}; cmd=${spec##*|} [[ -d $R$HOME/$rel ]] || continue b=$(folder_bytes "$R$HOME/$rel") || continue (( b >= 1 * GB )) || continue DEV_GUIDE+=("$(row "$label" "$(size $b)" "$cmd")") T_DEV+=("$(row "$(nice $R$HOME/$rel)" "$label" "$(size $b)" '' "$cmd")") done M[base:devReclaimBytes]=$DEV_RECLAIM; M[base:derivedDataBytes]=$DERIVED_BYTES local n_el=${#${(M)${(v)DEV_ELIGIBLE}:#1}} if (( ${#DEV_PATHS} || DERIVED_BYTES || ${#DEV_GUIDE} )); then add_check 'Storage' 'Developer build folders' "$(plural ${#DEV_PATHS} 'project folder' 'project folders') found, $(plural $n_el 'in a project' 'in projects') untouched for 30+ days ($(size $DEV_RECLAIM))$( (( DERIVED_BYTES )) && print -rn -- "; Xcode DerivedData $(size $DERIVED_BYTES)")" \ $( (( DEV_RECLAIM + DERIVED_BYTES >= 2 * GB )) && print Flagged || print Clear) if (( DEV_RECLAIM + DERIVED_BYTES >= 2 * GB )); then add_finding Review 'Storage' "Rebuildable developer folders use $(size $(( DEV_RECLAIM + DERIVED_BYTES )))" \ 'Folders such as node_modules, Rust target folders and Xcode DerivedData are recreated by the project'"'"'s own tools. In projects you have not touched for a month, they are usually just taking space.' \ 'See "Developer folders" for each one and the command that rebuilds it. Odd$ Tune can move the ones you approve to the Trash, one at a time.' \ 'Inactive project folders' $n_el 'Xcode DerivedData' "$(size $DERIVED_BYTES)" set_last_finding storage High "Up to $(size $(( DEV_RECLAIM + DERIVED_BYTES ))) once the Trash is emptied. The next build of each project takes longer once." 25 fi else add_check 'Storage' 'Developer build folders' 'None found' fi return 0 } # ==== lib/diag_performance.zsh ==== # ============================================================================= # Odd$ Tune for Mac - performance diagnostics: CPU, memory, disk activity and energy. # Works from the measurements taken by sampler.zsh. Read-only. # ============================================================================= typeset -a QUIT_CANDIDATES; typeset -A QUIT_REASON # What a busy macOS process is, in plain English, and whether it should be left alone. proc_note() { # NAME -> REPLY ('' when unknown) case $1 in kernel_task) REPLY='The core of macOS. When it uses a lot of CPU, macOS is often deliberately holding the processor back to manage heat (Apple documents this). It cannot and should not be quit.' ;; WindowServer) REPLY='Draws everything on screen. It works harder with many windows, several displays or heavy animation.' ;; mds|mds_stores|mdworker|mdworker_shared|corespotlightd) REPLY='Spotlight indexing your files so search works. It is temporary and settles down after updates or large file changes. Do not turn Spotlight off.' ;; backupd|backupd-helper) REPLY='Time Machine making a backup. It finishes on its own.' ;; photoanalysisd|mediaanalysisd|photolibraryd) REPLY='Photos analysing your library (faces, objects, memories). It mostly runs while the Mac is idle and plugged in.' ;; cloudd|bird|fileproviderd) REPLY='iCloud syncing files. It settles down once syncing catches up.' ;; softwareupdated|softwareupdate_download_service) REPLY='macOS downloading or preparing an update.' ;; XProtect*|MRT|syspolicyd|trustd) REPLY='macOS malware protection or code-signature checks. Never disable these.' ;; nsurlsessiond) REPLY='Background downloads on behalf of apps and macOS.' ;; *) REPLY='' ;; esac } # The apps that are running this script (Terminal and its parents) are never suggested for quitting. typeset -A ANCESTOR_GROUP find_ancestors() { local p=$$ next i=0 while [[ $p == <-> ]] && (( p > 1 && i++ < 30 )); do [[ -n ${P_GROUP[$p]-} ]] && ANCESTOR_GROUP[${P_GROUP[$p]}]=1 next=${P_PPID[$p]-} [[ -z $next ]] && next=$(ps -o ppid= -p $p 2>/dev/null) p=${next//[^0-9]/} done # The terminal app itself, in case the parent chain could not be followed case ${TERM_PROGRAM:-} in Apple_Terminal) ANCESTOR_GROUP[Terminal]=1 ;; iTerm.app) ANCESTOR_GROUP[iTerm]=1; ANCESTOR_GROUP[iTerm2]=1 ;; esac } quit_ok() { # GROUP: can Odd$ Tune offer to quit this app? local g=$1 [[ ${G_KIND[base:$g]} == app && -n ${G_PATH[base:$g]} ]] || return 1 [[ -n ${ANCESTOR_GROUP[$g]-} ]] && return 1 case $g in Finder|Terminal|iTerm|iTerm2|'Odd$ Tune'|loginwindow|Dock|SystemUIServer|'System Settings'|'Activity Monitor') return 1 ;; esac return 0 } add_quit_candidate() { # GROUP REASON quit_ok $1 || return 0 (( ${QUIT_CANDIDATES[(Ie)$1]} )) || QUIT_CANDIDATES+=("$1") QUIT_REASON[$1]=${QUIT_REASON[$1]:+${QUIT_REASON[$1]}; }$2 } kind_label() { # KIND -> REPLY case $1 in app) REPLY='App' ;; system) REPLY='macOS' ;; service) REPLY='Background service' ;; tool) REPLY='Command-line program' ;; *) REPLY=$1 ;; esac } analyze_cpu() { local ncpu=${M[base:logicalCpus]:-0} mean=${M[base:cpuTotalPctMean]:-} n=${M[base:sampleIntervals]:-0} busy=${M[base:cpuBusyIntervals]:-0} local secs=${M[base:sampleSeconds]:-0} g cpu peak sust cores_txt if [[ -z $mean ]] || (( ! n )); then add_check 'Speed' 'Processor (CPU) use' 'Could not be measured' Skipped; return; fi cores_txt="$ncpu cores" [[ -n ${M[base:perfCores]-} && -n ${M[base:effCores]-} ]] && cores_txt="$ncpu cores (${M[base:perfCores]} performance, ${M[base:effCores]} efficiency)" # Top consumers table local -a top for g in ${SAMPLE_GROUPS_base}; do cpu=${G_CPU[base:$g]} (( cpu >= 1 )) || continue kind_label ${G_KIND[base:$g]} (( ${#T_CPU} < 12 )) && T_CPU+=("$(row "$g$( (( ${G_NPROC[base:$g]:-1} > 1 )) && print -rn -- " (${G_NPROC[base:$g]} processes)")" "$REPLY" "$(f0 $cpu)%" "$(f0 ${G_PEAK[base:$g]})%" "${G_SUST[base:$g]}%")") top+=("$g") done local result="$(f0 $mean)% of total capacity on average over $(f0 $secs) seconds (peak $(f0 ${M[base:cpuTotalPctPeak]})%), $cores_txt" [[ -n ${M[base:load5]-} ]] && result+="; load average ${M[base:load1]}/${M[base:load5]}/${M[base:load15]}" # Sustained contention across the whole processor local busy_pct=$(( busy * 100 / n )) if (( mean >= 70 && busy_pct >= 50 )); then add_check 'Speed' 'Processor (CPU) use' $result Flagged local -a contrib; local share for g in ${top[1,3]}; do share=$(( ${G_CPU[base:$g]} / ncpu )); contrib+=("$g ($(f0 $share)% of capacity)"); done local lv=Review; (( mean >= 90 )) && lv=Urgent add_bottleneck $lv 'Speed' 'The processor was close to fully busy for most of the test' \ "Over $(f0 $secs) seconds, apps and processes used $(f0 $mean)% of everything the processor can do, and it was more than 80% busy in $busy of $n samples. When the processor is this busy, everything waits its turn. Biggest users: ${(j:, :)contrib}." \ 'See "Busiest processes" below. Quit apps you are not using, or let a long task (an export, a build, a backup) finish before starting another heavy one.' \ High "Closing or pausing the biggest user could free up to $(f0 $(( ${G_CPU[base:${top[1]}]:-0} / ncpu )))% of the processor." \ $(( 55 + mean / 3 )) \ "Your Mac's processor stayed close to fully busy during the test, mostly because of ${top[1]}. Closing or pausing it may make the Mac feel faster." \ 'Average use' "$(f0 $mean)%" 'Busy samples' "$busy of $n" 'Cores' $ncpu 'Load average (1/5/15 min)' "${M[base:load1]:-?}/${M[base:load5]:-?}/${M[base:load15]:-?}" else add_check 'Speed' 'Processor (CPU) use' $result fi # Individual processes that kept at least half a core busy for most of the test for g in $top; do cpu=${G_CPU[base:$g]}; peak=${G_PEAK[base:$g]}; sust=${G_SUST[base:$g]} (( cpu >= 50 && sust >= 60 )) || continue local kind=${G_KIND[base:$g]} conf=Medium (( sust >= 80 )) && conf=High proc_note $g; local note=$REPLY case $kind in app) add_quit_candidate $g "used $(f0 $cpu)% of a core" add_bottleneck Review 'Speed' "$g kept the processor busy" \ "$g averaged $(f0 $cpu)% of one processor core (peak $(f0 $peak)%) and was busy in $sust% of the samples. On this $ncpu-core Mac that is $(f0 $(( cpu / ncpu )))% of the whole processor. Busy apps also drain the battery and make the Mac warmer." \ "If you are not using $g right now, quit it (save your work first). If it is busy all the time, check for an update, or close tabs, documents or windows it has open. Odd$ Tune can ask it to quit for you." \ $conf "Quitting $g would free about $(f0 $(( cpu / ncpu )))% of the processor." $(( 30 + cpu / ncpu )) \ "$g is keeping your Mac's processor busy. Quitting it when you are not using it may improve responsiveness and battery life." \ 'Average' "$(f0 $cpu)% of a core" 'Peak' "$(f0 $peak)%" 'Busy in samples' "$sust%" ;; system) add_bottleneck Review 'Speed' "macOS process \"$g\" was busy" \ "$g averaged $(f0 $cpu)% of one core during the test. ${note:-It is part of macOS.}" \ "${note:+This is usually temporary. }Leave it running. If it stays this busy for days, restart the Mac; if that does not help, contact Favorable Odds or Apple Support." \ Medium 'Usually none from you: it settles by itself. Restarting may help if it is stuck.' $(( 15 + cpu / ncpu )) '' \ 'Average' "$(f0 $cpu)% of a core" 'Busy in samples' "$sust%" ;; *) local first=${${(z)G_PIDS[base:$g]}[1]-} local ppath=${first:+${P_COMM[$first]-}} kind_label $kind add_bottleneck Review 'Speed' "Background program \"$g\" was busy" \ "$g ($REPLY, not an app you have open) averaged $(f0 $cpu)% of one core during the test." \ "If you recognise it, check its app's settings or update it. If you do not, run Odd$ Guard to see where it comes from. Odd$ Tune never stops background programs for you." \ $conf "Up to $(f0 $(( cpu / ncpu )))% of the processor if it is stopped or fixed." $(( 25 + cpu / ncpu )) '' \ 'Average' "$(f0 $cpu)% of a core" 'Busy in samples' "$sust%" 'Path' "$(nice $ppath)" ;; esac done return 0 } analyze_memory() { local ram=${M[base:ramBytes]:-0} worst=${M[base:memPressureWorst]:-} elev=${M[base:memPressureElevatedPct]:-0} local so=${M[base:swapOutBytesDuring]:-} sor=${M[base:swapOutPagesPerSec]:-0} comp=${M[base:compressedBytes]:-0} local swu=${M[base:swapUsedBytes]:-} secs=${M[base:sampleSeconds]:-0} free=${M[base:memFreePct]:-} local word g case $worst in 1) word=normal ;; 2) word=elevated ;; 4) word=critical ;; *) word='' ;; esac # Biggest memory users local -a bymem for g in ${(k)G_KIND}; do [[ $g == base:* ]] && bymem+=("$(printf '%015d' ${G_RSS[$g]:-0})$US${g#base:}"); done bymem=(${(O)bymem}); bymem=(${bymem##*$US}) for g in ${bymem[1,12]}; do kind_label ${G_KIND[base:$g]} T_MEM+=("$(row "$g$( (( ${G_NPROC[base:$g]:-1} > 1 )) && print -rn -- " (${G_NPROC[base:$g]} processes)")" "$REPLY" "$(size ${G_RSS[base:$g]})")") done if [[ -z $word && -z $so ]]; then add_check 'Speed' 'Memory' "${free:+$free% free right now; }pressure could not be read" Skipped; return; fi local result="${ram:+$(ramsize $ram) installed}" [[ -n $word ]] && result+=", pressure $word" (( comp )) && result+=", $(size $comp) compressed" [[ -n $swu ]] && result+=", $(size $swu) swap in use" [[ -n $so ]] && result+=", $(size $so) swapped out during the test" [[ -n $free ]] && result+=" ($free% free right now; free memory is not a problem by itself)" local swapping=0; [[ -n $so ]] && (( so >= 50000000 || sor >= 200 )) && swapping=1 local -a heavy for g in ${bymem[1,5]}; do (( ${G_RSS[base:$g]:-0} >= 500000000 )) && heavy+=("$g ($(size ${G_RSS[base:$g]}))"); done local hw='' (( ram && ram <= 8 * GB )) && hw=" This Mac has $(ramsize $ram) of memory; if this happens with your normal set of apps, the workload may simply need more memory than the Mac has (memory cannot be added to Apple silicon Macs)." if [[ $worst == 4 ]] || { [[ $worst == <-> ]] && (( worst >= 2 && elev >= 50 )) && (( swapping )) }; then add_check 'Speed' 'Memory' $result Flagged for g in ${bymem[1,5]}; do (( ${G_RSS[base:$g]:-0} >= 500000000 )) && add_quit_candidate $g "uses $(size ${G_RSS[base:$g]}) of memory"; done add_bottleneck Urgent 'Speed' 'Your Mac is running short of memory' \ "macOS reported memory pressure as $word for $elev% of the test and moved $(size ${so:-0}) out to the drive (swap) while it ran. Swapping is much slower than memory, so apps pause and feel sluggish.${heavy:+ Biggest users: ${(j:, :)heavy}.}$hw" \ 'Quit apps you are not using, and close browser tabs and documents you no longer need (save your work first). Odd$ Tune can ask the biggest apps to quit. Restarting clears out apps that have been running for weeks.' \ High 'Freeing memory stops swapping, which is one of the biggest causes of a sluggish Mac.' 88 \ 'Your Mac is experiencing sustained memory pressure while several applications are active. Closing unused applications may improve responsiveness.' \ 'Pressure' $word 'Time elevated' "$elev%" 'Swapped out during test' "$(size ${so:-0})" 'Compressed' "$(size $comp)" 'Installed' "$(ramsize $ram)" elif { [[ $worst == <-> ]] && (( worst >= 2 )) } || (( swapping )); then add_check 'Speed' 'Memory' $result Flagged for g in ${bymem[1,3]}; do (( ${G_RSS[base:$g]:-0} >= 1000000000 )) && add_quit_candidate $g "uses $(size ${G_RSS[base:$g]}) of memory"; done local conf=Medium; (( swapping && elev >= 25 )) && conf=High add_bottleneck Review 'Speed' 'Memory is under pressure' \ "During the $(f0 $secs)-second test, $( (( worst >= 2 )) && print -rn -- "macOS raised memory pressure to $word for $elev% of the time" || print -rn -- 'memory pressure stayed normal')$( (( swapping )) && print -rn -- " and $(size ${so:-0}) was swapped out to the drive"). This is the point where macOS starts working harder to make room.${heavy:+ Biggest users: ${(j:, :)heavy}.}$hw" \ 'Close apps, tabs and documents you are not using. If you often see this, keep fewer heavy apps open at once.' \ $conf 'Less swapping, so apps switch and respond more quickly.' 55 \ 'Memory is under pressure while several apps are open. Closing unused applications may improve responsiveness.' \ 'Pressure' "${word:-unknown}" 'Swapped out during test' "$(size ${so:-0})" 'Compressed' "$(size $comp)" else add_check 'Speed' 'Memory' $result # Swap left over from earlier is history, not a current problem. if [[ -n $swu ]] && (( ram && swu * 4 >= ram )); then add_check 'Speed' 'Swap used earlier' "$(size $swu) of swap is in use, but nothing was swapped during the test, so it is not slowing the Mac now" Clear fi fi return 0 } analyze_disk_activity() { local mbs=${M[base:diskMBps]:-} if [[ -z $mbs ]]; then add_check 'Speed' 'Disk activity' 'Could not be measured' Skipped; return; fi local -a culprits; local g for g in mds_stores mds backupd mdworker_shared photoanalysisd cloudd bird fileproviderd; do [[ -n ${G_CPU[base:$g]-} ]] && (( ${G_CPU[base:$g]} >= 5 )) && culprits+=("$g") done if (( mbs >= 100 )); then add_check 'Speed' 'Disk activity' "$(f0 $mbs) MB/s during the test (whole drive)" Flagged add_bottleneck Review 'Speed' 'The drive was very busy during the test' \ "The drive moved about $(f0 $mbs) MB every second while Odd$ Tune was measuring (and Odd$ Tune itself was idle). macOS does not show which app is responsible without administrator rights.${culprits:+ Busy at the same time: ${(j:, :)culprits}.}" \ 'If a backup, iCloud sync, Spotlight indexing or a large copy is running, let it finish. Activity Monitor > Disk shows which app is reading and writing.' \ Low 'Apps open and save faster once the drive is less busy.' 20 '' 'Throughput' "$(f1 $mbs) MB/s" else add_check 'Speed' 'Disk activity' "$(f1 $mbs) MB/s during the test (whole drive)" fi return 0 } analyze_energy() { local g e src=${M[base:powerSource]:-} local -a order for g in ${(k)G_ENERGY}; do [[ $g == base:* ]] && order+=("$(printf '%012.2f' ${G_ENERGY[$g]})$US${g#base:}"); done (( ${#order} )) || return 0 order=(${(O)order}); order=(${order##*$US}) for g in ${order[1,8]}; do T_ENERGY+=("$(row "$g" "$(f1 ${G_ENERGY[base:$g]})")"); done [[ $src == Battery ]] || return 0 for g in ${order[1,3]}; do e=${G_ENERGY[base:$g]} (( e >= 30 )) || continue [[ ${G_KIND[base:$g]} == system ]] && continue add_bottleneck Review 'Battery' "$g is using a lot of energy" \ "macOS rates $g's energy impact at $(f0 $e) while running on battery. High energy use shortens battery life and warms the Mac." \ "Quit $g when you are not using it, or check its settings for background activity." \ Medium 'Longer battery life and a cooler Mac.' 22 '' 'Energy impact' "$(f1 $e)" add_quit_candidate $g "energy impact $(f0 $e) on battery" done return 0 } # ==== lib/diag_startup.zsh ==== # ============================================================================= # Odd$ Tune for Mac - startup and background activity. # v0.1.0 counted .plist files. v0.2.0 reads each job's label and program, checks whether it is loaded or # running right now, measures what it used during the test, and flags helpers whose program is gone. # Read-only. Odd$ Tune never disables a service; the only change it can offer is moving the file of a # helper whose program no longer exists, in your own LaunchAgents folder, to the Trash. # ============================================================================= typeset -a S_LABEL S_SCOPE S_STATE S_CPU S_RSS S_FILE S_ORPHAN S_PROG S_APPLE S_RUNNING typeset -a ORPHAN_FILES # user-scope orphaned agents eligible for the Trash typeset -A LC_PID LOGIN_ITEMS_SEEN startup_pids_for() { # PROGRAM -> REPLY (space-separated pids running that exact program) local pid; REPLY='' [[ -n $1 ]] || return for pid in ${(k)P_COMM}; do [[ ${P_COMM[$pid]} == $1 ]] && REPLY+="$pid "; done } scan_startup() { step 'Checking startup items and background helpers (are they running, and what do they use?)' local out line pid st label out=$(launchctl list 2>/dev/null) for line in ${(f)out}; do [[ $line == PID* ]] && continue local -a w; w=(${=line}) (( ${#w} >= 3 )) || continue pid=${w[1]}; label=${w[-1]} LC_PID[$label]=$pid done local spec dir who f prog dis kind running cpu rss state n=0 n_run=0 n_orphan=0 n_third_run=0 apple local -A plist_labels for spec in "$HOME/Library/LaunchAgents|You" '/Library/LaunchAgents|Everyone (starts when anyone signs in)' '/Library/LaunchDaemons|Everyone (starts with the Mac)'; do dir=${spec%%|*}; who=${spec#*|} for f in $R$dir/*.plist(N); do (( n++ )) label=$(pl $f Label); [[ -z $label ]] && label=${${f:t}%.plist} plist_labels[$label]=1 prog=$(pl $f Program); [[ -z $prog ]] && prog=$(pl $f ProgramArguments.0) dis=$(pl $f Disabled) apple=0; [[ $label == com.apple.* ]] && apple=1 running=''; cpu=0; rss=0 if [[ ${LC_PID[$label]-} == <-> ]] && (( LC_PID[$label] > 0 )); then running=${LC_PID[$label]} else startup_pids_for $prog; running=${REPLY%% *}; fi if [[ -n $running ]]; then startup_pids_for $prog local pids=${REPLY:-$running} for pid in ${=pids}; do (( cpu += ${P_CPU[$pid]:-0} )); (( rss += ${P_RSS[$pid]:-0} )); done fi local orphan=0 if [[ -n $prog && $prog == /* && $prog != /Volumes/* && ! -e $R$prog ]] && (( ! apple )); then orphan=1; (( n_orphan++ )); fi if [[ $dis == (true|1) ]]; then state='Turned off' elif (( orphan )); then state='Program missing (cannot run)' elif [[ -n $running ]]; then state="Running (PID $running)"; (( n_run++ )); (( ! apple )) && (( n_third_run++ )) elif [[ -n ${LC_PID[$label]-} ]]; then state='Loaded, waiting' else state='Not running'; fi S_LABEL+=("$label"); S_SCOPE+=("$who"); S_STATE+=("$state"); S_CPU+=("$cpu"); S_RSS+=("$rss"); S_FILE+=("${f:A}"); S_ORPHAN+=("$orphan"); S_PROG+=("$prog"); S_APPLE+=("$apple") S_RUNNING+=("$running") if (( orphan )) && [[ $dir == $HOME/Library/LaunchAgents ]]; then ORPHAN_FILES+=("${f:A}"); remember ${f:A} ${${f:h}:A}; fi done done # Helpers that apps register directly with macOS (no plist in the folders above) and are running now. local n_app=0 for label in ${(k)LC_PID}; do [[ -n ${plist_labels[$label]-} || $label == com.apple.* || $label == (0x*|*.[0-9]*.[0-9]*) ]] && continue pid=${LC_PID[$label]} [[ $pid == <-> ]] && (( pid > 0 )) || continue [[ -n ${P_COMM[$pid]-} ]] || continue classify ${P_COMM[$pid]} ${P_UID[$pid]} [[ $GKIND == system ]] && continue (( n_app++ )); (( n_third_run++ )) S_LABEL+=("$label"); S_SCOPE+=('Registered by an app'); S_STATE+=("Running (PID $pid)"); S_CPU+=("${P_CPU[$pid]:-0}"); S_RSS+=("${P_RSS[$pid]:-0}") S_FILE+=(''); S_ORPHAN+=(0); S_PROG+=("${P_COMM[$pid]}"); S_APPLE+=(0); S_RUNNING+=("$pid") done # Login items, by name, when the person asked for them (macOS asks permission for System Events). if (( LOGIN_ITEMS )); then local li; li=$(osascript -e 'tell application "System Events" to get the name of every login item' 2>/dev/null) if [[ -n $li ]]; then for label in ${(s:, :)li}; do S_LABEL+=("$label"); S_SCOPE+=('Login item (opens when you sign in)'); S_STATE+=('Listed in Login Items'); S_CPU+=(0); S_RSS+=(0) S_FILE+=(''); S_ORPHAN+=(0); S_PROG+=(''); S_APPLE+=(0); S_RUNNING+=('') done add_check 'Speed' 'Login items' "$(plural ${#${(s:, :)li}} item items): ${li}" else add_check 'Speed' 'Login items' 'Could not be listed (macOS did not allow it). See System Settings > General > Login Items & Extensions.' Skipped fi fi STARTUP_N=$n; STARTUP_RUN=$n_run; STARTUP_ORPHAN=$n_orphan; STARTUP_THIRD=$n_third_run; STARTUP_APP=$n_app startup_report return 0 } # Table, counts, check and findings from the S_* arrays (also used by --demo). startup_report() { local n=$STARTUP_N n_run=$STARTUP_RUN n_orphan=$STARTUP_ORPHAN n_third_run=$STARTUP_THIRD n_app=$STARTUP_APP # Table, busiest first local i; local -a order for (( i = 1; i <= ${#S_LABEL}; i++ )); do order+=("$(printf '%012.3f' ${S_CPU[$i]})$(printf '%015d' ${S_RSS[$i]})$US$i"); done order=(${(O)order}) for i in ${order##*$US}; do T_STARTUP+=("$(row "${S_LABEL[$i]}" "${S_SCOPE[$i]}" "${S_STATE[$i]}" "$( [[ -n ${S_RUNNING[$i]} ]] && print -rn -- "$(f1 ${S_CPU[$i]})%")" "$( (( ${S_RSS[$i]} )) && size ${S_RSS[$i]})")") done M[base:startupItems]=$n; M[base:startupRunning]=$n_run; M[base:startupOrphans]=$n_orphan; M[base:thirdPartyHelpersRunning]=$n_third_run add_check 'Speed' 'Launch agents and daemons' "$(plural $n item items): $n_run running now, $(plural $n_orphan 'whose program is missing' 'whose programs are missing')$( (( n_app )) && print -rn -- "; $n_app more registered by apps") (Login Items are listed in System Settings)" # Findings: what is actually running and using resources, not how many files exist. local heavy_n=0 for (( i = 1; i <= ${#S_LABEL}; i++ )); do (( ${S_APPLE[$i]} )) && continue [[ -n ${S_RUNNING[$i]} ]] || continue if (( ${S_CPU[$i]} >= 10 || ${S_RSS[$i]} >= 300000000 )); then (( heavy_n++ )) add_bottleneck Review 'Speed' "Background helper \"${S_LABEL[$i]}\" is using resources" \ "It starts automatically (installed for: ${S_SCOPE[$i]}) and used $(f1 ${S_CPU[$i]})% of a processor core and $(size ${S_RSS[$i]}) of memory during the test, whether or not you are using its app." \ 'If you do not need it, turn it off in Apple menu > System Settings > General > Login Items & Extensions (under "Allow in the Background"), or remove the app it belongs to. Odd$ Tune can open that page for you.' \ High 'Fewer resources used in the background, especially after a restart.' $(( 25 + ${S_CPU[$i]%.*} / 2 )) '' \ 'Program' "$(nice ${S_PROG[$i]})" 'CPU' "$(f1 ${S_CPU[$i]})%" 'Memory' "$(size ${S_RSS[$i]})" fi done if (( n_orphan )); then add_finding Review 'Speed' "$(plural $n_orphan 'startup helper points' 'startup helpers point') to a program that is no longer installed" \ 'These are left over from apps that were removed. They cannot run, so they are not slowing the Mac, but macOS keeps trying to start them and logs an error each time.' \ "$( (( ${#ORPHAN_FILES} )) && print -rn -- 'Odd$ Tune can move the ones in your own LaunchAgents folder to the Trash, one at a time. ')Ones in /Library need an administrator: remove them in System Settings > General > Login Items & Extensions, or ask Favorable Odds." \ 'Leftovers' $n_orphan 'In your own folder' ${#ORPHAN_FILES} set_last_finding startup High 'Tidiness and fewer errors in the system log. No speed gain should be expected.' 12 fi if (( n_third_run >= 12 && ! heavy_n )); then add_finding Review 'Speed' "$(plural $n_third_run 'third-party background helper is' 'third-party background helpers are') running" \ 'None of them used much during the test, but each one starts with the Mac and takes some memory. Old ones often stay after you stop using an app.' \ 'Open Apple menu > System Settings > General > Login Items & Extensions and turn off helpers for apps you no longer use.' \ 'Running' $n_third_run set_last_finding startup Medium 'Small: a little memory and a faster start-up.' 15 fi return 0 } # ==== lib/diag_health.zsh ==== # ============================================================================= # Odd$ Tune for Mac - system health: hardware, battery and power, heat, backups, updates, drive, restart. # Read-only. Heat is reported only from what macOS itself says: Odd$ Tune never estimates temperatures. # ============================================================================= HW_MODEL=''; HW_CHIP=''; HW_ARCH='' scan_hardware() { step 'Reading hardware details' local f=$TMP/hw.json v HW_MODEL=$(sysctl -n hw.model 2>/dev/null) HW_CHIP=$(sysctl -n machdep.cpu.brand_string 2>/dev/null) if system_profiler SPHardwareDataType -json > $f 2>/dev/null; then v=$(pl $f SPHardwareDataType.0.machine_name); [[ -n $v ]] && HW_MODEL="$v${HW_MODEL:+ ($HW_MODEL)}" v=$(pl $f SPHardwareDataType.0.chip_type); [[ -n $v ]] && HW_CHIP=$v fi [[ $(sysctl -n hw.optional.arm64 2>/dev/null) == 1 ]] && HW_ARCH='Apple silicon' || HW_ARCH='Intel' v=$(sysctl -n hw.memsize 2>/dev/null); [[ $v == <-> ]] && M[base:ramBytes]=$v v=$(sysctl -n hw.logicalcpu 2>/dev/null); [[ $v == <-> ]] || v=$(sysctl -n hw.ncpu 2>/dev/null) [[ $v == <-> ]] && M[base:logicalCpus]=$v if [[ $HW_ARCH == 'Apple silicon' ]]; then v=$(sysctl -n hw.perflevel0.logicalcpu 2>/dev/null); [[ $v == <-> ]] && M[base:perfCores]=$v v=$(sysctl -n hw.perflevel1.logicalcpu 2>/dev/null); [[ $v == <-> ]] && M[base:effCores]=$v fi M[after:logicalCpus]=${M[base:logicalCpus]-} add_check 'Health' 'Hardware' "${HW_MODEL:-Unknown model}, ${HW_CHIP:-unknown processor} ($HW_ARCH), $(ramsize ${M[base:ramBytes]:-0}) memory, ${M[base:logicalCpus]:-?} cores" return 0 } scan_battery() { step 'Checking battery health and power' local f=$TMP/power.json i health cycles maxcap if ! system_profiler SPPowerDataType -json > $f 2>/dev/null; then add_check 'Health' 'Battery' 'Could not be read' Skipped; return; fi for (( i = 0; i < 8; i++ )); do health=$(pl $f "SPPowerDataType.$i.sppower_battery_health_info.sppower_battery_health") [[ -n $health ]] && break done if [[ -z $health ]]; then add_check 'Health' 'Battery' 'No battery (desktop Mac)'; HAS_BATTERY=0; return; fi HAS_BATTERY=1 cycles=$(pl $f "SPPowerDataType.$i.sppower_battery_health_info.sppower_battery_cycle_count") maxcap=$(pl $f "SPPowerDataType.$i.sppower_battery_health_info.sppower_battery_health_maximum_capacity") maxcap=${maxcap%\%} [[ $cycles == <-> ]] && M[base:batteryCycles]=$cycles [[ $maxcap == <-> ]] && M[base:batteryMaxCapacityPct]=$maxcap local result="$health" [[ $cycles == <-> ]] && result+=", $cycles charge cycles" [[ $maxcap == <-> ]] && result+=", holds $maxcap% of its original charge" if [[ $health != (Good|Normal) ]] || { [[ $maxcap == <-> ]] && (( maxcap < 80 )) }; then add_check 'Health' 'Battery' "$result" Flagged add_finding Review 'Health' 'The battery is worn and may need service' \ "macOS rates the battery \"$health\"$([[ $maxcap == <-> ]] && print -rn -- " and it holds $maxcap% of its original charge"). A worn battery runs down faster and can make the Mac slow itself down." \ 'Open Apple menu > System Settings > Battery and click the (i) next to Battery Health. If it recommends service, Apple or an Apple Authorized Service Provider can replace the battery.' \ 'Condition' "$health" 'Charge cycles' "${cycles:-unknown}" 'Maximum capacity' "${maxcap:+$maxcap%}" set_last_finding health High 'A new battery restores run time and removes any slow-down macOS applies to protect a worn one.' 35 else add_check 'Health' 'Battery' "$result" fi return 0 } scan_power() { step 'Checking power source and Low Power Mode' local b pct b=$(pmset -g batt 2>/dev/null) if [[ -z $b ]]; then add_check 'Health' 'Power' 'Could not be read' Skipped; return; fi [[ $b =~ '([0-9]+)%' ]] && { pct=$match[1]; M[base:batteryPct]=$pct } local src=${M[base:powerSource]:-unknown} lp=${M[base:lowPowerMode]:-} local result case $src in AC) result='Plugged in' ;; Battery) result="On battery${pct:+ ($pct%)}" ;; *) result='Power source not reported' ;; esac [[ $lp == 1 ]] && result+=', Low Power Mode on' || { [[ $lp == 0 ]] && result+=', Low Power Mode off' } if [[ $lp == 1 ]]; then add_check 'Health' 'Power' $result Flagged add_bottleneck Review 'Speed' 'Low Power Mode is on' \ 'Low Power Mode saves energy by limiting how fast the processor runs and pausing some background work. That is useful on battery, but it makes the Mac slower by design.' \ 'If you need full speed, open Apple menu > System Settings > Battery and set Low Power Mode to Never (or "Only on Battery"). Odd$ Tune can open that page for you.' \ High 'Full processor speed, at the cost of battery life.' 50 \ 'Low Power Mode is on, which limits processor speed by design. Turning it off when you need performance should make the Mac faster.' \ 'Low Power Mode' On 'Power source' $src else add_check 'Health' 'Power' $result fi return 0 } scan_thermal() { step 'Checking for heat-related slow-downs reported by macOS' local out lim='' out=$(pmset -g therm 2>/dev/null) if [[ -z $out ]]; then add_check 'Health' 'Heat and throttling' 'Not reported on this Mac' Skipped; return; fi [[ $out =~ 'CPU_Speed_Limit[[:space:]]*=[[:space:]]*([0-9]+)' ]] && lim=$match[1] local twl='' pwl='' [[ $out =~ '[Tt]hermal warning level[^0-9]*([0-9]+)' ]] && twl=$match[1] [[ $out =~ '[Pp]erformance warning level[^0-9]*([0-9]+)' ]] && pwl=$match[1] [[ -n $lim ]] && M[base:cpuSpeedLimitPct]=$lim local kt=${G_CPU[base:kernel_task]:-0} if [[ -n $lim ]] && (( lim < 100 )); then add_check 'Health' 'Heat and throttling' "macOS is limiting the processor to $lim% of its speed" Flagged add_bottleneck Urgent 'Speed' 'macOS is slowing the processor down to control heat' \ "macOS reports CPU_Speed_Limit = $lim%, meaning the processor is held to $lim% of its normal speed. This is usually heat: blocked vents, a hot room, dust in the fans, or a long heavy workload." \ 'Make sure the vents are clear and the Mac is on a hard surface, quit heavy apps, and let it cool. If it happens in normal use, the fans may need cleaning: contact Favorable Odds or Apple.' \ High 'Full processor speed once the Mac cools down.' 80 \ "macOS is holding your Mac's processor to $lim% of its speed, which points to heat. Clearing the vents and reducing heavy work should restore performance." \ 'CPU speed limit' "$lim%" elif [[ -n $twl$pwl ]] && (( ${twl:-0} > 0 || ${pwl:-0} > 0 )); then add_check 'Health' 'Heat and throttling' "macOS has recorded a thermal or performance warning (thermal ${twl:-none}, performance ${pwl:-none})" Flagged add_bottleneck Review 'Speed' 'macOS has recorded a heat warning' \ 'macOS keeps a record when the Mac gets hot enough that it may need to reduce performance. One has been recorded since the last restart.' \ 'Keep the vents clear and avoid soft surfaces. If the Mac runs hot in normal use, have the fans checked.' \ Medium 'Fewer slow-downs under load.' 40 '' 'Thermal warning level' "${twl:-none}" 'Performance warning level' "${pwl:-none}" elif (( kt >= 50 )); then add_check 'Health' 'Heat and throttling' "No warning recorded, but kernel_task used $(f0 $kt)% of a core" Flagged add_bottleneck Review 'Speed' 'There are signs macOS is managing heat' \ "kernel_task averaged $(f0 $kt)% of one processor core. Apple explains that macOS uses kernel_task to keep the processor from getting too hot, by taking processor time away from apps. macOS did not record a formal warning, so this is an indication, not proof." \ 'Clear the vents, use the Mac on a hard surface, and check whether charging, a hot room or an external display is adding heat.' \ Medium 'More processor time for your apps once the Mac runs cooler.' 35 '' 'kernel_task CPU' "$(f0 $kt)% of a core" else add_check 'Health' 'Heat and throttling' "No thermal or performance warning reported by macOS$([[ -n $lim ]] && print -rn -- " (processor speed limit $lim%)")" fi return 0 } scan_backup() { step 'Checking Time Machine' local dest latest d age dest=$(tmutil destinationinfo 2>&1) if [[ $dest != *'No destinations configured'* && $dest != *(Name|Kind)*:* ]]; then add_check 'Backups' 'Time Machine' 'Could not be read. See System Settings > General > Time Machine.' Skipped; return fi if [[ $dest == *'No destinations configured'* ]]; then add_check 'Backups' 'Time Machine' 'Not set up' Flagged add_finding Review 'Backups' 'This Mac is not backed up with Time Machine' \ 'Without a backup, a failed drive, a lost Mac or ransomware can take your files with it. iCloud keeps some files, but not your apps, settings or everything in your folders.' \ 'Connect an external drive and open Apple menu > System Settings > General > Time Machine, then click Add Backup Disk. Favorable Odds can set this up with you.' set_last_finding health High 'Protection against losing your files. No speed change.' 40 return fi latest=$(tmutil latestbackup 2>/dev/null) if [[ $latest =~ '([0-9]{4}-[0-9]{2}-[0-9]{2})-([0-9]{6})' ]]; then d=$match[1] age=$(( (EPOCHSECONDS - $(strftime -r '%Y-%m-%d' $d)) / 86400 )) if (( age > 14 )); then add_check 'Backups' 'Time Machine' "Last backup $d ($age days ago)" Flagged add_finding Review 'Backups' "The last Time Machine backup was $age days ago" \ 'Anything changed since then is not backed up.' \ 'Connect your backup drive and leave it connected for a while, or choose Back Up Now from the Time Machine menu (or System Settings > General > Time Machine).' \ 'Last backup' $d set_last_finding health High 'Up-to-date protection for your files.' 32 else add_check 'Backups' 'Time Machine' "Last backup $d" fi else add_check 'Backups' 'Time Machine' 'Set up. The date of the last backup needs Full Disk Access to read; see it in System Settings > General > Time Machine.' fi return 0 } scan_updates() { step 'Checking for waiting macOS updates (no internet needed)' local n n=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate LastRecommendedUpdatesAvailable 2>/dev/null) if [[ $n != <-> ]]; then add_check 'Health' 'macOS updates' "Not known yet. Check System Settings > General > Software Update" Skipped; return; fi if (( n > 0 )); then add_check 'Health' 'macOS updates' "$(plural $n update updates) waiting" Flagged add_finding Review 'Health' "$(plural $n 'macOS update is' 'macOS updates are') waiting" \ 'Updates fix security holes and bugs, and some speed problems.' \ 'Open Apple menu > System Settings > General > Software Update and install them. Save your work first; the Mac may restart.' \ 'Waiting' $n set_last_finding health High 'Security fixes, and sometimes performance fixes.' 30 else add_check 'Health' 'macOS updates' 'Up to date when the Mac last checked' fi return 0 } scan_disk() { step 'Checking drive health' # The physical drive(s) behind the startup volume: one on most Macs, two on a Fusion Drive, and an external drive when # the Mac starts from one. Falls back to disk0 when they can't be worked out. local f=$TMP/disk.plist sf=$TMP/store.plist store whole smart d i where='' local -a disks states if diskutil info -plist / > $f 2>/dev/null; then for (( i = 0; i < 8; i++ )); do store=$(pl $f APFSPhysicalStores.$i.APFSPhysicalStore) [[ $store == disk[0-9]* ]] || break whole='' diskutil info -plist $store > $sf 2>/dev/null && whole=$(pl $sf ParentWholeDisk) [[ $whole == disk<-> ]] || whole=${store%s<->} [[ $whole == disk<-> ]] && (( ! ${disks[(Ie)$whole]} )) && disks+=("$whole") done fi (( ${#disks} )) || disks=(disk0) [[ ${(j: :)disks} == disk0 ]] || where=" (${(j:, :)disks})" for d in $disks; do diskutil info -plist $d > $f 2>/dev/null && states+=("$(pl $f SMARTStatus)") || states+=('') done local st failing=0 unread=0 other='' for st in "${states[@]}"; do case $st in Failing) failing=1 ;; '') unread=1 ;; Verified) ;; *) other=$st ;; esac done if (( failing )); then smart=Failing elif (( unread )); then smart='' elif [[ -n $other ]]; then smart=$other else smart=Verified; fi M[base:driveSmart]=${smart:-unknown} case $smart in Verified) add_check 'Health' 'Drive health' "Verified$where" ;; Failing) add_check 'Health' 'Drive health' "Failing$where" Flagged add_finding Urgent 'Health' 'The drive reports that it is failing' \ "The Mac's own drive check says the drive may stop working. Files on it could be lost." \ 'Back up your files today (Time Machine or copy them to an external drive), then contact Apple or Favorable Odds about a repair.' 'Drive status' $smart set_last_finding health High 'Protecting your files from loss.' 100 \ "Your Mac's drive reports that it is failing. Back up your files today before doing anything else." ;; '') add_check 'Health' 'Drive health' "Could not be read$where" Skipped ;; *) add_check 'Health' 'Drive health' "Not reported by this drive ($smart)$where" ;; esac return 0 } scan_uptime() { step 'Checking when the Mac last restarted' local out sec days out=$(sysctl -n kern.boottime 2>/dev/null) if [[ $out =~ 'sec = ([0-9]+)' ]]; then sec=$match[1]; days=$(( (EPOCHSECONDS - sec) / 86400 )) M[base:uptimeDays]=$days if (( days >= 30 )); then add_check 'Speed' 'Last restart' "$days days ago" Flagged add_finding Review 'Speed' "The Mac hasn't restarted in $days days" \ 'Restarting finishes installing updates and closes apps and helpers that have been running for weeks. If memory or processor problems are listed above, a restart is a quick first thing to try.' \ 'Save your work and choose Apple menu > Restart. Then run Odd$ Tune again to compare.' 'Last restart' "$(day $sec)" set_last_finding health Medium 'Often helps when apps have been open for weeks; run Odd$ Tune again afterwards and compare to see whether it did.' 22 else add_check 'Speed' 'Last restart' "$(plural $days 'day ago' 'days ago')" fi else add_check 'Speed' 'Last restart' 'Could not be read' Skipped fi return 0 } # ==== lib/analyze.zsh ==== # ============================================================================= # Odd$ Tune for Mac - analysis: ranks the problems found, writes the one-line summary, and builds the # Optimization Engine's list of recommended actions for this Mac. # ============================================================================= typeset -a RANK SUMMARY='' rank_findings() { local i lv; local -a order for (( i = 1; i <= ${#F_LEVEL}; i++ )); do [[ ${F_LEVEL[$i]} == Urgent ]] && lv=1 || lv=0 order+=("$lv$(printf '%03d' ${F_SCORE[$i]:-0})$US$i") done order=(${(O)order}) RANK=(${order##*$US}) return 0 } build_summary() { local i secs=$(f0 ${M[base:sampleSeconds]:-0}) SUMMARY='' for i in $RANK; do [[ -n ${F_SUMMARY[$i]} ]] && { SUMMARY=${F_SUMMARY[$i]}; break }; done if [[ -z $SUMMARY ]]; then local nb=${#${(M)F_KIND:#bottleneck}} if (( ${#F_LEVEL} == 0 )); then SUMMARY="Nothing slowed your Mac down during the $secs-second test, and the storage and health checks came back fine." elif (( nb == 0 )); then SUMMARY="Nothing slowed your Mac down during the $secs-second test. $(plural ${#F_LEVEL} 'storage or health item is' 'storage or health items are') worth doing." else SUMMARY="Odd$ Tune found $(plural $nb 'possible cause' 'possible causes') of slowness during the $secs-second test. Start with the first item below." fi fi (( DEMO )) || [[ -n ${M[base:sampleSeconds]-} ]] || SUMMARY="Performance could not be measured on this run. ${SUMMARY}" return 0 } # The catalogue. Level 1 = safe (you approve each change; files go to the Trash). Level 2 = advanced # (startup behaviour, developer files: each item needs its own yes). Restricted operations are never offered: # see "What Odd$ Tune will never do" in the report and README. build_recommendations() { local b=0 f n if (( ${#INSTALLER_PATHS} )); then b=0; for f in $INSTALLER_PATHS; do (( b += ${CAND_SIZE[$f]:-0} )); done add_rec installers "Move $(plural ${#INSTALLER_PATHS} 'old installer' 'old installers') to the Trash" 1 \ 'You choose: all of them, one at a time, or none' $b ${#INSTALLER_PATHS} \ 'Installers are only needed while you install an app.' 'Open the Trash, right-click the file and choose Put Back.' fi b=0; for f in $OLD_DL_PATHS; do (( b += ${CAND_SIZE[$f]:-0} )); done if (( ${#OLD_DL_PATHS} && b >= 500000000 )); then add_rec old-downloads "Review $(plural ${#OLD_DL_PATHS} 'large old download' 'large old downloads'), one at a time" 1 \ 'Each file needs its own yes' $b ${#OLD_DL_PATHS} \ 'Not modified for 90+ days; most are one-off files.' 'Open the Trash, right-click the file and choose Put Back.' fi if (( ${#DUP_HASHES} )); then add_rec duplicates "Review $(plural ${#DUP_HASHES} 'set' 'sets') of identical files" 1 \ 'For each set you pick the copy to keep; at least one copy always stays' $DUP_RECLAIM ${#DUP_HASHES} \ 'Contents verified identical with SHA-256. Savings may be smaller where APFS shares storage between copies.' 'Open the Trash, right-click the file and choose Put Back.' fi if (( ${#QUIT_CANDIDATES} )); then add_rec quit-apps "Ask $(plural ${#QUIT_CANDIDATES} 'busy app' 'busy apps') to quit (${(j:, :)QUIT_CANDIDATES})" 1 \ 'Each app needs its own yes. Apps ask you to save unsaved work; Odd$ Tune never force-quits' 0 ${#QUIT_CANDIDATES} \ 'They used a lot of processor time, memory or energy during the test.' 'Open the app again from Applications or the Dock.' fi add_rec settings 'Open the macOS settings page for a fix (Storage, Login Items, Battery, Activity Monitor)' 1 \ 'Nothing changes until you change it in System Settings' 0 0 \ 'Some fixes belong to macOS itself; Odd$ Tune takes you to the right page.' 'Not needed: opening a page changes nothing.' n=${#${(M)${(v)DEV_ELIGIBLE}:#1}} if (( n )); then add_rec dev-folders "Move $(plural $n 'rebuildable developer folder' 'rebuildable developer folders') from inactive projects to the Trash" 2 \ 'Advanced. Each folder needs its own yes' $DEV_RECLAIM $n \ 'node_modules, target and similar folders are recreated by the project'"'"'s tools.' 'Put Back from the Trash, or run the rebuild command shown for that folder.' fi if [[ -n $DERIVED_DATA ]]; then add_rec derived-data 'Move Xcode DerivedData to the Trash' 2 \ 'Advanced. Needs its own yes, and Xcode must be closed' $DERIVED_BYTES 1 \ 'Xcode recreates it on the next build.' 'Put Back from the Trash, or simply build again in Xcode.' fi if (( ${#ORPHAN_FILES} )); then add_rec orphan-agents "Move $(plural ${#ORPHAN_FILES} 'leftover startup helper' 'leftover startup helpers') to the Trash" 2 \ 'Advanced. Each one needs its own yes; only helpers whose program is missing, in your own LaunchAgents folder' 0 ${#ORPHAN_FILES} \ 'Their program has been removed, so they can never run.' 'Put Back from the Trash, then log out and back in.' fi if (( ${M[base:thirdPartyHelpersRunning]:-0} )); then add_rec startup-review 'Turn off background helpers you do not need' 2 \ 'You make the change yourself in System Settings > General > Login Items & Extensions' 0 ${M[base:thirdPartyHelpersRunning]} \ 'Odd$ Tune never disables services itself, because it cannot know which ones an app depends on.' 'Turn the switch back on in the same place.' fi # Background workload advice: report only, built from what was busy. local g; local -a sched for g in backupd photoanalysisd mediaanalysisd mds_stores mds cloudd bird softwareupdated; do [[ -n ${G_CPU[base:$g]-} ]] && (( ${G_CPU[base:$g]} >= 20 )) && sched+=("$g") done if (( ${#sched} )); then add_rec schedule 'Let background work run when you are not using the Mac' 2 \ 'Guidance only' 0 ${#sched} \ "macOS work was busy during the test (${(j:, :)sched}). Leaving the Mac on, plugged in and awake for a while (for example overnight) lets backups, indexing, photo analysis and iCloud catch up, so they compete less with you during the day." \ 'Not needed.' fi return 0 } # ==== lib/optimize.zsh ==== # ============================================================================= # Odd$ Tune Optimization Engine. # # Runs in Terminal after the scan, only when you are there to answer. Every action: # - is listed with its risk level and what it would free, # - needs your yes (the default answer is always no), # - re-checks each item immediately before changing it (path_guard in core.zsh), # - moves files to the Trash through Finder (Put Back works) and never deletes anything itself, # - is written to a change log as it happens. # Ctrl-C stops after the item in progress; everything already done is kept and reported. # # Never offered (Level 3, restricted): deleting system files, clearing swap or "purging" RAM, disabling # security protections, Spotlight, Time Machine or Apple services, changing kernel or SIP settings, # force-quitting anything, deleting app databases or personal files outright, or any command that needs # your administrator password. # ============================================================================= CHANGES_MADE=0; TRASHED_BYTES=0; CANCELLED=0 typeset -a TRASHED_PATHS settings_url() { # NAME -> REPLY case $1 in storage) REPLY='x-apple.systempreferences:com.apple.settings.Storage' ;; login) REPLY='x-apple.systempreferences:com.apple.LoginItems-Settings.extension' ;; battery) REPLY='x-apple.systempreferences:com.apple.Battery-Settings.extension' ;; update) REPLY='x-apple.systempreferences:com.apple.Software-Update-Settings.extension' ;; timemachine) REPLY='x-apple.systempreferences:com.apple.Time-Machine-Settings.extension' ;; *) REPLY='' ;; esac } open_settings() { # NAME LABEL settings_url $1 if open -- $REPLY >/dev/null 2>&1; then add_action 'Open settings' "System Settings > $2" 'Opened (nothing was changed)' 1 0 else add_action 'Open settings' "System Settings > $2" 'Could not open it. Open Apple menu > System Settings and go there yourself.' 0 0; fi } # Move one recorded item to the Trash after re-checking it. TYPE is f (file) or d (folder). trash_one() { # PATH TYPE ACTION RECOVERY local p=$1 type=$2 act=$3 rec=$4 b rc local root=${CAND_ROOT[$p]-} if [[ -z $root ]]; then add_action $act "$(nice $p)" 'Skipped: not found by this scan' 0 0; return 1; fi local sz='' if [[ $type == f ]]; then b=${CAND_SIZE[$p]:-$(bytes_of $p)}; sz=${CAND_SIZE[$p]-} else b=${DEV_BYTES[$p]:-0}; [[ $p == $DERIVED_DATA ]] && b=$DERIVED_BYTES; fi log_line $act "$(nice $p)" 'About to move to the Trash' trash_checked $p $root $type "$sz" "${CAND_MTIME[$p]-}"; rc=$? case $rc in 0) add_action $act "$(nice $p)" 'Moved to the Trash' 1 $b $rec (( CHANGES_MADE++ )); (( TRASHED_BYTES += b )); TRASHED_PATHS+=("$p") T_MOVED+=("$(row "$(nice $p)" "$(size $b)" 'Moved to the Trash')") ;; 2) add_action $act "$(nice $p)" "Skipped: $GUARD_WHY" 0 $b T_MOVED+=("$(row "$(nice $p)" "$(size $b)" "Skipped: $GUARD_WHY")") ;; *) add_action $act "$(nice $p)" 'Not moved (Finder did not move it)' 0 $b T_MOVED+=("$(row "$(nice $p)" "$(size $b)" 'Not moved (Finder did not move it)')") ;; esac return $rc } opt_installers() { local f total=0 print; print -r -- "Old installers in your Downloads folder (at least a week old):" for f in $INSTALLER_PATHS; do print -r -- " $(nice $f) ($(size ${CAND_SIZE[$f]:-0}))"; (( total += ${CAND_SIZE[$f]:-0} )); done print -r -- "Moving them frees $(size $total) once you empty the Trash. You can put them back from the Trash." print -r -- 'macOS may ask whether Terminal can control Finder.' ask 'Type yes to move them all, pick to choose one at a time, or press Return to skip: ' || return case $REPLY in yes|y) for f in $INSTALLER_PATHS; do (( CANCELLED )) && break; trash_one $f f 'Old installer' 'Put Back from the Trash'; done ;; pick|p) for f in $INSTALLER_PATHS; do (( CANCELLED )) && break ask " Move $(nice $f) ($(size ${CAND_SIZE[$f]:-0}))? [y/N] " || break yes_answer && trash_one $f f 'Old installer' 'Put Back from the Trash' done ;; *) print -r -- 'Skipped. Nothing was moved.' ;; esac } opt_old_downloads() { local f print; print -r -- 'The largest files in Downloads that have not been modified for 90+ days, one at a time.' print -r -- 'Answer y to move a file to the Trash, Return to keep it, or q to stop.' for f in $OLD_DL_PATHS; do (( CANCELLED )) && break [[ -e $f ]] || continue (( ${TRASHED_PATHS[(Ie)$f]} )) && continue ask " $(nice $f) ($(size ${CAND_SIZE[$f]:-0}), modified $(day ${CAND_MTIME[$f]:-0}))? [y/N/q] " || break [[ $REPLY == q ]] && break yes_answer && trash_one $f f 'Old download' 'Put Back from the Trash' done } # Duplicates: you choose the copy to keep. Before anything moves, every copy is fingerprinted again, so a # file that changed since the scan is never mistaken for a copy, and the one you keep is confirmed intact. opt_duplicates() { local hk i keep f h0 hn ok n=0 total=${#DUP_HASHES} local -a group print; print -r -- 'For each set of identical files, choose the one copy to keep. The others go to the Trash.' for hk in $DUP_HASHES; do (( CANCELLED )) && break (( n++ )) group=("${(@ps:$RS:)DUP_FILES[$hk]}"); group=(${group:#}) print; print -r -- "Set $n of $total: $(plural ${#group} copy copies) of $(size ${DUP_SIZE[$hk]}) each" for (( i = 1; i <= ${#group}; i++ )); do print -r -- " $i) $(nice ${group[$i]}) (modified $(day ${CAND_MTIME[${group[$i]}]:-0}))"; done ask " Number of the copy to KEEP, Return to skip this set, or q to stop: " || break [[ $REPLY == q ]] && break [[ $REPLY == <-> ]] && (( REPLY >= 1 && REPLY <= ${#group} )) || { [[ -n $REPLY ]] && print -r -- ' Not a number from the list: skipped this set.'; continue } keep=${group[$REPLY]} # Re-verify: the copy you keep must still be there, unchanged, with the same fingerprint. ok=1 path_guard $keep ${CAND_ROOT[$keep]} f ${CAND_SIZE[$keep]} ${CAND_MTIME[$keep]} || ok=0 if (( ok )); then h0=$(shasum -a 256 < $keep 2>/dev/null); h0=${h0%% *}; [[ $h0 == ${hk#*:} ]] || ok=0; fi if (( ! ok )); then add_action 'Duplicate files' "$(nice $keep)" 'Skipped the whole set: the copy to keep changed since the scan' 0 0 continue fi for f in $group; do [[ $f == $keep ]] && continue (( CANCELLED )) && break hn=$(shasum -a 256 < $f 2>/dev/null); hn=${hn%% *} if [[ $hn != $h0 ]]; then add_action 'Duplicate files' "$(nice $f)" 'Skipped: no longer identical to the copy you kept' 0 0; continue; fi trash_one $f f 'Duplicate files' "Put Back from the Trash. The copy kept is $(nice $keep)" done done } # Asks an app to quit the normal way (like choosing Quit from its menu). The app shows its own "save # changes?" dialog if it has unsaved work. Odd$ Tune never force-quits. app_running() { # GROUP: true while any of its processes is still running local pid; local app=${G_PATH[base:$1]} for pid in ${=G_PIDS[base:$1]}; do [[ $(ps -o comm= -p $pid 2>/dev/null) == $app/* ]] && return 0; done return 1 } opt_quit_apps() { local g bid w print; print -r -- 'Apps that were busy during the test. Odd$ Tune asks each one to quit normally;' print -r -- 'if it has unsaved work it will ask you to save first. macOS may ask whether Terminal can control the app.' for g in $QUIT_CANDIDATES; do (( CANCELLED )) && break if ! app_running $g; then add_action 'Quit app' $g 'Already closed' 1 0; continue; fi ask " Ask $g to quit? (${QUIT_REASON[$g]}) [y/N] " || break yes_answer || continue bid=$(pl "$R${G_PATH[base:$g]}/Contents/Info.plist" CFBundleIdentifier) if [[ $bid != [A-Za-z0-9][A-Za-z0-9.-]# ]]; then add_action 'Quit app' $g 'Skipped: could not identify the app safely' 0 0; continue; fi log_line 'Quit app' $g "Asking $bid to quit" osascript -e 'on run argv' -e 'tell application id (item 1 of argv) to quit' -e 'end run' -- "$bid" >/dev/null 2>&1 for (( w = 0; w < QUIT_WAIT * 4; w++ )); do app_running $g || break; sleep 0.25; done if app_running $g; then add_action 'Quit app' $g 'Still open: it may be waiting for you to save or confirm. Nothing was forced.' 0 0 else add_action 'Quit app' $g 'Quit' 1 0 'Open it again from Applications or the Dock'; (( CHANGES_MADE++ )) fi done } opt_dev_folders() { local d print; print -r -- 'Rebuildable developer folders in projects you have not changed for 30+ days. Advanced: each needs its own yes.' for d in $DEV_PATHS; do (( ${DEV_ELIGIBLE[$d]:-0} )) || continue (( CANCELLED )) && break print -r -- " $(nice $d)" print -r -- " ${DEV_KIND[$d]}, $(size ${DEV_BYTES[$d]}), project last changed $(plural ${DEV_AGE_DAYS[$d]} 'day ago' 'days ago'). Rebuild with: ${DEV_REBUILD[$d]}" ask ' Move it to the Trash? [y/N/q] ' || break [[ $REPLY == q ]] && break yes_answer && trash_one $d d 'Developer folder' "Put Back from the Trash, or in the project folder run: ${DEV_REBUILD[$d]}" done } opt_derived_data() { print; print -r -- "Xcode DerivedData: $(size $DERIVED_BYTES). Xcode rebuilds it on the next build (the first build takes longer)." if ps -axo comm= 2>/dev/null | grep -q '/Xcode\.app/Contents/MacOS/Xcode$'; then print -r -- ' Xcode is open. Quit Xcode first, then run Odd$ Tune again.' add_action 'Xcode DerivedData' "$(nice $DERIVED_DATA)" 'Skipped: Xcode was open' 0 $DERIVED_BYTES; return fi ask ' Move DerivedData to the Trash? [y/N] ' || return yes_answer && trash_one $DERIVED_DATA d 'Xcode DerivedData' 'Put Back from the Trash, or build again in Xcode' } opt_orphan_agents() { local f i label prog print; print -r -- 'Startup helpers in your LaunchAgents folder whose program has been removed. Advanced: each needs its own yes.' for f in $ORPHAN_FILES; do (( CANCELLED )) && break label=''; prog='' for (( i = 1; i <= ${#S_FILE}; i++ )); do [[ ${S_FILE[$i]} == $f ]] && { label=${S_LABEL[$i]}; prog=${S_PROG[$i]}; break }; done print -r -- " $label" print -r -- " File: $(nice $f)" print -r -- " Program it starts (missing): $prog" # Check again that the program is still missing: if the app was reinstalled, leave its helper alone. if [[ -e $R$prog ]]; then add_action 'Leftover startup helper' $label 'Skipped: its program is installed again' 0 0; continue; fi ask ' Move this helper file to the Trash? [y/N/q] ' || break [[ $REPLY == q ]] && break yes_answer && trash_one $f f 'Leftover startup helper' 'Put Back from the Trash, then log out and back in' done (( CHANGES_MADE )) && print -r -- ' macOS forgets moved helpers the next time you log out and back in.' } opt_settings() { print; print -r -- 'Open a macOS settings page:' print -r -- ' 1) Storage 2) Login Items & Extensions 3) Battery 4) Software Update 5) Time Machine 6) Activity Monitor' ask ' Number, or Return to go back: ' || return case $REPLY in 1) open_settings storage 'General > Storage' ;; 2) open_settings login 'General > Login Items & Extensions' ;; 3) open_settings battery 'Battery' ;; 4) open_settings update 'General > Software Update' ;; 5) open_settings timemachine 'General > Time Machine' ;; 6) if open -a 'Activity Monitor' >/dev/null 2>&1; then add_action 'Open app' 'Activity Monitor' 'Opened (nothing was changed)' 1 0 else add_action 'Open app' 'Activity Monitor' 'Could not open it (Applications > Utilities > Activity Monitor)' 0 0; fi ;; esac } menu_ids() { # recommendations that have a Terminal action local id; MENU=() for id in $R_ID; do [[ $id == (installers|old-downloads|duplicates|quit-apps|dev-folders|derived-data|orphan-agents|startup-review) ]] && MENU+=("$id"); done (( ${R_ID[(Ie)settings]} )) && MENU+=(settings) # always last } run_optimizer() { local interactive=0 [[ -t 0 && -t 1 ]] && interactive=1 [[ -n $R && -n ${ODDS_TUNE_TEST_TTY:-} ]] && interactive=1 # automated tests only (needs the fake-Mac root) (( interactive && ! SCAN_ONLY && ! DEMO )) || return 0 local -a MENU; local i id idx pick done_ids menu_ids (( ${#MENU} > 1 )) || return 0 # only "open settings": nothing worth asking about trap 'CANCELLED=1; print -r -- " (stopping: finishing the current item first)"' INT print print -r -- "Odd\$ Tune Optimization Engine" print -r -- 'Nothing changes unless you say yes. Files go to the Trash, where you can put them back.' while (( ! CANCELLED && ! INPUT_CLOSED )); do print i=0 for id in $MENU; do (( i++ )) idx=$(rec_index $id) local lvl='Safe'; (( ${R_RISK[$idx]} == 2 )) && lvl='Advanced' local free=''; (( ${R_RECLAIM[$idx]} )) && free=" - frees up to $(size ${R_RECLAIM[$idx]})" local d=''; (( ${done_ids[(Ie)$id]} )) && d=' (reviewed)' print -r -- " $i. [$lvl] ${R_TITLE[$idx]}$free$d" done ask 'Type the numbers to review (for example: 1 3), or press Return to finish: ' || break [[ -z $REPLY ]] && break for pick in ${=REPLY//,/ }; do (( CANCELLED )) && break [[ $pick == <-> ]] && (( pick >= 1 && pick <= ${#MENU} )) || { print -r -- " \"$pick\" is not on the list."; continue } id=${MENU[$pick]} case $id in installers) opt_installers ;; old-downloads) opt_old_downloads ;; duplicates) opt_duplicates ;; quit-apps) opt_quit_apps ;; dev-folders) opt_dev_folders ;; derived-data) opt_derived_data ;; orphan-agents) opt_orphan_agents ;; startup-review) open_settings login 'General > Login Items & Extensions'; print -r -- ' Turn off helpers you do not need under "Allow in the Background".' ;; settings) opt_settings ;; esac done_ids+=("$id") done done trap - INT (( CANCELLED )) && add_action 'Optimization' 'Remaining items' 'Stopped by you (Ctrl-C). Everything listed above was kept as it was done.' 0 0 local n_ok=${#${(M)A_OK:#1}} print if (( CHANGES_MADE )); then print -r -- "Done: $(plural $CHANGES_MADE change changes) made$( (( TRASHED_BYTES )) && print -rn -- ", $(size $TRASHED_BYTES) moved to the Trash (empty the Trash to free the space)")." else print -r -- 'No changes were made.' fi return 0 } # ==== lib/benchmark.zsh ==== # ============================================================================= # Odd$ Tune for Mac - before-and-after measurement. # # After the Optimization Engine changes something, the same measurements are repeated with the same # sampling window. A change is called "measurable" only when it is larger than the variation seen within # the samples themselves (about two standard errors) and larger than a minimum size. Otherwise the # report says "No measurable change". No percentage improvement is ever claimed for anything else. # # --compare FILE does the same against an earlier Odd$ Tune report (for example, before and after a restart). # ============================================================================= typeset -a CMP_METRIC CMP_BEFORE CMP_AFTER CMP_CHANGE CMP_VERDICT CMP_NOTES typeset -a BENCH_METRIC BENCH_BEFORE BENCH_AFTER BENCH_CHANGE BENCH_VERDICT BENCH_NOTES typeset -a PREV_METRIC PREV_BEFORE PREV_AFTER PREV_CHANGE PREV_VERDICT PREV_NOTES BENCH_DONE=0; BENCH_COMPARABLE=0; PREV_DONE=0; PREV_COMPARABLE=0; PREV_FILE=''; PREV_WHEN=''; PREV_VERSION='' measure_after() { print step "Measuring again for the before-and-after comparison ($(f0 $SAMPLE_SECONDS) seconds, the same as before)" (( CHANGES_MADE )) && sleep ${SETTLE_SECONDS:-5} # let quit apps finish closing before measuring measure_disk_free after measure_power_source after sample_system after $SAMPLE_SECONDS bench_responsiveness after compare_tags base after BENCH_METRIC=("${CMP_METRIC[@]}"); BENCH_BEFORE=("${CMP_BEFORE[@]}"); BENCH_AFTER=("${CMP_AFTER[@]}") BENCH_CHANGE=("${CMP_CHANGE[@]}"); BENCH_VERDICT=("${CMP_VERDICT[@]}"); BENCH_NOTES=("${CMP_NOTES[@]}") BENCH_COMPARABLE=$CMP_OK; BENCH_DONE=1 return 0 } cmp_row() { CMP_METRIC+=("$1"); CMP_BEFORE+=("$2"); CMP_AFTER+=("$3"); CMP_CHANGE+=("$4"); CMP_VERDICT+=("$5") } # Is the difference between two sampled means bigger than the noise? Welch-style: |difference| must be at # least 2 standard errors and at least MIN. Sets SIG to lower|higher|none. significance() { # MEAN_A SD_A N_A MEAN_B SD_B N_B MIN local -F ma=$1 sa=$2 na=$3 mb=$4 sb=$5 nb=$6 mn=$7 se d (( na < 1 )) && na=1; (( nb < 1 )) && nb=1 se=$(( sqrt(sa * sa / na + sb * sb / nb) )) d=$(( mb - ma )) if (( (d < 0 ? -d : d) >= (2 * se > mn ? 2 * se : mn) )); then (( d < 0 )) && SIG=lower || SIG=higher else SIG=none; fi } compare_tags() { # A B (A = before, B = after) local a=$1 b=$2 v1 v2 d verdict key label w1 w2 e1 e2 CMP_METRIC=(); CMP_BEFORE=(); CMP_AFTER=(); CMP_CHANGE=(); CMP_VERDICT=(); CMP_NOTES=() CMP_OK=1 # Conditions local s1=${M[${a}:sampleSeconds]:-0} s2=${M[${b}:sampleSeconds]:-0} if [[ -n ${M[${a}:powerSource]-} && -n ${M[${b}:powerSource]-} && ${M[${a}:powerSource]} != ${M[${b}:powerSource]} ]]; then CMP_OK=0; CMP_NOTES+=("The power source changed (${M[${a}:powerSource]} before, ${M[${b}:powerSource]} after). macOS runs differently on battery, so processor and responsiveness figures are not directly comparable.") fi if (( s1 > 0 && s2 > 0 )) && (( s2 < s1 * 0.8 || s2 > s1 * 1.25 )); then CMP_OK=0; CMP_NOTES+=("The two measurements used different lengths ($(f0 $s1) s and $(f0 $s2) s).") fi [[ ${M[${a}:lowPowerMode]-} != ${M[${b}:lowPowerMode]-} && -n ${M[${a}:lowPowerMode]-} && -n ${M[${b}:lowPowerMode]-} ]] && { CMP_OK=0; CMP_NOTES+=('Low Power Mode was switched between the two measurements.') } CMP_NOTES+=('Each measurement is a short sample of whatever the Mac was doing at the time. Opening or closing apps between them changes the result as much as any fix does.') # 1. Free space: exact. v1=${M[${a}:diskFreeBytes]-}; v2=${M[${b}:diskFreeBytes]-} if [[ -n $v1 && -n $v2 ]]; then d=$(( v2 - v1 )) if (( d >= 100000000 )); then verdict="$(size $d) more free space" elif (( d <= -100000000 )); then verdict="$(size $(( -d ))) less free space (something else wrote files meanwhile)" else verdict='No change'; fi (( ${TRASHED_BYTES:-0} && d < 100000000 )) && [[ $b == after ]] && verdict+=": files moved to the Trash still use space until you empty it" local chg='0'; (( d > 0 )) && chg="+$(size $d)"; (( d < 0 )) && chg="-$(size $(( -d )))" cmp_row 'Available disk space' "$(size $v1)" "$(size $v2)" "$chg" "$verdict" fi if [[ $b == after ]] && (( ${TRASHED_BYTES:-0} )); then cmp_row 'Space waiting in the Trash from this run' '' "$(size $TRASHED_BYTES)" '' 'Freed when you empty the Trash' fi # 2. CPU v1=${M[${a}:cpuTotalPctMean]-}; v2=${M[${b}:cpuTotalPctMean]-} if [[ -n $v1 && -n $v2 ]]; then significance $v1 ${M[${a}:cpuTotalPctSd]:-0} ${M[${a}:sampleIntervals]:-1} $v2 ${M[${b}:cpuTotalPctSd]:-0} ${M[${b}:sampleIntervals]:-1} 3 case $SIG in lower) verdict='Lower (measurable)' ;; higher) verdict='Higher (measurable)' ;; *) verdict='No measurable change' ;; esac cmp_row 'CPU utilization (average, % of total capacity)' "$(f1 $v1)%" "$(f1 $v2)%" "$(f1 $(( v2 - v1 ))) points" $verdict fi # 3. Memory pressure v1=${M[${a}:memPressureWorst]-}; v2=${M[${b}:memPressureWorst]-} if [[ -n $v1 && -n $v2 ]]; then case $v1 in 1) w1=Normal ;; 2) w1=Elevated ;; 4) w1=Critical ;; *) w1=$v1 ;; esac case $v2 in 1) w2=Normal ;; 2) w2=Elevated ;; 4) w2=Critical ;; *) w2=$v2 ;; esac e1=${M[${a}:memPressureElevatedPct]:-0}; e2=${M[${b}:memPressureElevatedPct]:-0} if (( v2 < v1 )); then verdict='Lower (measurable)' elif (( v2 > v1 )); then verdict='Higher (measurable)' elif (( v1 >= 2 && e2 + 25 <= e1 )); then verdict='Elevated less of the time' elif (( v1 >= 2 && e2 >= e1 + 25 )); then verdict='Elevated more of the time' else verdict='No measurable change'; fi cmp_row 'Memory pressure (worst level seen)' "$w1$( (( v1 >= 2 )) && print -rn -- " ($e1% of the time)")" "$w2$( (( v2 >= 2 )) && print -rn -- " ($e2% of the time)")" '' $verdict fi # 4. Swap activity v1=${M[${a}:swapOutBytesDuring]-}; v2=${M[${b}:swapOutBytesDuring]-} if [[ -n $v1 && -n $v2 ]]; then if (( v1 < 10000000 && v2 < 10000000 )); then verdict='None in either measurement' else significance ${M[${a}:swapOutPagesPerSec]:-0} ${M[${a}:swapOutPagesPerSecSd]:-0} ${M[${a}:sampleIntervals]:-1} ${M[${b}:swapOutPagesPerSec]:-0} ${M[${b}:swapOutPagesPerSecSd]:-0} ${M[${b}:sampleIntervals]:-1} 20 case $SIG in lower) verdict='Less swapping (measurable)' ;; higher) verdict='More swapping (measurable)' ;; *) verdict='No measurable change' ;; esac fi cmp_row 'Swap activity (written out during the measurement)' "$(size $v1)" "$(size $v2)" '' $verdict fi v1=${M[${a}:compressedBytes]-}; v2=${M[${b}:compressedBytes]-} if [[ -n $v1 && -n $v2 ]]; then d=$(( v2 - v1 )) (( d <= -200000000 )) && verdict='Less compressed' || { (( d >= 200000000 )) && verdict='More compressed' || verdict='No meaningful change' } cmp_row 'Compressed memory' "$(size $v1)" "$(size $v2)" '' $verdict fi # 5. Background activity v1=${M[${a}:activeProcessCount]-}; v2=${M[${b}:activeProcessCount]-} if [[ -n $v1 && -n $v2 ]]; then d=$(( v2 - v1 )) (( d < 0 )) && verdict="$(( -d )) fewer" || { (( d > 0 )) && verdict="$d more" || verdict='Same' } cmp_row 'Active processes (using 1% of a core or more)' $v1 $v2 "$( (( d > 0 )) && print -rn -- +)$d" $verdict fi v1=${M[${a}:backgroundActiveCount]-}; v2=${M[${b}:backgroundActiveCount]-} if [[ -n $v1 && -n $v2 ]]; then d=$(( v2 - v1 )) (( d < 0 )) && verdict="$(( -d )) fewer" || { (( d > 0 )) && verdict="$d more" || verdict='Same' } cmp_row 'Active third-party background processes' $v1 $v2 "$( (( d > 0 )) && print -rn -- +)$d" $verdict fi v1=${M[${a}:processCount]-}; v2=${M[${b}:processCount]-} [[ -n $v1 && -n $v2 ]] && cmp_row 'Processes running' $v1 $v2 "$( (( v2 - v1 > 0 )) && print -rn -- +)$(( v2 - v1 ))" '' # 6. Responsiveness proxy, shown for reference only. In testing, identical before/after runs produced # "measurable" differences too often (CPU frequency changes and performance/efficiency core scheduling # move it by more than any fix does), so it is never used to claim an improvement. for key label in spawnMs 'Responsiveness check: start a small program (median)'; do v1=${M[${a}:${key}Median]-}; v2=${M[${b}:${key}Median]-} [[ -n $v1 && -n $v2 ]] || continue cmp_row $label "$(printf '%.2f' $v1) ms" "$(printf '%.2f' $v2) ms" '' 'Reference only: varies too much between identical runs to show a real change' done return 0 } # ---- Comparing with an earlier report ------------------------------------------ PREV_KEYS=(diskFreeBytes diskTotalBytes cpuTotalPctMean cpuTotalPctSd sampleIntervals sampleSeconds memPressureWorst memPressureElevatedPct swapOutBytesDuring swapOutPagesPerSec swapOutPagesPerSecSd compressedBytes activeProcessCount backgroundActiveCount processCount spawnMsMedian spawnMsQ1 spawnMsQ3 powerSource lowPowerMode) load_previous() { # FILE local f=$1 k v tool PREV_FILE=$f if [[ ! -f $f || -L $f || ! -r $f ]]; then CMP_LOAD_ERR='that file could not be read'; return 1; fi (( $(bytes_of $f) <= 20000000 )) || { CMP_LOAD_ERR='that file is too large to be an Odd$ Tune report'; return 1 } tool=$(pl $f tool) [[ $tool == 'Odd$ Tune' ]] || { CMP_LOAD_ERR='that file is not an Odd$ Tune report'; return 1 } PREV_WHEN=$(pl $f checkedAt); PREV_VERSION=$(pl $f version) for k in $PREV_KEYS; do v=$(pl $f metrics.baseline.$k) [[ -n $v ]] && M[prev:$k]=$v done [[ -z ${M[prev:diskFreeBytes]-} ]] && { v=$(pl $f storage.freeBytes); [[ $v == <-> && $v != 0 ]] && M[prev:diskFreeBytes]=$v } # Processes that were heavy in the earlier report local i name cpu mem typeset -gA PREV_HEAVY for (( i = 0; i < 40; i++ )); do name=$(pl $f processes.$i.name); [[ -z $name ]] && break cpu=$(pl $f processes.$i.cpuMeanPct); mem=$(pl $f processes.$i.memoryBytes) PREV_HEAVY[$name]="${cpu:-0}$US${mem:-0}" done return 0 } compare_previous() { compare_tags prev base PREV_METRIC=("${CMP_METRIC[@]}"); PREV_BEFORE=("${CMP_BEFORE[@]}"); PREV_AFTER=("${CMP_AFTER[@]}") PREV_CHANGE=("${CMP_CHANGE[@]}"); PREV_VERDICT=("${CMP_VERDICT[@]}"); PREV_NOTES=("${CMP_NOTES[@]}") PREV_COMPARABLE=$CMP_OK; PREV_DONE=1 [[ $PREV_VERSION == 0.1.* ]] && PREV_NOTES=("The earlier report is from Odd\$ Tune $PREV_VERSION, which did not measure performance, so only free space can be compared." "${PREV_NOTES[@]}") # Apps that were heavy both times: a pattern, not a one-off. local g pc pm cc cm local -a repeat for g in ${SAMPLE_GROUPS_base}; do [[ -n ${PREV_HEAVY[$g]-} ]] || continue [[ ${G_KIND[base:$g]} == system ]] && continue pc=${PREV_HEAVY[$g]%%$US*}; pm=${PREV_HEAVY[$g]#*$US}; cc=${G_CPU[base:$g]:-0}; cm=${G_RSS[base:$g]:-0} if (( (pc >= 25 && cc >= 25) || (pm >= 1500000000 && cm >= 1500000000) )); then repeat+=("$g"); fi done for g in $repeat; do pc=${PREV_HEAVY[$g]%%$US*}; pm=${PREV_HEAVY[$g]#*$US} add_bottleneck Review 'Speed' "$g was heavy in both scans" \ "$g used $(f0 $pc)% of a core and $(size $pm) of memory in the earlier report, and $(f0 ${G_CPU[base:$g]})% of a core and $(size ${G_RSS[base:$g]}) now. When an app is heavy every time, it is a pattern rather than a one-off." \ "Check $g for updates and for settings that keep it busy in the background (sync, indexing, many open tabs or projects). If you rarely use it, quit it when you are done." \ Medium "Less background load every day, not just once." 45 '' 'Earlier CPU' "$(f0 $pc)% of a core" 'Now CPU' "$(f0 ${G_CPU[base:$g]})% of a core" done return 0 } # ==== lib/report_html.zsh ==== # ============================================================================= # Odd$ Tune for Mac - HTML report. # Four main sections: System Health, Performance Bottlenecks, Recommended Optimizations, Optimization # Results. The report is a static page: it cannot change anything on the Mac. Changes are only ever made # by Odd$ Tune in Terminal, after you approve them. # ============================================================================= finding_html() { # INDEX RANK local i=$1 rank=$2 cls=${(L)F_LEVEL[$1]} pair kind case ${F_KIND[$i]} in bottleneck) kind=Performance ;; storage) kind=Storage ;; startup) kind=Startup ;; health) kind=${${F_AREA[$i]:#Speed}:-Health} ;; *) kind=${F_AREA[$i]} ;; esac print -r -- "
" print -r -- "

#$rank$( [[ ${F_LEVEL[$i]} == Urgent ]] && print -rn -- 'Needs attention now' || print -rn -- 'Worth doing')$(h $kind)$([[ -n ${F_CONF[$i]} ]] && print -rn -- "Confidence: $(h ${F_CONF[$i]})")

" print -r -- "

$(h ${F_TITLE[$i]})

" print -r -- "

Why: $(h ${F_WHY[$i]})

" print -r -- "

What to do: $(h ${F_ACTION[$i]})

" [[ -n ${F_BENEFIT[$i]} ]] && print -r -- "

Expected benefit: $(h ${F_BENEFIT[$i]})

" if [[ -n ${F_DETAILS[$i]} ]]; then print -r -- '
Measurements
' for pair in "${(@ps:$RS:)F_DETAILS[$i]}"; do [[ -z $pair ]] && continue print -r -- "" done print -r -- '
$(h ${pair%%$US*})$(h ${pair#*$US})
' fi print -r -- '
' } table_html() { # COLS_ARRAY_NAME ROWS_ARRAY_NAME local -a cols rows; cols=("${(@P)1}"); rows=("${(@P)2}") local c r if (( ! ${#rows} )); then print -r -- '

Nothing found.

'; return; fi print -rn -- '
' for c in $cols; do print -rn -- ""; done print -r -- '' for r in $rows; do print -rn -- '' for c in "${(@ps:$RS:)r}"; do print -rn -- ""; done print -r -- '' done print -r -- '
$(h $c)
$(h $c)
' } compare_table_html() { # PREFIX local p=$1 i local -a m b a v m=("${(@P)${:-${p}_METRIC}}"); b=("${(@P)${:-${p}_BEFORE}}"); a=("${(@P)${:-${p}_AFTER}}"); v=("${(@P)${:-${p}_VERDICT}}") (( ${#m} )) || { print -r -- '

Nothing could be measured twice.

'; return } print -r -- '
' for (( i = 1; i <= ${#m}; i++ )); do local vc='' [[ ${v[$i]} == *(Lower|Less|Faster|fewer|more\ free)* ]] && vc=' class="good"' [[ ${v[$i]} == *(Higher|More\ swapping|Slower|less\ free)* ]] && vc=' class="bad"' print -r -- "$(h ${v[$i]})" done print -r -- '
MeasurementBeforeAfterResult
$(h ${m[$i]})$(h ${b[$i]})$(h ${a[$i]})
' local -a notes; notes=("${(@P)${:-${p}_NOTES}}") local n; for n in $notes; do print -r -- "

$(h $n)

"; done } check_status() { # NAME -> REPLY (Clear|Flagged|Skipped|'') local i; REPLY='' for (( i = 1; i <= ${#C_NAME}; i++ )); do [[ ${C_NAME[$i]} == $1 ]] && { REPLY=${C_STATUS[$i]}; return }; done } check_result() { local i; REPLY=''; for (( i = 1; i <= ${#C_NAME}; i++ )); do [[ ${C_NAME[$i]} == $1 ]] && { REPLY=${C_RESULT[$i]}; return }; done } card() { # TITLE VALUE NOTE STATUS local st=${(L)4:-clear} print -r -- "

$(h $1)

$(h $2)

$(h $3)

" } health_html() { local mp word swap ram=${M[base:ramBytes]:-0} print -r -- '

System Health

' print -r -- '
' print -r -- "" print -r -- "" print -r -- "" print -r -- "" [[ -n ${M[base:uptimeDays]-} ]] && print -r -- "" print -r -- '
Mac$(h ${HW_MODEL:-Unknown})
Processor$(h "${HW_CHIP:-Unknown} ($HW_ARCH), ${M[base:logicalCpus]:-?} cores${M[base:perfCores]:+ (${M[base:perfCores]} performance, ${M[base:effCores]} efficiency)}")
Memory$(h "$(ramsize $ram)")
macOS$(h ${MACOS:-Unknown})
Since last restart$(h "$(plural ${M[base:uptimeDays]} day days)")
' check_status 'Free space' (( DISK_TOTAL )) && card Storage "$(size $DISK_FREE) free" "of $(size $DISK_TOTAL)" $REPLY || card Storage 'Unknown' 'Could not be read' Skipped case ${M[base:memPressureWorst]-} in 1) word=Normal ;; 2) word=Elevated ;; 4) word=Critical ;; *) word='Unknown' ;; esac check_status Memory; [[ ${M[base:memPressureWorst]-} == 4 ]] && REPLY=Urgent card 'Memory pressure' $word "$( [[ -n ${M[base:swapOutBytesDuring]-} ]] && print -rn -- "$(size ${M[base:swapOutBytesDuring]}) swapped during the test" || print -rn -- 'Swap not measured')" $REPLY check_status 'Processor (CPU) use' card 'Processor (CPU)' "$( [[ -n ${M[base:cpuTotalPctMean]-} ]] && print -rn -- "$(f0 ${M[base:cpuTotalPctMean]})% busy" || print -rn -- Unknown)" "average over $(f0 ${M[base:sampleSeconds]:-0}) seconds" $REPLY check_status Battery; local bst=$REPLY; check_result Battery card Battery "${REPLY%%,*}" "$( [[ -n ${M[base:batteryMaxCapacityPct]-} ]] && print -rn -- "${M[base:batteryMaxCapacityPct]}% of original capacity" || { [[ $REPLY == *desktop* ]] && print -rn -- 'Desktop Mac' })" $bst check_status 'Drive health'; local dst=$REPLY; check_result 'Drive health' card 'Drive' "${REPLY%% \(*}" 'SMART status reported by macOS' $dst check_status 'Heat and throttling'; local tst=$REPLY; check_result 'Heat and throttling' card 'Heat' "$( [[ $tst == Flagged ]] && print -rn -- 'Signs of throttling' || { [[ $tst == Skipped ]] && print -rn -- 'Not reported' || print -rn -- 'No warnings' })" 'From macOS only; no temperatures are guessed' $tst print -r -- '
' } recs_html() { local i lvl print -r -- '' } results_html() { local i print -r -- '

Optimization Results

' if (( ! ${#A_ACTION} )); then if (( DEMO )); then print -r -- '

This sample report shows no changes.

' else print -r -- '

No changes were made. Odd$ Tune only reads your Mac unless you approve a change in Terminal.

'; fi else local n_ok=0 n_fail=0 for (( i = 1; i <= ${#A_OK}; i++ )); do if (( ${A_OK[$i]} )); then (( n_ok += 1 )); else (( n_fail += 1 )); fi; done print -r -- "

$(h "$(plural $n_ok 'action succeeded' 'actions succeeded')$( (( n_fail )) && print -rn -- ", $n_fail did not")$( (( TRASHED_BYTES )) && print -rn -- "; $(size $TRASHED_BYTES) moved to the Trash")").

" (( TRASHED_BYTES )) && print -r -- '

Files you approved were moved to the Trash. To get one back, open the Trash, right-click it and choose Put Back. The space is freed when you empty the Trash.

' print -r -- '
' for (( i = 1; i <= ${#A_ACTION}; i++ )); do print -r -- "" done print -r -- '
ActionItemResultTo undo
$(h ${A_ACTION[$i]})$(h ${A_ITEM[$i]})$(h ${A_RESULT[$i]})$(h ${A_RECOVERY[$i]})
' [[ -n $LOG_PATH && -e $LOG_PATH ]] && print -r -- "

Change log: $(h $(nice $LOG_PATH))

" fi if (( BENCH_DONE )); then print -r -- '

Before and after

' (( BENCH_COMPARABLE )) || print -r -- '' compare_table_html BENCH print -r -- '

Remaining concerns

' fi print -r -- '
' if (( PREV_DONE )); then print -r -- "

Compared with your earlier report $(h $PREV_WHEN)

" (( PREV_COMPARABLE )) || print -r -- '' compare_table_html PREV print -r -- '
' fi } report_html() { local -a urgent review local i n_clear=0 n_skip=0 cls headline when summary word for (( i = 1; i <= ${#F_LEVEL}; i++ )); do [[ ${F_LEVEL[$i]} == Urgent ]] && urgent+=("$i") || review+=("$i"); done for (( i = 1; i <= ${#C_STATUS}; i++ )); do [[ ${C_STATUS[$i]} == Clear ]] && (( n_clear++ )) [[ ${C_STATUS[$i]} == Skipped ]] && (( n_skip++ )) done if (( ${#urgent} )); then cls=urgent; headline="$(plural ${#urgent} 'thing needs' 'things need') your attention now." elif (( ${#review} )); then cls=review; headline="Your Mac is OK. $(plural ${#review} 'thing' 'things') would help it run better." elif (( n_skip )); then cls=clear; headline="Nothing needs fixing in what could be checked. $(plural $n_skip 'check' 'checks') couldn't be read." else cls=clear; headline='Your Mac is in good shape.'; fi when="$(strftime '%A, %B %f, %Y' $SCAN_EPOCH) at $(strftime '%L:%M %p' $SCAN_EPOCH)" local -a parts (( ${#urgent} )) && parts+=("$(plural ${#urgent} 'needs attention now' 'need attention now')") (( ${#review} )) && parts+=("$(plural ${#review} 'is worth doing' 'are worth doing')") parts+=("$(plural $n_clear 'check came back fine' 'checks came back fine')") (( n_skip )) && parts+=("$(plural $n_skip "couldn't be read" "couldn't be read")") summary="${(j:, :)parts}." print -r -- '' print -r -- '' print -r -- "" print -r -- "$(h $BRAND) report for $(h $COMPUTER)" print -r -- '
' print -r -- "

$(h $BRAND)Performance and health check by $(h $COMPANY)

" print -r -- "

$(h $headline)

" print -r -- "

$(h $COMPUTER)$([[ -n $MACOS ]] && print -rn -- ", macOS $(h $MACOS)"), checked $(h $when).

" print -r -- "

$(h $summary)

" print -r -- "

$(h $SUMMARY)

" (( DEMO )) && print -r -- '' if (( DISK_TOTAL )); then local used=$(( (DISK_TOTAL - DISK_FREE) * 100 / DISK_TOTAL )) print -r -- "
" print -r -- "

$(h "$(size $(( DISK_TOTAL - DISK_FREE ))) used, $(size $DISK_FREE) free of $(size $DISK_TOTAL)")

" fi print -r -- '' health_html print -r -- "

Performance Bottlenecks $(plural ${#RANK} problem problems), most important first

" if (( ${#RANK} )); then local r=0; for i in $RANK; do (( r++ )); finding_html $i $r; done else print -r -- "

Nothing slowed the Mac down during the $(f0 ${M[base:sampleSeconds]:-0})-second measurement, and no storage or health problems were found.

" fi print -r -- "

Measurements cover a $(f0 ${M[base:sampleSeconds]:-0})-second window while Odd\$ Tune itself was idle. A problem that comes and goes may not show up in one run: run it again while the Mac feels slow, and use --compare to see the difference.

" print -r -- '
' recs_html results_html print -r -- "

What was checked $(plural ${#C_NAME} check checks)

' print -r -- '

The details Click to open

' local spec label n for spec in 'Busiest processes (CPU, averaged over the test)|T_CPU' 'Largest memory users|T_MEM' 'Energy impact (macOS estimate)|T_ENERGY' \ 'Startup items and background helpers (busiest first)|T_STARTUP' \ 'Where your space goes|T_SPACE' 'Largest files (500 MB or more, biggest first)|T_LARGE' 'Large archives (100 MB or more)|T_ARCHIVES' \ 'Duplicate files (identical contents)|T_DUPES' 'Developer folders|T_DEV' 'Old installers in Downloads|T_INSTALLERS' \ 'Downloads not modified for 90 days or more|T_DOWNLOADS'; do label=${spec%%|*}; n=${spec#*|} print -r -- "
$(h $label) (${#${(P)n}})" table_html ${n}_COLS $n print -r -- '
' done print -r -- '
' print -r -- '

Next steps

    ' if (( ${#urgent} + ${#review} )); then print -r -- '
  1. Work through the problems above, starting at #1. Each one says exactly where to click.
  2. ' else print -r -- '
  3. Nothing needs doing. Keep macOS up to date and run Odd$ Tune again every few months.
  4. ' fi print -r -- '
  5. Run Odd$ Tune again afterwards, with --compare and this report'"'"'s .json file, to see what changed.
  6. ' print -r -- "
  7. Want to know who or what can get into this Mac? Odd\$ Guard for Mac is a free, read-only security check.
  8. " print -r -- "
  9. Rather have someone do it with you? $(h $COMPANY) offers remote tune-ups, backup setup and storage clean-ups: see services and prices.
  10. " print -r -- '
' print -r -- '
' } # ==== lib/report_json.zsh ==== # ============================================================================= # Odd$ Tune for Mac - JSON report (schema 2). # Every v0.1.0 key is kept with the same meaning. New keys carry raw numbers so other tools (and the # planned native app) can read, rank and compare results without parsing text. See docs/JSON-SCHEMA.md. # ============================================================================= json_metrics() { # TAG -> JSON object of that measurement, or null local tag=$1 k first=1 v local -a keys; keys=(${(ok)M[(I)${tag}:*]}) if (( ! ${#keys} )); then print -rn -- null; return; fi print -rn -- '{' for k in $keys; do v=${M[$k]} (( first )) || print -rn -- ', ' first=0 if isnum $v; then print -rn -- "$(j ${k#${tag}:}): $v"; else print -rn -- "$(j ${k#${tag}:}): $(j $v)"; fi done local -a series out; series=(${(P)${:-CPU_SERIES_$tag}}) for v in $series; do out+=($(f1 $v)); done (( ${#out} )) && print -rn -- ", \"cpuTotalPctSeries\": [${(j:, :)out}]" print -rn -- '}' } json_rows() { # PREFIX (BENCH or PREV) -> array of comparison rows local p=$1 i first=1 local -a m b a c v m=("${(@P)${:-${p}_METRIC}}"); b=("${(@P)${:-${p}_BEFORE}}"); a=("${(@P)${:-${p}_AFTER}}"); c=("${(@P)${:-${p}_CHANGE}}"); v=("${(@P)${:-${p}_VERDICT}}") print -rn -- '[' for (( i = 1; i <= ${#m}; i++ )); do (( first )) || print -rn -- ', ' first=0 print -rn -- "{\"metric\": $(j ${m[$i]}), \"before\": $(j ${b[$i]}), \"after\": $(j ${a[$i]}), \"change\": $(j ${c[$i]}), \"verdict\": $(j ${v[$i]})}" done print -rn -- ']' } json_list() { # VALUES... -> JSON array of strings local x first=1 print -rn -- '[' for x in "$@"; do (( first )) || print -rn -- ', '; first=0; print -rn -- "$(j $x)"; done print -rn -- ']' } report_json() { local i first pair t g local -a c print -r -- '{' print -r -- " \"tool\": $(j $BRAND), \"platform\": \"macOS\", \"version\": $(j $VERSION), \"schemaVersion\": 2, \"macOSVersion\": $(j $MACOS)," print -r -- " \"computer\": $(j $COMPUTER), \"checkedAt\": $(j $(strftime '%Y-%m-%dT%H:%M:%S%z' $SCAN_EPOCH)), \"demo\": $(jb $DEMO)," print -r -- " \"storage\": {\"totalBytes\": $DISK_TOTAL, \"freeBytes\": $DISK_FREE}," print -r -- " \"hardware\": {\"model\": $(j $HW_MODEL), \"chip\": $(j $HW_CHIP), \"architecture\": $(j $HW_ARCH), \"ramBytes\": $(jn ${M[base:ramBytes]-}), \"logicalCpus\": $(jn ${M[base:logicalCpus]-}), \"performanceCores\": $(jn ${M[base:perfCores]-}), \"efficiencyCores\": $(jn ${M[base:effCores]-})}," print -r -- " \"summary\": $(j $SUMMARY)," print -r -- " \"metrics\": {\"baseline\": $(json_metrics base), \"after\": $(json_metrics after)}," # Processes: the busiest by CPU and the largest by memory local -a plist bymem plist=(${SAMPLE_GROUPS_base[1,25]}) for g in ${(k)G_RSS}; do [[ $g == base:* ]] && bymem+=("$(printf '%015d' ${G_RSS[$g]:-0})$US${g#base:}"); done bymem=(${(O)bymem}); for g in ${${bymem##*$US}[1,15]}; do (( ${plist[(Ie)$g]} )) || plist+=("$g"); done print -r -- ' "processes": [' for (( i = 1; i <= ${#plist}; i++ )); do g=${plist[$i]} print -r -- " {\"name\": $(j $g), \"kind\": $(j ${G_KIND[base:$g]}), \"cpuMeanPct\": $(jn $(f1 ${G_CPU[base:$g]:-0})), \"cpuPeakPct\": $(jn $(f1 ${G_PEAK[base:$g]:-0})), \"busySamplesPct\": $(jn ${G_SUST[base:$g]:-0}), \"memoryBytes\": $(jn ${G_RSS[base:$g]:-0}), \"energyImpact\": $(jn ${G_ENERGY[base:$g]:+$(f1 ${G_ENERGY[base:$g]})}), \"processCount\": $(jn ${G_NPROC[base:$g]:-0})}$( (( i < ${#plist} )) && print ',')" done print -r -- ' ],' print -r -- ' "startupItems": [' for (( i = 1; i <= ${#S_LABEL}; i++ )); do print -r -- " {\"label\": $(j ${S_LABEL[$i]}), \"scope\": $(j ${S_SCOPE[$i]}), \"state\": $(j ${S_STATE[$i]}), \"running\": $(jb ${S_RUNNING[$i]:+1}), \"program\": $(j ${S_PROG[$i]}), \"programMissing\": $(jb ${S_ORPHAN[$i]}), \"apple\": $(jb ${S_APPLE[$i]}), \"cpuMeanPct\": $(jn $(f1 ${S_CPU[$i]:-0})), \"memoryBytes\": $(jn ${S_RSS[$i]:-0})}$( (( i < ${#S_LABEL} )) && print ',')" done print -r -- ' ],' print -r -- ' "findings": [' local r n=${#RANK} for (( r = 1; r <= n; r++ )); do i=${RANK[$r]} print -rn -- " {\"Level\": $(j ${F_LEVEL[$i]}), \"Area\": $(j ${F_AREA[$i]}), \"Title\": $(j ${F_TITLE[$i]}), \"Why\": $(j ${F_WHY[$i]}), \"Action\": $(j ${F_ACTION[$i]}), \"Details\": {" first=1 for pair in "${(@ps:$RS:)F_DETAILS[$i]}"; do [[ -z $pair ]] && continue (( first )) || print -rn -- ', ' first=0 print -rn -- "$(j ${pair%%$US*}): $(j ${pair#*$US})" done print -r -- "}, \"Kind\": $(j ${F_KIND[$i]}), \"Confidence\": $(j ${F_CONF[$i]}), \"ExpectedBenefit\": $(j ${F_BENEFIT[$i]}), \"Rank\": $r, \"Score\": $(jn ${F_SCORE[$i]})}$( (( r < n )) && print ',')" done print -r -- ' ],' print -r -- ' "checks": [' for (( i = 1; i <= ${#C_NAME}; i++ )); do print -r -- " {\"Area\": $(j ${C_AREA[$i]}), \"Name\": $(j ${C_NAME[$i]}), \"Result\": $(j ${C_RESULT[$i]}), \"Status\": $(j ${C_STATUS[$i]})}$( (( i < ${#C_NAME} )) && print ',')" done print -r -- ' ],' print -r -- ' "recommendations": [' for (( i = 1; i <= ${#R_ID}; i++ )); do print -r -- " {\"id\": $(j ${R_ID[$i]}), \"title\": $(j ${R_TITLE[$i]}), \"risk\": ${R_RISK[$i]}, \"riskLabel\": $(j $( (( ${R_RISK[$i]} == 1 )) && print Safe || print Advanced)), \"approval\": $(j ${R_APPROVAL[$i]}), \"reclaimableBytes\": $(jn ${R_RECLAIM[$i]}), \"items\": $(jn ${R_COUNT[$i]}), \"why\": $(j ${R_WHY[$i]}), \"recovery\": $(j ${R_RECOVERY[$i]})}$( (( i < ${#R_ID} )) && print ',')" done print -r -- ' ],' print -r -- ' "actions": [' for (( i = 1; i <= ${#A_ACTION}; i++ )); do print -r -- " {\"time\": $(j $(strftime '%Y-%m-%dT%H:%M:%S%z' ${A_TIME[$i]})), \"action\": $(j ${A_ACTION[$i]}), \"item\": $(j ${A_ITEM[$i]}), \"result\": $(j ${A_RESULT[$i]}), \"ok\": $(jb ${A_OK[$i]}), \"bytes\": $(jn ${A_BYTES[$i]}), \"recovery\": $(j ${A_RECOVERY[$i]})}$( (( i < ${#A_ACTION} )) && print ',')" done print -r -- ' ],' print -rn -- ' "movedToTrash": [' first=1 for t in $T_MOVED; do c=("${(@ps:$RS:)t}") (( first )) || print -rn -- ', ' first=0 print -rn -- "{\"File\": $(j ${c[1]}), \"Size\": $(j ${c[2]}), \"Result\": $(j ${c[3]})}" done print -r -- '],' print -r -- " \"trashBytesFromThisRun\": ${TRASHED_BYTES:-0}," print -r -- " \"benchmark\": {\"performed\": $(jb $BENCH_DONE), \"comparable\": $(jb $BENCH_COMPARABLE), \"notes\": $(json_list "${BENCH_NOTES[@]}"), \"rows\": $(json_rows BENCH)}," print -r -- " \"comparison\": {\"performed\": $(jb $PREV_DONE), \"earlierReport\": $(j ${PREV_FILE:+$(nice $PREV_FILE)}), \"earlierCheckedAt\": $(j $PREV_WHEN), \"comparable\": $(jb $PREV_COMPARABLE), \"notes\": $(json_list "${PREV_NOTES[@]}"), \"rows\": $(json_rows PREV)}," print -r -- " \"changeLog\": $( [[ -n $LOG_PATH && -e $LOG_PATH ]] && j $LOG_PATH || print -rn -- null)" print -r -- '}' } # ==== lib/demo.zsh ==== # ============================================================================= # Odd$ Tune for Mac - sample report (--demo). Nothing is read from the computer. # The sample measurements go through the same analysis as a real scan, so the demo also shows how # real findings are worded and ranked. Every page of the result is marked as a sample. # ============================================================================= demo_group() { # TAG NAME KIND CPU PEAK SUST RSS NPROC [ENERGY] [APP_PATH] local t=$1 g=$2 G_KIND[${t}:$g]=$3; G_CPU[${t}:$g]=$4; G_PEAK[${t}:$g]=$5; G_SUST[${t}:$g]=$6; G_RSS[${t}:$g]=$7; G_NPROC[${t}:$g]=$8 [[ -n ${9:-} ]] && G_ENERGY[${t}:$g]=$9 [[ -n ${10:-} ]] && G_PATH[${t}:$g]=${10} } add_demo_data() { HW_MODEL='MacBook Air (Mac14,2)'; HW_CHIP='Apple M2'; HW_ARCH='Apple silicon' M[base:ramBytes]=8589934592; M[base:logicalCpus]=8; M[base:perfCores]=4; M[base:effCores]=4; M[base:uptimeDays]=41 add_check 'Health' 'Hardware' 'MacBook Air (Mac14,2), Apple M2 (Apple silicon), 8 GB memory, 8 cores' M[base:diskTotalBytes]=494400000000; M[base:diskFreeBytes]=31000000000 local t for t in base after; do M[${t}:sampleSeconds]=10.0; M[${t}:sampleIntervals]=5; M[${t}:powerSource]=Battery; M[${t}:lowPowerMode]=0; done M[base:cpuTotalPctMean]=34.2; M[base:cpuTotalPctSd]=6.1; M[base:cpuTotalPctPeak]=44.0; M[base:cpuBusyIntervals]=0 M[base:load1]=3.91; M[base:load5]=4.20; M[base:load15]=4.02 M[base:memPressureWorst]=2; M[base:memPressureElevatedPct]=80; M[base:swapOutBytesDuring]=412000000; M[base:swapOutPagesPerSec]=2514.6 M[base:swapOutPagesPerSecSd]=410.2; M[base:compressedBytes]=2900000000; M[base:swapUsedBytes]=3100000000; M[base:swapTotalBytes]=4294967296 M[base:memFreePct]=9; M[base:processCount]=512; M[base:activeProcessCount]=38; M[base:backgroundActiveCount]=6; M[base:diskMBps]=12.4 M[base:spawnMsMedian]=1.840; M[base:spawnMsQ1]=1.712; M[base:spawnMsQ3]=2.006; CPU_SERIES_base=(28.1 31.9 35.0 44.0 32.0) demo_group base 'Google Chrome' app 62.4 118.0 100 3400000000 23 48.2 '/Applications/Google Chrome.app' demo_group base 'Microsoft Teams' app 18.3 41.0 40 1600000000 6 22.4 '/Applications/Microsoft Teams.app' demo_group base 'WindowServer' system 21.0 30.2 60 310000000 1 9.1 demo_group base 'Dropbox' service 12.1 25.0 20 520000000 3 4.0 demo_group base 'Slack' app 4.2 12.0 0 910000000 5 2.3 '/Applications/Slack.app' demo_group base 'kernel_task' system 8.0 11.0 0 0 1 3.0 demo_group base 'mds_stores' system 6.1 15.0 0 120000000 1 1.1 SAMPLE_GROUPS_base=('Google Chrome' WindowServer 'Microsoft Teams' Dropbox kernel_task mds_stores Slack) analyze_cpu; analyze_memory; analyze_disk_activity; analyze_energy # Storage, as in v0.1.0 DISK_TOTAL=494400000000; DISK_FREE=31000000000 add_check 'Storage' 'Free space' "31.0 GB free of 494.4 GB (6%)" Flagged add_finding Review 'Storage' 'Storage is getting full' \ '31.0 GB is free. macOS updates need 20 GB or more, and a nearly full drive makes the Mac slower.' \ 'Start with the largest items in this report. Then open Apple menu > System Settings > General > Storage, where macOS offers to store files in iCloud, empty the Trash automatically and remove things you no longer use.' \ 'Free' '31.0 GB' 'Drive size' '494.4 GB' set_last_finding storage High 'More free space gives macOS room for updates, swap and caches.' 45 T_SPACE=("$(row Desktop '2.1 GB' '')" "$(row Documents '38.4 GB' '')" "$(row Downloads '24.7 GB' '')" "$(row Pictures '96.2 GB' '')" "$(row Movies '61.0 GB' '')" "$(row Music '8.3 GB' '')" "$(row 'App caches' '4.9 GB' 'macOS and apps manage these. Clearing them rarely helps; apps rebuild them, which costs time and energy. Odd$ Tune does not clear caches.')" "$(row 'iPhone and iPad backups' '' 'Private to Finder. See them in Finder: select your device, then Manage Backups.')") add_check 'Storage' 'Where your space goes' '8 folders measured, 1 not readable' T_LARGE=("$(row '~/Movies/Family reunion 2023.mov' '14.2 GB' 'Jul 9, 2023' Video)" "$(row '~/Downloads/Windows11.iso' '6.1 GB' 'Mar 2, 2025' 'Disk image')" "$(row '~/Documents/Old laptop backup.zip' '4.8 GB' 'Jan 15, 2024' Archive)" "$(row '~/Downloads/Xcode_16.xip' '3.4 GB' 'Feb 20, 2025' Installer)") add_check 'Storage' 'Large files' '4 found, 28.5 GB in total' Flagged add_finding Review 'Storage' '4 large files use 28.5 GB' \ 'These are the biggest files in your folders. Old videos, disk images and archives are common ones you may no longer need.' \ 'Look through the list under "Largest files". Move what you no longer need to the Trash, or to an external drive or iCloud if you want to keep it.' 'Files' 4 'Total' '28.5 GB' set_last_finding storage High 'Up to 28.5 GB, depending on what you decide to keep.' 40 T_ARCHIVES=("$(row '~/Documents/Old laptop backup.zip' '4.8 GB' 'Jan 15, 2024')") add_check 'Storage' 'Large archives' '1 archive of 100 MB or more, 4.8 GB' Flagged T_DOWNLOADS=("$(row '~/Downloads/Windows11.iso' '6.1 GB' 'Mar 2, 2025')" "$(row '~/Downloads/Xcode_16.xip' '3.4 GB' 'Feb 20, 2025')" "$(row '~/Downloads/Zoom.pkg' '91 MB' 'Jan 6, 2025')") T_INSTALLERS=("$(row '~/Downloads/Windows11.iso' '6.1 GB' 'Mar 2, 2025')" "$(row '~/Downloads/Xcode_16.xip' '3.4 GB' 'Feb 20, 2025')" "$(row '~/Downloads/Zoom.pkg' '91 MB' 'Jan 6, 2025')" "$(row '~/Downloads/googlechrome.dmg' '233 MB' 'Nov 30, 2024')") add_check 'Storage' 'Downloads folder' '412 files, 24.7 GB; 368 files not modified for 90+ days' add_check 'Storage' 'Old installers in Downloads' '4 files, 9.8 GB' Flagged add_finding Review 'Storage' 'Old installers in Downloads use 9.8 GB' \ 'Disk images (.dmg) and installer packages (.pkg) are only needed while you install an app. Once it is in Applications, the installer can go.' \ 'Delete the installers listed under "Old installers" that you have finished with. Odd$ Tune can move them to the Trash for you when the scan ends; you can put them back from the Trash.' 'Files' 4 'Total' '9.8 GB' set_last_finding storage High '9.8 GB once the Trash is emptied.' 35 T_DUPES=("$(row '~/Downloads/Tax return 2024.pdf; ~/Documents/Taxes/Tax return 2024.pdf' '3 MB' '3 MB')" "$(row '~/Downloads/Team offsite.mov; ~/Desktop/Team offsite.mov' '1.2 GB' '1.2 GB')") add_check 'Storage' 'Duplicate files' '2 sets of identical files; up to 1.2 GB could be freed' Flagged add_finding Review 'Storage' 'Identical copies of files use up to 1.2 GB' \ 'These files have exactly the same contents (checked with a SHA-256 fingerprint, not just the name). Copies made by Finder on APFS drives can share storage, so the real saving may be smaller.' \ 'Review the sets under "Duplicate files". Odd$ Tune can show you each set and move the copies you pick to the Trash. It always keeps at least one copy and never chooses for you.' 'Sets' 2 'Could free (up to)' '1.2 GB' set_last_finding storage High 'Up to 1.2 GB once the Trash is emptied.' 18 T_DEV=("$(row '~/Code/old-site/node_modules' 'Node.js packages' '1.4 GB' '214 days ago' 'npm install')") add_check 'Storage' 'Developer build folders' '1 project folder found, 1 in a project untouched for 30+ days (1.4 GB)' add_check 'Storage' 'Trash' 'Not checked: macOS keeps the Trash private from Terminal. See its size in Finder.' Skipped # Startup items S_LABEL=(com.google.keystone.agent com.adobe.ccxprocess us.zoom.ZoomDaemon com.oldvpn.helper) S_SCOPE=(You 'Everyone (starts when anyone signs in)' 'Everyone (starts with the Mac)' You) S_STATE=('Loaded, waiting' 'Running (PID 812)' 'Running (PID 301)' 'Program missing (cannot run)') S_CPU=(0 0.4 0.1 0); S_RSS=(0 82000000 21000000 0); S_RUNNING=('' 812 301 ''); S_ORPHAN=(0 0 0 1); S_APPLE=(0 0 0 0) S_PROG=('/Users/sam/Library/Google/GoogleSoftwareUpdate/GoogleSoftwareUpdate.bundle/Contents/Resources/GoogleSoftwareUpdateAgent.app/Contents/MacOS/GoogleSoftwareUpdateAgent' '/Applications/Utilities/Adobe Creative Cloud Experience/CCXProcess/CCXProcess.app/Contents/MacOS/Creative Cloud Content Manager.node' '/Library/PrivilegedHelperTools/us.zoom.ZoomDaemon' '/Applications/OldVPN.app/Contents/MacOS/helper') S_FILE=('' '' '' '') STARTUP_N=4; STARTUP_RUN=2; STARTUP_ORPHAN=1; STARTUP_THIRD=2; STARTUP_APP=0 startup_report # Health add_check 'Health' 'Battery' 'Normal, 412 charge cycles, holds 87% of its original charge'; M[base:batteryMaxCapacityPct]=87 add_check 'Health' 'Power' 'On battery (64%), Low Power Mode off' add_check 'Health' 'Heat and throttling' 'No thermal or performance warning reported by macOS' add_check 'Backups' 'Time Machine' 'Not set up' Flagged add_finding Review 'Backups' 'This Mac is not backed up with Time Machine' \ 'Without a backup, a failed drive, a lost Mac or ransomware can take your files with it. iCloud keeps some files, but not your apps, settings or everything in your folders.' \ 'Connect an external drive and open Apple menu > System Settings > General > Time Machine, then click Add Backup Disk. Favorable Odds can set this up with you.' set_last_finding health High 'Protection against losing your files. No speed change.' 40 add_check 'Health' 'macOS updates' '2 updates waiting' Flagged add_finding Review 'Health' '2 macOS updates are waiting' 'Updates fix security holes and bugs, and some speed problems.' \ 'Open Apple menu > System Settings > General > Software Update and install them. Save your work first; the Mac may restart.' 'Waiting' 2 set_last_finding health High 'Security fixes, and sometimes performance fixes.' 30 add_check 'Health' 'Drive health' 'Verified' add_check 'Speed' 'Last restart' '41 days ago' Flagged add_finding Review 'Speed' "The Mac hasn't restarted in 41 days" \ 'Restarting finishes installing updates and closes apps and helpers that have been running for weeks. If memory or processor problems are listed above, a restart is a quick first thing to try.' 'Save your work and choose Apple menu > Restart. Then run Odd$ Tune again to compare.' set_last_finding health Medium 'Often helps when apps have been open for weeks; run Odd$ Tune again afterwards and compare to see whether it did.' 22 # Recommendations as a real scan would build them INSTALLER_PATHS=(/demo/1 /demo/2 /demo/3 /demo/4); CAND_SIZE=(/demo/1 6100000000 /demo/2 3400000000 /demo/3 91000000 /demo/4 233000000) DUP_HASHES=(a b); DUP_RECLAIM=1203000000 DEV_PATHS=(/demo/nm); DEV_ELIGIBLE=(/demo/nm 1); DEV_RECLAIM=1400000000 ORPHAN_FILES=(/demo/orphan); M[base:thirdPartyHelpersRunning]=2 build_recommendations # A sample optimization session with a before-and-after measurement A_TIME=($SCAN_EPOCH $SCAN_EPOCH $SCAN_EPOCH $SCAN_EPOCH); A_ACTION=('Old installer' 'Old installer' 'Old installer' 'Quit app') A_ITEM=('~/Downloads/Windows11.iso' '~/Downloads/Zoom.pkg' '~/Downloads/googlechrome.dmg' 'Google Chrome') A_RESULT=('Moved to the Trash' 'Moved to the Trash' 'Moved to the Trash' 'Quit'); A_OK=(1 1 1 1) A_BYTES=(6100000000 91000000 233000000 0); A_RECOVERY=('Put Back from the Trash' 'Put Back from the Trash' 'Put Back from the Trash' 'Open it again from Applications or the Dock') T_MOVED=("$(row '~/Downloads/Windows11.iso' '6.1 GB' 'Moved to the Trash')" "$(row '~/Downloads/Zoom.pkg' '91 MB' 'Moved to the Trash')" "$(row '~/Downloads/googlechrome.dmg' '233 MB' 'Moved to the Trash')") CHANGES_MADE=4; TRASHED_BYTES=6424000000 M[after:diskTotalBytes]=494400000000; M[after:diskFreeBytes]=31000000000 M[after:cpuTotalPctMean]=17.6; M[after:cpuTotalPctSd]=3.2; M[after:memPressureWorst]=1; M[after:memPressureElevatedPct]=0 M[after:swapOutBytesDuring]=0; M[after:swapOutPagesPerSec]=0; M[after:swapOutPagesPerSecSd]=0; M[after:compressedBytes]=1400000000 M[after:processCount]=486; M[after:activeProcessCount]=24; M[after:backgroundActiveCount]=6 M[after:spawnMsMedian]=1.210; M[after:spawnMsQ1]=1.160; M[after:spawnMsQ3]=1.270; CPU_SERIES_after=(15.2 21.0 17.4 18.0 16.4) compare_tags base after BENCH_METRIC=("${CMP_METRIC[@]}"); BENCH_BEFORE=("${CMP_BEFORE[@]}"); BENCH_AFTER=("${CMP_AFTER[@]}") BENCH_CHANGE=("${CMP_CHANGE[@]}"); BENCH_VERDICT=("${CMP_VERDICT[@]}"); BENCH_NOTES=("${CMP_NOTES[@]}") BENCH_COMPARABLE=$CMP_OK; BENCH_DONE=1 } # ---- end of modules ---- # ----------------------------------------------------------------------------- # Main # ----------------------------------------------------------------------------- SCAN_EPOCH=$EPOCHSECONDS if (( DEMO )); then COMPUTER='Sample MacBook Air'; MACOS='15.1' else COMPUTER=$(scutil --get ComputerName 2>/dev/null); [[ -z $COMPUTER ]] && COMPUTER=$(hostname 2>/dev/null) MACOS=$(sw_vers -productVersion 2>/dev/null) fi print print -r -- "$BRAND for Mac v$VERSION $COMPANY" print -r -- 'Performance, storage and health check. It only reads; it asks before changing anything.' print # Pick a writable output folder (the script may be on a read-only disk image) probe_dir() { local t; mkdir -p -- "$1" 2>/dev/null && t=$(mktemp "$1/.oddstune-write.XXXXXX" 2>/dev/null) && rm -f -- "$t" } if ! probe_dir $OUTPUT_DIR; then OUTPUT_DIR="$HOME/Desktop/OddsTune Reports" probe_dir $OUTPUT_DIR || OUTPUT_DIR=${TMPDIR:-/tmp} fi stamp=$(strftime '%Y%m%d-%H%M%S' $SCAN_EPOCH) if (( DEMO )); then base="OddsTune-Mac-SAMPLE-$stamp"; else base="OddsTune-${COMPUTER//[^A-Za-z0-9._-]/-}-$stamp"; fi html_path="$OUTPUT_DIR/$base.html"; json_path="$OUTPUT_DIR/$base.json" if (( DEMO )); then step 'Building a sample report (no scan)' add_demo_data else scan_hardware || add_check 'Scanner' scan_hardware 'Stopped early' Skipped measure_power_source base step "Measuring activity for $(f0 $SAMPLE_SECONDS) seconds. Carry on as normal, but please don't start anything new." sample_system base $SAMPLE_SECONDS || add_check 'Scanner' sample_system 'Stopped early' Skipped bench_responsiveness base || add_check 'Scanner' bench_responsiveness 'Stopped early' Skipped find_ancestors for s in analyze_cpu analyze_memory analyze_disk_activity analyze_energy \ scan_storage scan_folders scan_large_files scan_downloads scan_trash scan_duplicates scan_dev_artifacts \ scan_startup scan_battery scan_power scan_thermal scan_backup scan_updates scan_disk scan_uptime; do $s || add_check 'Scanner' $s 'Stopped early' Skipped done if [[ -n $COMPARE_FILE ]]; then step 'Comparing with your earlier report' if load_previous $COMPARE_FILE; then compare_previous else add_check 'Scanner' 'Comparison with earlier report' "Not done: $CMP_LOAD_ERR" Skipped; fi fi build_recommendations LOG_PATH="$OUTPUT_DIR/$base-changes.log" run_optimizer (( CHANGES_MADE )) && measure_after fi rank_findings build_summary report_html > $html_path report_json > $json_path n_urgent=${#${(M)F_LEVEL:#Urgent}}; n_review=${#${(M)F_LEVEL:#Review}} print print -r -- "Done. $n_urgent urgent, $n_review worth doing." print -r -- "$SUMMARY" print -r -- "Report: $html_path" [[ -n $LOG_PATH && -e $LOG_PATH ]] && print -r -- "Change log: $LOG_PATH" (( ! NO_OPEN && IS_MAC )) && open -- $html_path 2>/dev/null exit 0