focus_daemon: split 543 -> 206 + 165 + 140 + 94, with 110 tests
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run

Location/curfew goes to daemon_location.sh, the derived state files to
daemon_state.sh, the app layer to daemon_apps.sh. All 23 functions moved
verbatim -- nothing restructured, which matters more here than anywhere
else in this session.

focus_daemon.sh has five `while IFS= read -r pkg; do ... done <file` loops
and EVERY body calls pm. Piping any of them in lets pm inherit and drain
the loop's stdin, so it would process one package instead of all of them --
measured elsewhere in this repo as 1 of 54. That audit ran BEFORE the
extraction, not after coverage came back short, and all five moved
untouched with a note above them saying why.

CURRENT_MODE and _CURFEW_TICK_CACHED are each written in both the entry
script and a library, so both stay declared with main, same call as
NET_BUILT in the curfew split.

110 assertions and 33 mutations, all killed. Two survived the first run and
both were defects in my own tests: the whitelist and sysprotect exactness
checks used a SUPERSTRING of a listed entry, which fails under grep -qF and
grep -qxF alike and so proved nothing about which was in use.

Two subjects are NOT at 100%, and the numbers are reported as measured:

  daemon_state.sh     67/67 = 100.00%
  daemon_location.sh  26/40 =  65.00%
  daemon_apps.sh      71/76 =  93.42%

Both shortfalls are kcov attribution failures, shown to be artifacts rather
than gaps. daemon_location.sh's missing lines are all inside the embedded
awk Haversine; mutating the Earth radius and dropping the longitude term
both fail the suite, and an isolated probe shows a one-line awk measuring
100% where the identical multi-line one measures 0%. Collapsing the formula
to satisfy the tool would cost the readability of the only real mathematics
in the repo, so it stays.

daemon_apps.sh's five are the trailing `done <file` of the very loops
described above. That is the same artifact piping fixed in curfew_net.sh,
and it is exactly what must NOT be done here. Redirecting two of them from
/dev/null fails the suite, so the lines run; all three are pinned in the
mutation spec instead.

Over-cap count 19 -> 18.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
This commit is contained in:
Krzysztof Rudnicki 2026-08-17 16:54:04 +02:00
parent 35ddf4114f
commit 094c4765f3
14 changed files with 1696 additions and 343 deletions

View File

@ -0,0 +1,21 @@
{
"title": "Split focus_daemon.sh into three tested libraries",
"objective": "Take focus_daemon.sh from 543 lines to under the repo's 250-line cap by extracting its location/curfew logic, its state-file builders and its app layer into three flat siblings, and test all three. is_allowed is the single decision that determines whether an app keeps working; it had no test at all.",
"acceptance_criteria": [
"bash meta/scripts/check_file_length.sh --all no longer lists phone_focus_mode/focus_daemon.sh, and no new file is over the cap.",
"Every stdin-draining `while read ... done < file` loop is identified BEFORE extraction and moved verbatim. None may be converted to a pipe: each body calls pm, which would drain the loop's stdin.",
"Every assertion is mutation-proofed with zero survivors, including mutations targeting code kcov cannot attribute — the embedded awk Haversine and the trailing `done < file` redirect lines.",
"Where kcov cannot reach 100%, the shortfall must be shown to be a measurement artifact by mutation, and reported as an explicit exception with the real number — never by restructuring code in a way that risks behaviour.",
"meta/scripts/verify_shell_split.sh reports every function moved verbatim.",
"All three siblings are added to BOTH of deploy.sh's hardcoded lists, and the two lists remain in exact correspondence.",
"shellcheck passes on each touched file individually, with no -x and no disable directive; sh -n passes on all four phone-side scripts.",
"A reproducible mutation spec lands in meta/scripts/fixtures/mutations/."
],
"out_of_scope": [
"Deploying to the phone or verifying on-device; there is no device in this session.",
"Splitting init, main, acquire_lock or the logging helpers out of the entry script, which is under the cap without the three extracted clusters.",
"Moving CURRENT_MODE or _CURFEW_TICK_CACHED out of the entry script: both are written there and in a library, so they are genuine shared globals.",
"Collapsing the multi-line awk Haversine onto one line to satisfy kcov; readability of the distance formula outweighs a measurement artifact."
],
"verifier": "bash phone_focus_mode/lib/tests/test_daemon_libs.sh (expects 110 passed, 0 failed), plus shell_coverage.sh reporting 100.00% for daemon_state.sh and the documented artifact figures for the other two, plus python3 meta/scripts/mutate_shell.py meta/scripts/fixtures/mutations/daemon_libs.json at 33 killed / 0 not killed, plus check_file_length.sh --all showing 18 files, plus deploy-list parity, plus pre-commit run --files on the touched files."
}

View File

@ -0,0 +1,76 @@
{
"intent": "Bring focus_daemon.sh under the 250-line cap by extracting three clusters into flat siblings, and test all three — including is_allowed, the single decision that determines whether any app on the phone keeps working, which had no test at all.",
"scope": [
"phone_focus_mode/focus_daemon.sh - 543 lines down to 206",
"phone_focus_mode/daemon_location.sh - new: get_location, calc_distance, _dec, is_curfew_now, curfew_active",
"phone_focus_mode/daemon_state.sh - new: the four build_*_file helpers, refresh_default_handlers, is_default_handler, write_status_snapshot",
"phone_focus_mode/daemon_apps.sh - new: reconcile_disabled_apps, is_allowed, enable_focus_mode, disable_focus_mode",
"phone_focus_mode/deploy.sh - all three added to both hardcoded lists",
"phone_focus_mode/lib/tests/ - a harness, four case files and one entry point, all new",
"meta/scripts/fixtures/mutations/daemon_libs.json - new: 33 reproducible mutations",
"Non-goal: any device deploy."
],
"changes": [
"Audited for stdin-draining loops BEFORE extracting anything. focus_daemon.sh has five `while IFS= read -r pkg; do ... done < file` loops and EVERY body calls pm, which inherits and drains the loop's stdin if the file is piped in instead. All five moved verbatim and none was converted to a pipe. A note above them in daemon_apps.sh says why, because the measured symptom elsewhere in this repo was processing 1 package of 54.",
"Checked which globals cross the seam. CURRENT_MODE is written by init (staying) and by enable/disable (moving), and read by main; _CURFEW_TICK_CACHED is written by curfew_active (moving) and cleared by main each tick. Both are genuine shared globals and stay declared in the entry script, the same call made for NET_BUILT in the curfew split.",
"Placed all three as flat siblings and added them to both deploy lists, then verified the lists correspond exactly in both directions.",
"Wrote 110 assertions concentrated on the decisions that matter: the midnight-wrapping curfew window, the Haversine against known city distances, the day-vs-night whitelist swap, the default-handler safety net that keeps the keyboard enabled, and the fact that each sweep loop processes every package rather than only the first."
],
"verification": [
{
"command": "bash phone_focus_mode/lib/tests/test_daemon_libs.sh",
"result": "pass",
"evidence": "Results: 110 passed, 0 failed. None of this code had a test before."
},
{
"command": "python3 meta/scripts/mutate_shell.py meta/scripts/fixtures/mutations/daemon_libs.json",
"result": "pass",
"evidence": "33 killed, 0 not killed. Two survived the first run and both were real test defects: the whitelist and sysprotect exactness assertions used a SUPERSTRING of a listed entry, which fails under both grep -qF and grep -qxF and so proved nothing about which was in use. Rewritten to use a substring, which discriminates."
},
{
"command": "bash meta/scripts/shell_coverage.sh phone_focus_mode/lib/tests/test_daemon_libs.sh daemon_state.sh",
"result": "pass",
"evidence": "daemon_state.sh: 67/67 lines = 100.00%."
},
{
"command": "bash meta/scripts/shell_coverage.sh phone_focus_mode/lib/tests/test_daemon_libs.sh daemon_location.sh",
"result": "fail",
"evidence": "daemon_location.sh: 26/40 = 65.00%, NOT 100%. Every uncovered line (24-37) is inside the embedded awk Haversine program. kcov instruments those lines but bash never reports them, exactly as it does for multi-line array literals. Demonstrated to be an artifact rather than untested code: mutating R = 6371000.0 to R = 1.0 and dropping the longitude term from the formula BOTH fail the suite, so the awk body is fully exercised. Reproduced the class in an isolated probe where a one-line awk measures 100% and the identical multi-line awk measures 0%. Collapsing the formula onto one line would satisfy kcov at the cost of the readability of the only piece of real mathematics in the repo; that trade was declined."
},
{
"command": "bash meta/scripts/shell_coverage.sh phone_focus_mode/lib/tests/test_daemon_libs.sh daemon_apps.sh",
"result": "fail",
"evidence": "daemon_apps.sh: 71/76 = 93.42%, NOT 100%. All five uncovered lines (35, 60, 110, 130, 158) are the trailing `done < file` of a redirect-driven while loop — the same artifact class fixed by piping in curfew_net.sh, which is NOT safe here because every one of these loop bodies calls pm. Demonstrated to be an artifact: redirecting two of them from /dev/null instead fails the suite, so the lines execute and are load-bearing. Both are in the mutation spec permanently."
},
{
"command": "bash meta/scripts/verify_shell_split.sh 35ddf41 phone_focus_mode/focus_daemon.sh phone_focus_mode/focus_daemon.sh phone_focus_mode/daemon_location.sh phone_focus_mode/daemon_state.sh phone_focus_mode/daemon_apps.sh",
"result": "pass",
"evidence": "IDENTICAL: all 23 top-level functions moved verbatim. Nothing was restructured, which is the point given the stdin hazard."
},
{
"command": "shellcheck on each touched file individually (no -x); sh -n on the four phone-side scripts",
"result": "pass",
"evidence": "All thirteen clean standalone. Seven SC2034 findings — test files resetting a config global for the next file's cases — were each resolved by reading the value back, not by a disable. All four phone scripts parse under ash."
},
{
"command": "deploy-list parity check in both directions",
"result": "pass",
"evidence": "comm over the push list and the cp list returns empty both ways. daemon_location.sh, daemon_state.sh and daemon_apps.sh appear in both."
},
{
"command": "bash meta/scripts/check_file_length.sh --all",
"result": "pass",
"evidence": "18 over-cap files, down from 19. focus_daemon.sh 206, the three siblings 94/140/165, and the six test files between 21 and 249."
}
],
"risks": [
"TWO SUBJECTS ARE BELOW 100% LINE COVERAGE and the numbers above are the real ones. Both shortfalls are kcov attribution failures shown by mutation to cover executed code, but anyone auditing the coverage figure alone will see 65% and 93% and should read this entry rather than assume neglect.",
"UNVERIFIED ON DEVICE. This is the fourth enforcer-family split of the session without a deploy, and the largest. focus_daemon.sh now sources three files; a partial push leaves it unable to start.",
"The five redirect-driven loops are a standing trap for future edits. A later change that pipes any of them in — a natural-looking cleanup, and one this session performed deliberately in another file — would silently process one package instead of all of them. The comment above them and the three mutations pinning them are the only guards."
],
"rollback": [
"git revert the commit. focus_daemon.sh returns to a single 543-line file, over the cap and untested, and deploy.sh stops pushing the three siblings.",
"After rollback, run sh -n phone_focus_mode/focus_daemon.sh expecting exit 0, and confirm grep -c 'daemon_location\\|daemon_state\\|daemon_apps' phone_focus_mode/deploy.sh returns 0.",
"A rollback AFTER a deploy leaves three stale files in $REMOTE_DIR; they are inert once nothing sources them."
]
}

View File

@ -0,0 +1,204 @@
{
"test": "phone_focus_mode/lib/tests/test_daemon_libs.sh",
"timeout": 300,
"mutations": [
{
"file": "phone_focus_mode/daemon_location.sh",
"find": "R = 6371000.0",
"replace": "R = 1.0",
"describe": "wrong Earth radius in the Haversine (awk body kcov cannot measure)"
},
{
"file": "phone_focus_mode/daemon_location.sh",
"find": "sdlat * sdlat + cos(lat1) * cos(lat2) * sdlon * sdlon",
"replace": "sdlat * sdlat",
"describe": "drop the longitude term from the Haversine"
},
{
"file": "phone_focus_mode/daemon_location.sh",
"find": "PI / 180.0",
"replace": "PI",
"describe": "skip the degrees-to-radians conversion"
},
{
"file": "phone_focus_mode/daemon_location.sh",
"find": "head -1",
"replace": "tail -1",
"describe": "take the stalest GPS fix instead of the freshest"
},
{
"file": "phone_focus_mode/daemon_location.sh",
"find": "[0-9]{4,}",
"replace": "[0-9]{1,}",
"describe": "accept imprecise coordinates as a real fix"
},
{
"file": "phone_focus_mode/daemon_location.sh",
"find": "[ \"$now\" -ge \"$start\" ] || [ \"$now\" -lt \"$end\" ]",
"replace": "[ \"$now\" -ge \"$start\" ] && [ \"$now\" -lt \"$end\" ]",
"describe": "break the midnight-wrapping curfew window"
},
{
"file": "phone_focus_mode/daemon_location.sh",
"find": "[ \"$now\" -ge \"$start\" ] && [ \"$now\" -lt \"$end\" ]\n\telse",
"replace": "[ \"$now\" -gt \"$start\" ] && [ \"$now\" -lt \"$end\" ]\n\telse",
"describe": "exclude the start minute of a same-day window"
},
{
"file": "phone_focus_mode/daemon_location.sh",
"find": "'' | *[!0-9]*) return 1 ;;",
"replace": "'' | *[!0-9]*) return 0 ;;",
"describe": "fail CLOSED on a broken clock instead of open"
},
{
"file": "phone_focus_mode/daemon_location.sh",
"find": "while [ \"${n#0}\" != \"$n\" ] && [ \"${#n}\" -gt 1 ]; do n=\"${n#0}\"; done",
"replace": ":",
"describe": "stop stripping leading zeros (octal parse)"
},
{
"file": "phone_focus_mode/daemon_location.sh",
"find": "[ ! -e \"$CURFEW_OVERRIDE_FILE\" ]",
"replace": "[ -e \"$CURFEW_OVERRIDE_FILE\" ]",
"describe": "invert the curfew override"
},
{
"file": "phone_focus_mode/daemon_location.sh",
"find": "_CURFEW_TICK_CACHED=1",
"replace": ":",
"describe": "never set the per-tick curfew memo"
},
{
"file": "phone_focus_mode/daemon_state.sh",
"find": "[ \"${n:-0}\" -lt 30 ]",
"replace": "[ \"${n:-0}\" -lt 0 ]",
"describe": "never warn about a truncated whitelist"
},
{
"file": "phone_focus_mode/daemon_state.sh",
"find": "[ \"${n:-0}\" -lt 10 ]",
"replace": "[ \"${n:-0}\" -lt 0 ]",
"describe": "never warn about a truncated night whitelist"
},
{
"file": "phone_focus_mode/daemon_state.sh",
"find": "grep -v '^[[:space:]]*#'",
"replace": "cat",
"describe": "keep comment lines as whitelist entries"
},
{
"file": "phone_focus_mode/daemon_state.sh",
"find": "cut -d/ -f1",
"replace": "cat",
"describe": "record the IME component instead of its package"
},
{
"file": "phone_focus_mode/daemon_state.sh",
"find": "[ \"$sms\" != \"null\" ]",
"replace": "true",
"describe": "record a literal null as the SMS handler"
},
{
"file": "phone_focus_mode/daemon_state.sh",
"find": "grep -qxF",
"replace": "grep -qF",
"describe": "match default handlers by substring instead of exactly"
},
{
"file": "phone_focus_mode/daemon_state.sh",
"find": "sort -u \"$tmp\" -o \"$f\"",
"replace": ":",
"describe": "never write the default-handler file"
},
{
"file": "phone_focus_mode/daemon_state.sh",
"find": "if curfew_active; then cf=1; else cf=0; fi",
"replace": "cf=0",
"describe": "always report curfew inactive in the snapshot"
},
{
"file": "phone_focus_mode/daemon_state.sh",
"find": "\"$DISABLED_APPS_FILE\" 2>/dev/null | tr -d ' ' || echo 0",
"replace": "/dev/null 2>/dev/null | tr -d ' ' || echo 0",
"describe": "always report zero disabled apps"
},
{
"file": "phone_focus_mode/daemon_apps.sh",
"find": "list=\"$STATE_DIR/night_whitelist.txt\"",
"replace": "list=\"$STATE_DIR/whitelist.txt\"",
"describe": "use the permissive day list during the night curfew"
},
{
"file": "phone_focus_mode/daemon_apps.sh",
"find": "if grep -qxF \"$pkg\" \"$list\" 2>/dev/null; then",
"replace": "if grep -qF \"$pkg\" \"$list\" 2>/dev/null; then",
"describe": "match the whitelist by substring instead of exactly"
},
{
"file": "phone_focus_mode/daemon_apps.sh",
"find": "\"$prefix\"*) return 0 ;;",
"replace": "*\"$prefix\"*) return 0 ;;",
"describe": "match sysprotect anywhere instead of as a prefix"
},
{
"file": "phone_focus_mode/daemon_apps.sh",
"find": "is_default_handler \"$pkg\" && return 0",
"replace": ":",
"describe": "drop the default-handler safety net"
},
{
"file": "phone_focus_mode/daemon_apps.sh",
"find": "if ! curfew_active &&",
"replace": "if true &&",
"describe": "let the browser guard resurrect a browser during curfew"
},
{
"file": "phone_focus_mode/daemon_apps.sh",
"find": "done <\"$tmp_pkgs\"",
"replace": "done </dev/null",
"describe": "sweep no packages (proves the redirect line kcov misses runs)"
},
{
"file": "phone_focus_mode/daemon_apps.sh",
"find": "done <\"$STATE_DIR/sysprotect.txt\"",
"replace": "done </dev/null",
"describe": "read no sysprotect prefixes (same redirect class)"
},
{
"file": "phone_focus_mode/daemon_apps.sh",
"find": "done <\"$blocked_sys\"",
"replace": "done </dev/null",
"describe": "disable no blocked system apps (same redirect class)"
},
{
"file": "phone_focus_mode/daemon_apps.sh",
"find": "newly_disabled=$((newly_disabled + 1))",
"replace": ":",
"describe": "stop counting newly disabled apps"
},
{
"file": "phone_focus_mode/daemon_apps.sh",
"find": "CURRENT_MODE=\"focus\"",
"replace": ":",
"describe": "never record entry into focus mode"
},
{
"file": "phone_focus_mode/daemon_apps.sh",
"find": "CURRENT_MODE=\"normal\"",
"replace": ":",
"describe": "never record the exit from focus mode"
},
{
"file": "phone_focus_mode/daemon_apps.sh",
"find": "mv \"$tmp_disabled\" \"$DISABLED_APPS_FILE\"",
"replace": ":",
"describe": "never apply the reconciliation result"
},
{
"file": "phone_focus_mode/daemon_apps.sh",
"find": "pm install-existing --user 0 \"$pkg\" >/dev/null 2>&1 || true",
"replace": ":",
"describe": "skip reinstalling for user 0 before enabling"
}
]
}

165
phone_focus_mode/daemon_apps.sh Executable file
View File

@ -0,0 +1,165 @@
#!/system/bin/sh
# shellcheck shell=ash
# daemon_apps.sh — the app layer of focus_daemon.sh: deciding whether a
# package is allowed, disabling everything that is not while focus mode is on,
# and re-enabling it afterwards.
#
# A flat sibling, not lib/: deploy.sh pushes phone scripts into one directory.
#
# Sourced by focus_daemon.sh, which owns log(), $CURRENT_MODE (written here
# and in init, read by main, so it stays with them) and the config.sh globals
# these read ($DISABLED_APPS_FILE, $MODE_FILE, $STATE_DIR).
#
# NOTE for anyone editing the `while IFS= read -r pkg; do ... done <file`
# loops below: they must stay redirect-driven. Every body calls pm, which
# inherits and drains the loop's stdin if the file is piped in instead — the
# measured symptom elsewhere in this repo was processing 1 package of 54.
reconcile_disabled_apps() {
[ -f "$DISABLED_APPS_FILE" ] || return
local tmp_disabled="$STATE_DIR/disabled_by_focus.tmp"
: >"$tmp_disabled"
while IFS= read -r pkg; do
[ -z "$pkg" ] && continue
if is_allowed "$pkg"; then
pm install-existing --user 0 "$pkg" >/dev/null 2>&1 || true
pm enable "$pkg" >/dev/null 2>&1 || true
log "Re-enabled allowed app during state reconciliation: $pkg"
continue
fi
echo "$pkg" >>"$tmp_disabled"
done <"$DISABLED_APPS_FILE"
mv "$tmp_disabled" "$DISABLED_APPS_FILE"
}
# ---- Check if package is allowed (whitelist or system-protected) ----
is_allowed() {
local pkg="$1"
# During the night curfew, swap the permissive day list for the strict
# night list. The sysprotect + default-handler guards below still apply on
# top of whichever list is active.
local list="$STATE_DIR/whitelist.txt"
if curfew_active; then
list="$STATE_DIR/night_whitelist.txt"
fi
# Exact match against the active whitelist file
if grep -qxF "$pkg" "$list" 2>/dev/null; then
return 0
fi
# Prefix match against system-protect file
while IFS= read -r prefix; do
[ -z "$prefix" ] && continue
case "$pkg" in
"$prefix"*) return 0 ;;
esac
done <"$STATE_DIR/sysprotect.txt"
# Hard-stop guard: refuse to disable any package that is the current
# default handler for a critical role (Dialer / SMS / Home / Contacts).
# Without this, a misconfigured WHITELIST can disable the default Phone
# app and Android falls back to com.android.settings/.FallbackHome -
# the persistent "Phone is starting..." screen with broken SystemUI
# gestures (no swipe-up recents). Recovering requires `pm enable` over
# ADB. Treat the guard as last-resort safety net independent of WHITELIST
# contents so a future config edit can never wipe these out.
is_default_handler "$pkg" && return 0
# The default browser is guarded only OUTSIDE curfew. At night the whole
# point is to disable browsers, so this guard must not re-allow it.
if ! curfew_active &&
grep -qxF "$pkg" "$STATE_DIR/default_browser.txt" 2>/dev/null; then
return 0
fi
return 1
}
enable_focus_mode() {
local first_entry=0
if [ "$CURRENT_MODE" != "focus" ]; then
first_entry=1
log "ENABLING focus mode - restricting non-whitelisted apps"
: >"$DISABLED_APPS_FILE"
fi
# Refresh default-handler list every tick. The user may switch dialer /
# SMS / launcher between sweeps; the guard in is_allowed() consults this
# list so a newly-promoted handler is never disabled.
refresh_default_handlers
# Blocked system app list is static; built once in init() (see
# build_blocked_sys_file), not rebuilt on every sweep.
local blocked_sys="$STATE_DIR/blocked_sys.txt"
# Periodic rescan catches third-party apps the user re-enabled (e.g. via
# Play Store or `pm enable` in a terminal) since the last tick.
# -e = enabled only, so we skip apps that are already disabled.
local tmp_pkgs="$STATE_DIR/pkg_list.txt"
pm list packages -3 -e 2>/dev/null | sed 's/^package://' >"$tmp_pkgs"
local newly_disabled=0
while IFS= read -r pkg; do
[ -z "$pkg" ] && continue
is_allowed "$pkg" && continue
if pm disable-user --user 0 "$pkg" >/dev/null 2>&1; then
grep -qxF "$pkg" "$DISABLED_APPS_FILE" 2>/dev/null ||
echo "$pkg" >>"$DISABLED_APPS_FILE"
newly_disabled=$((newly_disabled + 1))
fi
done <"$tmp_pkgs"
rm -f "$tmp_pkgs"
# Disable-for-user-0 any blocked system apps (Play Store, browsers,
# package installer UI, terminal apps).
# IMPORTANT: We intentionally use pm disable-user (NOT pm uninstall) here.
# pm uninstall -k --user 0 removes the package from Android's user-0
# package registry. If the daemon is killed with SIGKILL during a reboot
# (bypassing the cleanup trap), those packages stay uninstalled across the
# reboot. Android's bootloop-protection (MTK and others) then detects
# missing critical system packages and triggers recovery / factory wipe.
# pm disable-user leaves the package registered but inactive, so the
# PackageManager scan at next boot succeeds and no wipe occurs.
while IFS= read -r pkg; do
[ -z "$pkg" ] && continue
if pm disable-user --user 0 "$pkg" >/dev/null 2>&1; then
grep -qxF "$pkg" "$DISABLED_APPS_FILE" 2>/dev/null ||
echo "$pkg" >>"$DISABLED_APPS_FILE"
newly_disabled=$((newly_disabled + 1))
fi
done <"$blocked_sys"
CURRENT_MODE="focus"
echo "focus" >"$MODE_FILE"
if [ "$first_entry" -eq 1 ]; then
local count
count=$(wc -l <"$DISABLED_APPS_FILE" 2>/dev/null || echo 0)
log "Focus mode enabled - disabled $count apps"
elif [ "$newly_disabled" -gt 0 ]; then
log "Focus mode re-sweep: re-disabled $newly_disabled apps (re-enabled by user?)"
fi
reconcile_disabled_apps
}
disable_focus_mode() {
[ "$CURRENT_MODE" = "normal" ] && return
log "DISABLING focus mode - re-enabling apps"
local count=0
if [ -f "$DISABLED_APPS_FILE" ] && [ -s "$DISABLED_APPS_FILE" ]; then
# Re-enable all disabled apps (both 3rd-party and system apps).
# Both paths now use pm disable-user, so pm enable is the only
# restore command needed.
while IFS= read -r pkg; do
[ -z "$pkg" ] && continue
pm enable "$pkg" >/dev/null 2>&1 && count=$((count + 1))
done <"$DISABLED_APPS_FILE"
: >"$DISABLED_APPS_FILE"
fi
CURRENT_MODE="normal"
echo "normal" >"$MODE_FILE"
log "Focus mode disabled - re-enabled $count apps"
}

View File

@ -0,0 +1,94 @@
#!/system/bin/sh
# shellcheck shell=ash
# daemon_location.sh — where-and-when for focus_daemon.sh: reading the phone's
# GPS fix, the great-circle distance from home, and whether the night curfew
# window is currently open.
#
# A flat sibling, not lib/: deploy.sh pushes phone scripts into one directory.
#
# Sourced by focus_daemon.sh, which owns log() and the config.sh globals these
# read ($NIGHT_CURFEW_*, $CURFEW_FORCE_FILE, $CURFEW_OVERRIDE_FILE). It also
# owns $_CURFEW_TICK_CACHED: curfew_active memoises per tick and main clears
# the memo each loop, so both files write it and it stays with main.
# ---- Location ----
get_location() {
dumpsys location 2>/dev/null |
grep -oE '[-]?[0-9]{1,3}\.[0-9]{4,},[-]?[0-9]{1,3}\.[0-9]{4,}' |
head -1
}
# ---- Distance Calculation (Haversine via awk) ----
calc_distance() {
echo "$1 $2 $3 $4" | awk '{
PI = 3.14159265358979323846
R = 6371000.0
lat1 = $1 * PI / 180.0
lon1 = $2 * PI / 180.0
lat2 = $3 * PI / 180.0
lon2 = $4 * PI / 180.0
dlat = lat2 - lat1
dlon = lon2 - lon1
sdlat = sin(dlat / 2.0)
sdlon = sin(dlon / 2.0)
a = sdlat * sdlat + cos(lat1) * cos(lat2) * sdlon * sdlon
c = 2.0 * atan2(sqrt(a), sqrt(1.0 - a))
printf "%d\n", R * c
}'
}
# ---- Night curfew time check ----
# Returns 0 (true) when the local clock is inside the curfew window.
# Fails OPEN (return 1 = not curfew) on a malformed clock so a broken `date`
# can never strand you behind the strict list — essentials stay reachable
# either way, but the day list is the less-surprising default.
_dec() {
# Strip leading zeros so a zero-padded HHMM ("0500", "0830") is not parsed
# as (sometimes invalid) octal by the shell's arithmetic. Portable across
# ash/mksh; keeps at least one digit so "0000" -> "0".
local n="$1"
while [ "${n#0}" != "$n" ] && [ "${#n}" -gt 1 ]; do n="${n#0}"; done
printf '%s' "$n"
}
is_curfew_now() {
local now start end
now="$(date +%H%M 2>/dev/null)"
case "$now" in
'' | *[!0-9]*) return 1 ;;
esac
now="$(_dec "$now")"
start="$(_dec "$NIGHT_CURFEW_START")"
end="$(_dec "$NIGHT_CURFEW_END")"
if [ "$start" -le "$end" ]; then
[ "$now" -ge "$start" ] && [ "$now" -lt "$end" ]
else
# Window wraps past midnight (e.g. 2300 -> 0500).
[ "$now" -ge "$start" ] || [ "$now" -lt "$end" ]
fi
}
# Curfew is ACTIVE when enabled, not manually overridden, and either forced on
# (test hook) or inside the time window. The is_allowed() switch below consults
# this; because is_allowed() only runs during the focus-mode sweep/reconcile,
# curfew automatically takes effect only at home and is a no-op when away.
#
# Memoized once per main-loop tick (reset at the top of main()'s while loop):
# is_allowed() calls this once per enabled package in the sweep, and
# is_curfew_now forks `date` - on-device this meant up to ~N extra forks per
# 10s tick for N enabled apps, all recomputing a value that cannot change
# within a single tick. Result is cached in _CURFEW_TICK_RESULT.
curfew_active() {
if [ -n "$_CURFEW_TICK_CACHED" ]; then
[ "$_CURFEW_TICK_RESULT" = "1" ]
return
fi
_CURFEW_TICK_CACHED=1
_CURFEW_TICK_RESULT=0
if [ "${NIGHT_CURFEW_ENABLED:-0}" = "1" ] && [ ! -e "$CURFEW_OVERRIDE_FILE" ]; then
if [ -e "$CURFEW_FORCE_FILE" ] || is_curfew_now; then
_CURFEW_TICK_RESULT=1
fi
fi
[ "$_CURFEW_TICK_RESULT" = "1" ]
}

140
phone_focus_mode/daemon_state.sh Executable file
View File

@ -0,0 +1,140 @@
#!/system/bin/sh
# shellcheck shell=ash
# daemon_state.sh — the state files focus_daemon.sh derives from config: the
# whitelists, the system-protect and blocked-system lists, the cached default
# intent handlers, and the JSON status snapshot the companion app reads.
#
# A flat sibling, not lib/: deploy.sh pushes phone scripts into one directory.
#
# Sourced by focus_daemon.sh, which owns log() and the config.sh globals these
# read ($WHITELIST, $NIGHT_WHITELIST, $SYSTEM_NEVER_DISABLE,
# $BLOCKED_SYSTEM_APPS, $STATE_DIR, $STATUS_FILE, $RADIUS). Nothing here is
# assigned, so there is no global to keep in step.
build_whitelist_file() {
echo "$WHITELIST" | grep -v '^[[:space:]]*#' | grep -v '^[[:space:]]*$' |
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' >"$STATE_DIR/whitelist.txt"
# Sanity check: the WHITELIST string in config.sh is fragile - any
# literal double-quote inside a comment will close the heredoc and
# silently truncate the variable. Log the parsed line count so any
# future regression is visible in the log, and warn loudly if it
# falls below a known floor (we always have ~70+ entries).
local n
n=$(wc -l <"$STATE_DIR/whitelist.txt" 2>/dev/null | tr -d ' ')
log "Whitelist parsed: $n entries"
if [ "${n:-0}" -lt 30 ]; then
log "WARN: whitelist suspiciously small ($n lines) - check config.sh for stray quotes inside WHITELIST string"
fi
}
build_night_whitelist_file() {
# Strict allow-list used while the night curfew is active (see config.sh
# NIGHT_WHITELIST and is_curfew_now()). Parsed exactly like the day list.
echo "$NIGHT_WHITELIST" | grep -v '^[[:space:]]*#' | grep -v '^[[:space:]]*$' |
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' >"$STATE_DIR/night_whitelist.txt"
local n
n=$(wc -l <"$STATE_DIR/night_whitelist.txt" 2>/dev/null | tr -d ' ')
log "Night-curfew whitelist parsed: $n entries"
if [ "${n:-0}" -lt 10 ]; then
log "WARN: night whitelist suspiciously small ($n lines) - check config.sh for stray quotes inside NIGHT_WHITELIST string"
fi
}
build_sysprotect_file() {
echo "$SYSTEM_NEVER_DISABLE" | grep -v '^[[:space:]]*$' |
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' >"$STATE_DIR/sysprotect.txt"
}
# $BLOCKED_SYSTEM_APPS is a static config value (never changes without a
# daemon restart), so - like build_sysprotect_file above - this only needs
# to run once at startup, not every enable_focus_mode() sweep.
build_blocked_sys_file() {
echo "$BLOCKED_SYSTEM_APPS" | grep -v '^[[:space:]]*#' | grep -v '^[[:space:]]*$' |
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' >"$STATE_DIR/blocked_sys.txt"
}
# ---- Default handler detection ----
# Refreshed once per focus_daemon tick into $STATE_DIR/default_handlers.txt.
# Each line is a package name. Lookup is a cheap grep against this file.
refresh_default_handlers() {
local f="$STATE_DIR/default_handlers.txt"
local tmp="$f.tmp"
: >"$tmp"
# Default Home (launcher). resolve-activity prints "Activity Resolver Table:"
# on line 1 and "<pkg>/<.Activity>" on line 2 in --brief mode.
cmd package resolve-activity --brief \
-c android.intent.category.HOME -a android.intent.action.MAIN 2>/dev/null |
awk -F/ 'NR==2 && $1 != "" {print $1}' >>"$tmp"
# Default Dialer
local dialer
dialer="$(cmd telecom get-default-dialer 2>/dev/null | tr -d '[:space:]')"
[ -n "$dialer" ] && echo "$dialer" >>"$tmp"
# Default SMS handler (settings provider key)
local sms
sms="$(settings get secure sms_default_application 2>/dev/null | tr -d '[:space:]')"
[ -n "$sms" ] && [ "$sms" != "null" ] && echo "$sms" >>"$tmp"
# Default input method (active keyboard). Disabling the active IME with
# pm disable-user PERSISTS across reboot; a 1am reboot would then leave no
# keyboard to type any recovery command. Protect it day and night so the
# curfew can never lock you out of typing.
local ime
ime="$(settings get secure default_input_method 2>/dev/null | cut -d/ -f1)"
[ -n "$ime" ] && [ "$ime" != "null" ] && echo "$ime" >>"$tmp"
sort -u "$tmp" -o "$f"
rm -f "$tmp"
# Default Browser handler is tracked SEPARATELY and guarded only OUTSIDE
# the curfew window (see is_allowed). During curfew the whole point is to
# disable browsers, so the default-handler guard must not resurrect them.
local bf="$STATE_DIR/default_browser.txt"
cmd package resolve-activity --brief \
-a android.intent.action.VIEW -d http://example.com 2>/dev/null |
awk -F/ 'NR==2 && $1 != "" {print $1}' >"$bf.tmp" 2>/dev/null
mv "$bf.tmp" "$bf" 2>/dev/null || : >"$bf"
}
is_default_handler() {
local pkg="$1"
grep -qxF "$pkg" "$STATE_DIR/default_handlers.txt" 2>/dev/null
}
# ---- Status snapshot for companion notification app ----
# Writes a tiny JSON file that focus_status_app reads every few seconds.
# Fields: mode, lat, lon, distance_m, threshold_m, radius_m, disabled_count,
# last_check_ts (unix), last_check_iso (human).
write_status_snapshot() {
local mode="$1" lat="$2" lon="$3" dist="$4" thr="$5"
local count iso ts cf ov frc
count="$(wc -l <"$DISABLED_APPS_FILE" 2>/dev/null | tr -d ' ' || echo 0)"
[ -z "$count" ] && count=0
ts="$(date +%s)"
iso="$(date '+%Y-%m-%d %H:%M:%S')"
# Curfew state for the companion app: 1/0 so it slots into the existing
# numeric JSON path. "curfew" = restrictions active now; "curfew_override"
# = the escape-hatch file is set (curfew suspended).
if curfew_active; then cf=1; else cf=0; fi
if [ -e "$CURFEW_OVERRIDE_FILE" ]; then ov=1; else ov=0; fi
# "curfew_force" = the demo/test force file is set (curfew forced on
# regardless of clock). Lets the companion app show Start/Stop demo.
if [ -e "$CURFEW_FORCE_FILE" ]; then frc=1; else frc=0; fi
local tmp="$STATUS_FILE.tmp"
# Shell-emitted JSON — keep values numeric where possible, strings quoted.
{
printf '{'
printf '"mode":"%s",' "$mode"
printf '"lat":"%s",' "${lat:-}"
printf '"lon":"%s",' "${lon:-}"
printf '"distance_m":%s,' "${dist:-null}"
printf '"threshold_m":%s,' "${thr:-null}"
printf '"radius_m":%s,' "$RADIUS"
printf '"disabled_count":%s,' "$count"
printf '"curfew":%s,' "$cf"
printf '"curfew_override":%s,' "$ov"
printf '"curfew_force":%s,' "$frc"
printf '"last_check_ts":%s,' "$ts"
printf '"last_check_iso":"%s"' "$iso"
printf '}\n'
} >"$tmp" 2>/dev/null || return 0
mv "$tmp" "$STATUS_FILE" 2>/dev/null || true
chmod 644 "$STATUS_FILE" 2>/dev/null || true
}

View File

@ -373,6 +373,9 @@ do_deploy() {
echo "[4/7] Uploading scripts..."
adb_cmd push "$DEPLOY_DIR/config.sh" "/data/local/tmp/focus_stage/config.sh"
adb_cmd push "$DEPLOY_DIR/focus_daemon.sh" "/data/local/tmp/focus_stage/focus_daemon.sh"
adb_cmd push "$DEPLOY_DIR/daemon_location.sh" "/data/local/tmp/focus_stage/daemon_location.sh"
adb_cmd push "$DEPLOY_DIR/daemon_state.sh" "/data/local/tmp/focus_stage/daemon_state.sh"
adb_cmd push "$DEPLOY_DIR/daemon_apps.sh" "/data/local/tmp/focus_stage/daemon_apps.sh"
adb_cmd push "$DEPLOY_DIR/focus_ctl.sh" "/data/local/tmp/focus_stage/focus_ctl.sh"
adb_cmd push "$DEPLOY_DIR/hosts_enforcer.sh" "/data/local/tmp/focus_stage/hosts_enforcer.sh"
adb_cmd push "$DEPLOY_DIR/hosts_magisk.sh" "/data/local/tmp/focus_stage/hosts_magisk.sh"
@ -494,6 +497,9 @@ do_deploy() {
# Move staged files into place with root
adb_root "cp /data/local/tmp/focus_stage/config.sh $REMOTE_DIR/config.sh"
adb_root "cp /data/local/tmp/focus_stage/focus_daemon.sh $REMOTE_DIR/focus_daemon.sh"
adb_root "cp /data/local/tmp/focus_stage/daemon_location.sh $REMOTE_DIR/daemon_location.sh"
adb_root "cp /data/local/tmp/focus_stage/daemon_state.sh $REMOTE_DIR/daemon_state.sh"
adb_root "cp /data/local/tmp/focus_stage/daemon_apps.sh $REMOTE_DIR/daemon_apps.sh"
adb_root "cp /data/local/tmp/focus_stage/focus_ctl.sh $REMOTE_DIR/focus_ctl.sh"
adb_root "cp /data/local/tmp/focus_stage/hosts_enforcer.sh $REMOTE_DIR/hosts_enforcer.sh"
adb_root "cp /data/local/tmp/focus_stage/hosts_magisk.sh $REMOTE_DIR/hosts_magisk.sh"

View File

@ -8,6 +8,12 @@
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
. "$SCRIPT_DIR/config.sh"
# shellcheck source=daemon_location.sh
. "$SCRIPT_DIR/daemon_location.sh"
# shellcheck source=daemon_state.sh
. "$SCRIPT_DIR/daemon_state.sh"
# shellcheck source=daemon_apps.sh
. "$SCRIPT_DIR/daemon_apps.sh"
PIDFILE="$STATE_DIR/daemon.pid"
@ -51,69 +57,10 @@ rotate_log() {
# ---- Build helper files for fast package checks ----
build_whitelist_file() {
echo "$WHITELIST" | grep -v '^[[:space:]]*#' | grep -v '^[[:space:]]*$' |
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' >"$STATE_DIR/whitelist.txt"
# Sanity check: the WHITELIST string in config.sh is fragile - any
# literal double-quote inside a comment will close the heredoc and
# silently truncate the variable. Log the parsed line count so any
# future regression is visible in the log, and warn loudly if it
# falls below a known floor (we always have ~70+ entries).
local n
n=$(wc -l <"$STATE_DIR/whitelist.txt" 2>/dev/null | tr -d ' ')
log "Whitelist parsed: $n entries"
if [ "${n:-0}" -lt 30 ]; then
log "WARN: whitelist suspiciously small ($n lines) - check config.sh for stray quotes inside WHITELIST string"
fi
}
build_night_whitelist_file() {
# Strict allow-list used while the night curfew is active (see config.sh
# NIGHT_WHITELIST and is_curfew_now()). Parsed exactly like the day list.
echo "$NIGHT_WHITELIST" | grep -v '^[[:space:]]*#' | grep -v '^[[:space:]]*$' |
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' >"$STATE_DIR/night_whitelist.txt"
local n
n=$(wc -l <"$STATE_DIR/night_whitelist.txt" 2>/dev/null | tr -d ' ')
log "Night-curfew whitelist parsed: $n entries"
if [ "${n:-0}" -lt 10 ]; then
log "WARN: night whitelist suspiciously small ($n lines) - check config.sh for stray quotes inside NIGHT_WHITELIST string"
fi
}
build_sysprotect_file() {
echo "$SYSTEM_NEVER_DISABLE" | grep -v '^[[:space:]]*$' |
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' >"$STATE_DIR/sysprotect.txt"
}
# $BLOCKED_SYSTEM_APPS is a static config value (never changes without a
# daemon restart), so - like build_sysprotect_file above - this only needs
# to run once at startup, not every enable_focus_mode() sweep.
build_blocked_sys_file() {
echo "$BLOCKED_SYSTEM_APPS" | grep -v '^[[:space:]]*#' | grep -v '^[[:space:]]*$' |
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' >"$STATE_DIR/blocked_sys.txt"
}
reconcile_disabled_apps() {
[ -f "$DISABLED_APPS_FILE" ] || return
local tmp_disabled="$STATE_DIR/disabled_by_focus.tmp"
: >"$tmp_disabled"
while IFS= read -r pkg; do
[ -z "$pkg" ] && continue
if is_allowed "$pkg"; then
pm install-existing --user 0 "$pkg" >/dev/null 2>&1 || true
pm enable "$pkg" >/dev/null 2>&1 || true
log "Re-enabled allowed app during state reconciliation: $pkg"
continue
fi
echo "$pkg" >>"$tmp_disabled"
done <"$DISABLED_APPS_FILE"
mv "$tmp_disabled" "$DISABLED_APPS_FILE"
}
# ---- Initialization ----
init() {
@ -163,302 +110,18 @@ init() {
log "Intervals: focus=${CHECK_INTERVAL_FOCUS}s normal=${CHECK_INTERVAL_NORMAL}s"
}
# ---- Location ----
get_location() {
dumpsys location 2>/dev/null |
grep -oE '[-]?[0-9]{1,3}\.[0-9]{4,},[-]?[0-9]{1,3}\.[0-9]{4,}' |
head -1
}
# ---- Distance Calculation (Haversine via awk) ----
calc_distance() {
echo "$1 $2 $3 $4" | awk '{
PI = 3.14159265358979323846
R = 6371000.0
lat1 = $1 * PI / 180.0
lon1 = $2 * PI / 180.0
lat2 = $3 * PI / 180.0
lon2 = $4 * PI / 180.0
dlat = lat2 - lat1
dlon = lon2 - lon1
sdlat = sin(dlat / 2.0)
sdlon = sin(dlon / 2.0)
a = sdlat * sdlat + cos(lat1) * cos(lat2) * sdlon * sdlon
c = 2.0 * atan2(sqrt(a), sqrt(1.0 - a))
printf "%d\n", R * c
}'
}
# ---- Night curfew time check ----
# Returns 0 (true) when the local clock is inside the curfew window.
# Fails OPEN (return 1 = not curfew) on a malformed clock so a broken `date`
# can never strand you behind the strict list — essentials stay reachable
# either way, but the day list is the less-surprising default.
_dec() {
# Strip leading zeros so a zero-padded HHMM ("0500", "0830") is not parsed
# as (sometimes invalid) octal by the shell's arithmetic. Portable across
# ash/mksh; keeps at least one digit so "0000" -> "0".
local n="$1"
while [ "${n#0}" != "$n" ] && [ "${#n}" -gt 1 ]; do n="${n#0}"; done
printf '%s' "$n"
}
is_curfew_now() {
local now start end
now="$(date +%H%M 2>/dev/null)"
case "$now" in
'' | *[!0-9]*) return 1 ;;
esac
now="$(_dec "$now")"
start="$(_dec "$NIGHT_CURFEW_START")"
end="$(_dec "$NIGHT_CURFEW_END")"
if [ "$start" -le "$end" ]; then
[ "$now" -ge "$start" ] && [ "$now" -lt "$end" ]
else
# Window wraps past midnight (e.g. 2300 -> 0500).
[ "$now" -ge "$start" ] || [ "$now" -lt "$end" ]
fi
}
# Curfew is ACTIVE when enabled, not manually overridden, and either forced on
# (test hook) or inside the time window. The is_allowed() switch below consults
# this; because is_allowed() only runs during the focus-mode sweep/reconcile,
# curfew automatically takes effect only at home and is a no-op when away.
#
# Memoized once per main-loop tick (reset at the top of main()'s while loop):
# is_allowed() calls this once per enabled package in the sweep, and
# is_curfew_now forks `date` - on-device this meant up to ~N extra forks per
# 10s tick for N enabled apps, all recomputing a value that cannot change
# within a single tick. Result is cached in _CURFEW_TICK_RESULT.
curfew_active() {
if [ -n "$_CURFEW_TICK_CACHED" ]; then
[ "$_CURFEW_TICK_RESULT" = "1" ]
return
fi
_CURFEW_TICK_CACHED=1
_CURFEW_TICK_RESULT=0
if [ "${NIGHT_CURFEW_ENABLED:-0}" = "1" ] && [ ! -e "$CURFEW_OVERRIDE_FILE" ]; then
if [ -e "$CURFEW_FORCE_FILE" ] || is_curfew_now; then
_CURFEW_TICK_RESULT=1
fi
fi
[ "$_CURFEW_TICK_RESULT" = "1" ]
}
# ---- Check if package is allowed (whitelist or system-protected) ----
is_allowed() {
local pkg="$1"
# During the night curfew, swap the permissive day list for the strict
# night list. The sysprotect + default-handler guards below still apply on
# top of whichever list is active.
local list="$STATE_DIR/whitelist.txt"
if curfew_active; then
list="$STATE_DIR/night_whitelist.txt"
fi
# Exact match against the active whitelist file
if grep -qxF "$pkg" "$list" 2>/dev/null; then
return 0
fi
# Prefix match against system-protect file
while IFS= read -r prefix; do
[ -z "$prefix" ] && continue
case "$pkg" in
"$prefix"*) return 0 ;;
esac
done <"$STATE_DIR/sysprotect.txt"
# Hard-stop guard: refuse to disable any package that is the current
# default handler for a critical role (Dialer / SMS / Home / Contacts).
# Without this, a misconfigured WHITELIST can disable the default Phone
# app and Android falls back to com.android.settings/.FallbackHome -
# the persistent "Phone is starting..." screen with broken SystemUI
# gestures (no swipe-up recents). Recovering requires `pm enable` over
# ADB. Treat the guard as last-resort safety net independent of WHITELIST
# contents so a future config edit can never wipe these out.
is_default_handler "$pkg" && return 0
# The default browser is guarded only OUTSIDE curfew. At night the whole
# point is to disable browsers, so this guard must not re-allow it.
if ! curfew_active &&
grep -qxF "$pkg" "$STATE_DIR/default_browser.txt" 2>/dev/null; then
return 0
fi
return 1
}
# ---- Default handler detection ----
# Refreshed once per focus_daemon tick into $STATE_DIR/default_handlers.txt.
# Each line is a package name. Lookup is a cheap grep against this file.
refresh_default_handlers() {
local f="$STATE_DIR/default_handlers.txt"
local tmp="$f.tmp"
: >"$tmp"
# Default Home (launcher). resolve-activity prints "Activity Resolver Table:"
# on line 1 and "<pkg>/<.Activity>" on line 2 in --brief mode.
cmd package resolve-activity --brief \
-c android.intent.category.HOME -a android.intent.action.MAIN 2>/dev/null |
awk -F/ 'NR==2 && $1 != "" {print $1}' >>"$tmp"
# Default Dialer
local dialer
dialer="$(cmd telecom get-default-dialer 2>/dev/null | tr -d '[:space:]')"
[ -n "$dialer" ] && echo "$dialer" >>"$tmp"
# Default SMS handler (settings provider key)
local sms
sms="$(settings get secure sms_default_application 2>/dev/null | tr -d '[:space:]')"
[ -n "$sms" ] && [ "$sms" != "null" ] && echo "$sms" >>"$tmp"
# Default input method (active keyboard). Disabling the active IME with
# pm disable-user PERSISTS across reboot; a 1am reboot would then leave no
# keyboard to type any recovery command. Protect it day and night so the
# curfew can never lock you out of typing.
local ime
ime="$(settings get secure default_input_method 2>/dev/null | cut -d/ -f1)"
[ -n "$ime" ] && [ "$ime" != "null" ] && echo "$ime" >>"$tmp"
sort -u "$tmp" -o "$f"
rm -f "$tmp"
# Default Browser handler is tracked SEPARATELY and guarded only OUTSIDE
# the curfew window (see is_allowed). During curfew the whole point is to
# disable browsers, so the default-handler guard must not resurrect them.
local bf="$STATE_DIR/default_browser.txt"
cmd package resolve-activity --brief \
-a android.intent.action.VIEW -d http://example.com 2>/dev/null |
awk -F/ 'NR==2 && $1 != "" {print $1}' >"$bf.tmp" 2>/dev/null
mv "$bf.tmp" "$bf" 2>/dev/null || : >"$bf"
}
is_default_handler() {
local pkg="$1"
grep -qxF "$pkg" "$STATE_DIR/default_handlers.txt" 2>/dev/null
}
# ---- Focus Mode Control ----
enable_focus_mode() {
local first_entry=0
if [ "$CURRENT_MODE" != "focus" ]; then
first_entry=1
log "ENABLING focus mode - restricting non-whitelisted apps"
: >"$DISABLED_APPS_FILE"
fi
# Refresh default-handler list every tick. The user may switch dialer /
# SMS / launcher between sweeps; the guard in is_allowed() consults this
# list so a newly-promoted handler is never disabled.
refresh_default_handlers
# Blocked system app list is static; built once in init() (see
# build_blocked_sys_file), not rebuilt on every sweep.
local blocked_sys="$STATE_DIR/blocked_sys.txt"
# Periodic rescan catches third-party apps the user re-enabled (e.g. via
# Play Store or `pm enable` in a terminal) since the last tick.
# -e = enabled only, so we skip apps that are already disabled.
local tmp_pkgs="$STATE_DIR/pkg_list.txt"
pm list packages -3 -e 2>/dev/null | sed 's/^package://' >"$tmp_pkgs"
local newly_disabled=0
while IFS= read -r pkg; do
[ -z "$pkg" ] && continue
is_allowed "$pkg" && continue
if pm disable-user --user 0 "$pkg" >/dev/null 2>&1; then
grep -qxF "$pkg" "$DISABLED_APPS_FILE" 2>/dev/null ||
echo "$pkg" >>"$DISABLED_APPS_FILE"
newly_disabled=$((newly_disabled + 1))
fi
done <"$tmp_pkgs"
rm -f "$tmp_pkgs"
# Disable-for-user-0 any blocked system apps (Play Store, browsers,
# package installer UI, terminal apps).
# IMPORTANT: We intentionally use pm disable-user (NOT pm uninstall) here.
# pm uninstall -k --user 0 removes the package from Android's user-0
# package registry. If the daemon is killed with SIGKILL during a reboot
# (bypassing the cleanup trap), those packages stay uninstalled across the
# reboot. Android's bootloop-protection (MTK and others) then detects
# missing critical system packages and triggers recovery / factory wipe.
# pm disable-user leaves the package registered but inactive, so the
# PackageManager scan at next boot succeeds and no wipe occurs.
while IFS= read -r pkg; do
[ -z "$pkg" ] && continue
if pm disable-user --user 0 "$pkg" >/dev/null 2>&1; then
grep -qxF "$pkg" "$DISABLED_APPS_FILE" 2>/dev/null ||
echo "$pkg" >>"$DISABLED_APPS_FILE"
newly_disabled=$((newly_disabled + 1))
fi
done <"$blocked_sys"
CURRENT_MODE="focus"
echo "focus" >"$MODE_FILE"
if [ "$first_entry" -eq 1 ]; then
local count
count=$(wc -l <"$DISABLED_APPS_FILE" 2>/dev/null || echo 0)
log "Focus mode enabled - disabled $count apps"
elif [ "$newly_disabled" -gt 0 ]; then
log "Focus mode re-sweep: re-disabled $newly_disabled apps (re-enabled by user?)"
fi
reconcile_disabled_apps
}
disable_focus_mode() {
[ "$CURRENT_MODE" = "normal" ] && return
log "DISABLING focus mode - re-enabling apps"
local count=0
if [ -f "$DISABLED_APPS_FILE" ] && [ -s "$DISABLED_APPS_FILE" ]; then
# Re-enable all disabled apps (both 3rd-party and system apps).
# Both paths now use pm disable-user, so pm enable is the only
# restore command needed.
while IFS= read -r pkg; do
[ -z "$pkg" ] && continue
pm enable "$pkg" >/dev/null 2>&1 && count=$((count + 1))
done <"$DISABLED_APPS_FILE"
: >"$DISABLED_APPS_FILE"
fi
CURRENT_MODE="normal"
echo "normal" >"$MODE_FILE"
log "Focus mode disabled - re-enabled $count apps"
}
# ---- Status snapshot for companion notification app ----
# Writes a tiny JSON file that focus_status_app reads every few seconds.
# Fields: mode, lat, lon, distance_m, threshold_m, radius_m, disabled_count,
# last_check_ts (unix), last_check_iso (human).
write_status_snapshot() {
local mode="$1" lat="$2" lon="$3" dist="$4" thr="$5"
local count iso ts cf ov frc
count="$(wc -l <"$DISABLED_APPS_FILE" 2>/dev/null | tr -d ' ' || echo 0)"
[ -z "$count" ] && count=0
ts="$(date +%s)"
iso="$(date '+%Y-%m-%d %H:%M:%S')"
# Curfew state for the companion app: 1/0 so it slots into the existing
# numeric JSON path. "curfew" = restrictions active now; "curfew_override"
# = the escape-hatch file is set (curfew suspended).
if curfew_active; then cf=1; else cf=0; fi
if [ -e "$CURFEW_OVERRIDE_FILE" ]; then ov=1; else ov=0; fi
# "curfew_force" = the demo/test force file is set (curfew forced on
# regardless of clock). Lets the companion app show Start/Stop demo.
if [ -e "$CURFEW_FORCE_FILE" ]; then frc=1; else frc=0; fi
local tmp="$STATUS_FILE.tmp"
# Shell-emitted JSON — keep values numeric where possible, strings quoted.
{
printf '{'
printf '"mode":"%s",' "$mode"
printf '"lat":"%s",' "${lat:-}"
printf '"lon":"%s",' "${lon:-}"
printf '"distance_m":%s,' "${dist:-null}"
printf '"threshold_m":%s,' "${thr:-null}"
printf '"radius_m":%s,' "$RADIUS"
printf '"disabled_count":%s,' "$count"
printf '"curfew":%s,' "$cf"
printf '"curfew_override":%s,' "$ov"
printf '"curfew_force":%s,' "$frc"
printf '"last_check_ts":%s,' "$ts"
printf '"last_check_iso":"%s"' "$iso"
printf '}\n'
} >"$tmp" 2>/dev/null || return 0
mv "$tmp" "$STATUS_FILE" 2>/dev/null || true
chmod 644 "$STATUS_FILE" 2>/dev/null || true
}
# ---- Sleep with early-wake on recheck trigger ----
# Polls for $RECHECK_TRIGGER every second; if found, consumes it and returns

View File

@ -0,0 +1,143 @@
#!/usr/bin/env bash
# lib/tests/daemon_cases_apps.sh — assertions for daemon_apps.sh: which
# packages survive the focus-mode sweep, and what happens on the way in and
# out of focus mode.
#
# Sourced by test_daemon_libs.sh after daemon_libs_harness.sh, which owns the
# stubs, the subjects and the PASS/FAIL counters this file adds to.
#
# is_allowed is the single decision that determines whether an app keeps
# working. Everything below is a way of getting it wrong: the wrong list at
# night, a prefix that matches too much, a guard that resurrects a browser
# during curfew, or a default handler that gets disabled and leaves the phone
# without a keyboard after a reboot.
set -euo pipefail
_seed_lists() {
printf 'com.allowed.day\ncom.both\n' >"${STATE_DIR}/whitelist.txt"
printf 'com.both\n' >"${STATE_DIR}/night_whitelist.txt"
printf 'com.android.\n' >"${STATE_DIR}/sysprotect.txt"
: >"${STATE_DIR}/default_handlers.txt"
: >"${STATE_DIR}/default_browser.txt"
}
# --- is_allowed, day --------------------------------------------------------
_reset_dev
_seed_lists
NIGHT_CURFEW_ENABLED=0
if is_allowed "com.allowed.day"; then
_t_pass "a day-whitelisted package is allowed outside curfew"
else
_t_fail "the day whitelist must apply outside curfew"
fi
if ! is_allowed "com.random.app"; then
_t_pass "an unlisted package is not allowed"
else
_t_fail "an unlisted package must not be allowed"
fi
# Exact match on the whitelist. The query has to be a SUBSTRING of a listed
# entry, not a superstring: grep -qF "com.allowed" would match the line
# "com.allowed.day" and let an unlisted package through, while
# "com.allowed.dayplanner" fails under both -qF and -qxF and so proves
# nothing about which is in use.
if ! is_allowed "com.allowed"; then
_t_pass "whitelist matching is exact, not by substring"
else
_t_fail "a substring of a whitelist entry must not be allowed"
fi
if ! is_allowed "com.allowed.dayplanner"; then
_t_pass "a superstring of a whitelist entry is not allowed"
else
_t_fail "a superstring of a whitelist entry must not be allowed"
fi
# The sysprotect list IS a prefix list, deliberately, so a whole namespace
# stays reachable.
if is_allowed "com.android.settings"; then
_t_pass "the sysprotect list matches by prefix"
else
_t_fail "sysprotect must match by prefix"
fi
# Anchored at the START, not matched anywhere: "org.evil.com.android.thing"
# contains the protected prefix but is not in that namespace, and an
# unanchored match would silently protect any package that mentions it.
if ! is_allowed "org.evil.com.android.thing"; then
_t_pass "a sysprotect prefix must match at the start, not anywhere"
else
_t_fail "a sysprotect prefix must be anchored at the start"
fi
if ! is_allowed "org.android.fake"; then
_t_pass "a package outside the protected namespace is not protected"
else
_t_fail "only the protected namespace may match sysprotect"
fi
# The default-handler guard is independent of the whitelist, so a config edit
# can never disable the dialer, SMS app, launcher or keyboard.
printf 'com.dialer.app\n' >"${STATE_DIR}/default_handlers.txt"
if is_allowed "com.dialer.app"; then
_t_pass "a default handler is allowed even when not whitelisted"
else
_t_fail "the default-handler guard must override the whitelist"
fi
# The browser guard applies only outside curfew.
printf 'com.browser.app\n' >"${STATE_DIR}/default_browser.txt"
if is_allowed "com.browser.app"; then
_t_pass "the default browser is allowed outside curfew"
else
_t_fail "the default browser must be allowed outside curfew"
fi
# --- is_allowed, night curfew ----------------------------------------------
_reset_dev
_seed_lists
printf 'com.browser.app\n' >"${STATE_DIR}/default_browser.txt"
NIGHT_CURFEW_ENABLED=1
_set_now "0000"
# The strict list replaces the permissive one — this is the whole point of the
# curfew, and getting it backwards would leave the night unrestricted.
if is_allowed "com.both"; then
_t_pass "a night-whitelisted package is allowed during curfew"
else
_t_fail "the night whitelist must apply during curfew"
fi
if ! is_allowed "com.allowed.day"; then
_t_pass "a day-only package is blocked during curfew"
else
_t_fail "the day list must NOT apply during curfew"
fi
# The browser guard must not resurrect a browser at night.
if ! is_allowed "com.browser.app"; then
_t_pass "the default browser is blocked during curfew"
else
_t_fail "the browser guard must not re-allow a browser during curfew"
fi
# The sysprotect and default-handler guards still apply on top of the strict
# list, or the curfew could disable the keyboard.
if is_allowed "com.android.settings"; then
_t_pass "sysprotect still applies during curfew"
else
_t_fail "sysprotect must apply during curfew too"
fi
printf 'com.ime.app\n' >"${STATE_DIR}/default_handlers.txt"
if is_allowed "com.ime.app"; then
_t_pass "the default-handler guard still applies during curfew"
else
_t_fail "the keyboard must stay reachable during curfew"
fi
NIGHT_CURFEW_ENABLED=0
_t_eq "0" "${NIGHT_CURFEW_ENABLED}" \
"the curfew is switched back off for the sweep cases"

View File

@ -0,0 +1,228 @@
#!/usr/bin/env bash
# lib/tests/daemon_cases_location.sh — assertions for daemon_location.sh: the
# GPS fix, the Haversine distance, and the night-curfew window.
#
# Sourced by test_daemon_libs.sh after daemon_libs_harness.sh, which owns the
# stubs, the subjects and the PASS/FAIL counters this file adds to.
#
# The curfew window wraps past midnight (2300 -> 0500), which is the case a
# naive start<=now<end comparison gets exactly backwards: it would report
# curfew during the whole day and never at night.
set -euo pipefail
# --- get_location -----------------------------------------------------------
_reset_dev
_t_eq "" "$(get_location)" "location is empty when dumpsys reports no fix"
printf 'last location=Location[fused 52.2297,21.0122 hAcc=12]\n' >"${DEV}/dumpsys_out"
_t_eq "52.2297,21.0122" "$(get_location)" "location extracts a fused coordinate pair"
# Several fixes in one dump: the first is the freshest and the only one used.
printf 'Location[fused 52.2297,21.0122]\nLocation[gps 50.0000,19.0000]\n' >"${DEV}/dumpsys_out"
_t_eq "52.2297,21.0122" "$(get_location)" "location takes only the first fix"
# Too few decimal places is not a real fix and must not be matched, or the
# daemon would compute a distance from a truncated coordinate.
printf 'Location[fused 52.22,21.01]\n' >"${DEV}/dumpsys_out"
_t_eq "" "$(get_location)" "location ignores coordinates with too little precision"
printf 'Location[fused -33.8688,151.2093]\n' >"${DEV}/dumpsys_out"
_t_eq "-33.8688,151.2093" "$(get_location)" "location handles southern/negative coordinates"
# --- calc_distance ----------------------------------------------------------
_t_eq "0" "$(calc_distance 52.2297 21.0122 52.2297 21.0122)" \
"distance from a point to itself is zero"
# Warsaw to Krakow is ~252 km. A wrong radius or a degrees/radians slip shows
# up here as an answer off by orders of magnitude, not a rounding difference.
km="$(( $(calc_distance 52.2297 21.0122 50.0647 19.9450) / 1000 ))"
if [[ "${km}" -ge 245 && "${km}" -le 260 ]]; then
_t_pass "distance Warsaw-Krakow is ~252 km (got ${km} km)"
else
_t_fail "distance Warsaw-Krakow should be ~252 km, got ${km} km"
fi
# One degree of latitude is ~111 km anywhere on the globe.
deg="$(calc_distance 0 0 1 0)"
if [[ "${deg}" -ge 110000 && "${deg}" -le 112000 ]]; then
_t_pass "one degree of latitude is ~111 km (got ${deg} m)"
else
_t_fail "one degree of latitude should be ~111 km, got ${deg} m"
fi
# Symmetry: the distance cannot depend on which point is called home.
_t_eq "$(calc_distance 52.2297 21.0122 50.0647 19.9450)" \
"$(calc_distance 50.0647 19.9450 52.2297 21.0122)" \
"distance is symmetric"
# A short hop must still register, since the geofence threshold is ~100 m.
near="$(calc_distance 52.2297 21.0122 52.2306 21.0122)"
if [[ "${near}" -ge 80 && "${near}" -le 120 ]]; then
_t_pass "a 0.0009 degree step is ~100 m (got ${near} m)"
else
_t_fail "a 0.0009 degree step should be ~100 m, got ${near} m"
fi
# --- _dec -------------------------------------------------------------------
# Zero-padded times must not be read as octal: "0830" as octal is invalid and
# would abort the comparison, stranding the daemon on the wrong app list.
_t_eq "830" "$(_dec 0830)" "_dec strips the leading zero from 0830"
_t_eq "500" "$(_dec 0500)" "_dec strips the leading zero from 0500"
_t_eq "0" "$(_dec 0000)" "_dec keeps a single digit for midnight"
_t_eq "2300" "$(_dec 2300)" "_dec leaves an unpadded time alone"
_t_eq "9" "$(_dec 0009)" "_dec strips several leading zeros"
# --- is_curfew_now, wrapping window (2300 -> 0500) --------------------------
_reset_dev
NIGHT_CURFEW_START="2300"
NIGHT_CURFEW_END="0500"
for t in 2300 2359 0000 0430; do
_set_now "${t}"
if is_curfew_now; then
_t_pass "curfew is open at ${t} inside the wrapping window"
else
_t_fail "curfew should be open at ${t}"
fi
done
for t in 0500 1200 2259; do
_set_now "${t}"
if ! is_curfew_now; then
_t_pass "curfew is closed at ${t} outside the wrapping window"
else
_t_fail "curfew should be closed at ${t}"
fi
done
# --- is_curfew_now, non-wrapping window -------------------------------------
NIGHT_CURFEW_START="0900"
NIGHT_CURFEW_END="1700"
_set_now "1200"
if is_curfew_now; then
_t_pass "curfew is open midway through a same-day window"
else
_t_fail "curfew should be open at 1200 for a 0900-1700 window"
fi
_set_now "0900"
if is_curfew_now; then
_t_pass "a same-day window includes its start minute"
else
_t_fail "0900 should be inside a 0900-1700 window"
fi
# The end is exclusive, or two adjacent windows would both claim the boundary.
_set_now "1700"
if ! is_curfew_now; then
_t_pass "a same-day window excludes its end minute"
else
_t_fail "1700 should be outside a 0900-1700 window"
fi
_set_now "0800"
if ! is_curfew_now; then
_t_pass "curfew is closed before a same-day window opens"
else
_t_fail "0800 should be outside a 0900-1700 window"
fi
NIGHT_CURFEW_START="2300"
NIGHT_CURFEW_END="0500"
# Read back so the reset has a reader in this file (SC2034); the subject is
# what actually consumes it, but each file is linted standalone.
_t_eq "2300-0500" "${NIGHT_CURFEW_START}-${NIGHT_CURFEW_END}" \
"the wrapping window is restored for the remaining cases"
# A broken clock must fail OPEN — to the day list, not the strict one.
_set_now "not-a-time"
if ! is_curfew_now; then
_t_pass "a malformed clock reads as no curfew rather than permanent curfew"
else
_t_fail "a malformed clock must not enable the curfew"
fi
_set_now ""
if ! is_curfew_now; then
_t_pass "an empty clock reading reads as no curfew"
else
_t_fail "an empty clock must not enable the curfew"
fi
# --- curfew_active ----------------------------------------------------------
_reset_dev
_set_now "0000"
if curfew_active; then
_t_pass "curfew is active inside the window when enabled"
else
_t_fail "curfew should be active at 0000 when enabled"
fi
_reset_dev
_set_now "1200"
if ! curfew_active; then
_t_pass "curfew is inactive outside the window"
else
_t_fail "curfew should be inactive at 1200"
fi
# The force file is the test hook: it opens curfew regardless of the clock.
_reset_dev
_set_now "1200"
touch "${CURFEW_FORCE_FILE}"
if curfew_active; then
_t_pass "the force file opens curfew outside the window"
else
_t_fail "the force file should open curfew regardless of the clock"
fi
# The override must beat the force file, or there is no way out.
_reset_dev
touch "${CURFEW_OVERRIDE_FILE}"
_set_now "0000"
if ! curfew_active; then
_t_pass "the override file closes curfew even when forced"
else
_t_fail "the override must take precedence over the force file"
fi
rm -f "${CURFEW_OVERRIDE_FILE}" "${CURFEW_FORCE_FILE}"
_reset_dev
NIGHT_CURFEW_ENABLED=0
_set_now "0000"
if ! curfew_active; then
_t_pass "curfew is inactive while the feature is disabled"
else
_t_fail "curfew must be inactive when NIGHT_CURFEW_ENABLED is 0"
fi
NIGHT_CURFEW_ENABLED=1
_t_eq "1" "${NIGHT_CURFEW_ENABLED}" \
"the curfew is re-enabled for the memo cases"
# The memo exists to stop is_curfew_now forking `date` once per package in
# the sweep. Proven by moving the clock and requiring the answer not to move.
_reset_dev
_set_now "0000"
curfew_active
_set_now "1200"
if curfew_active; then
_t_pass "curfew_active answers from the per-tick memo, not the clock"
else
_t_fail "the memo should hold within a tick even as the clock moves"
fi
# Clearing the memo is what main does each tick; the answer must then follow
# the clock again, or a curfew could never end.
_CURFEW_TICK_CACHED=""
if ! curfew_active; then
_t_pass "clearing the memo lets the answer follow the clock again"
else
_t_fail "a cleared memo must be recomputed"
fi

View File

@ -0,0 +1,257 @@
#!/usr/bin/env bash
# lib/tests/daemon_cases_state.sh — assertions for daemon_state.sh: the state
# files derived from config, the cached default intent handlers, and the JSON
# status snapshot the companion app reads.
#
# Sourced by test_daemon_libs.sh after daemon_libs_harness.sh, which owns the
# stubs, the subjects and the PASS/FAIL counters this file adds to.
set -euo pipefail
# `settings` is only reached from refresh_default_handlers; stubbed here
# rather than in the harness because these are its only callers.
cat >"${RUN}/bin/settings" <<'STUB'
#!/usr/bin/env bash
printf 'settings %s\n' "$*" >>"${DEV}/calls.log"
key="${*: -1}"
[[ -f "${DEV}/setting_${key}" ]] && cat "${DEV}/setting_${key}"
exit 0
STUB
chmod +x "${RUN}/bin/settings"
# --- build_whitelist_file ---------------------------------------------------
_reset_dev
WHITELIST="com.one
com.two
# a comment
com.three "
build_whitelist_file
parsed="$(cat "${STATE_DIR}/whitelist.txt")"
_t_eq "com.one com.two com.three" "$(printf '%s' "${parsed}" | tr '\n' ' ' | sed 's/ $//')" \
"whitelist drops comments and blanks and trims whitespace"
# The floor warning exists because a stray quote in config.sh silently
# truncates the WHITELIST string; a short list must be loud, not silent.
case "$(_log)" in
*"WARN: whitelist suspiciously small"*) _t_pass "a short whitelist warns loudly" ;;
*) _t_fail "a whitelist under the floor must warn" ;;
esac
case "$(_log)" in
*"Whitelist parsed: 3 entries"*) _t_pass "whitelist logs the parsed entry count" ;;
*) _t_fail "whitelist should log its entry count" ;;
esac
# A healthy list must not cry wolf, or the warning stops meaning anything.
_reset_dev
WHITELIST="$(for i in $(seq 1 40); do printf 'com.app%02d\n' "$i"; done)"
build_whitelist_file
if _log | grep -q "WARN: whitelist suspiciously small"; then
_t_fail "a 40-entry whitelist must not warn"
else
_t_pass "a healthy whitelist does not warn"
fi
_t_eq "40" "$(wc -l <"${STATE_DIR}/whitelist.txt")" "whitelist keeps every entry"
_t_eq "40" "$(printf '%s\n' "${WHITELIST}" | wc -l)" \
"the seeded whitelist really held 40 entries"
# --- build_night_whitelist_file --------------------------------------------
_reset_dev
NIGHT_WHITELIST="com.night.one
# comment
com.night.two"
build_night_whitelist_file
_t_eq "com.night.one com.night.two" \
"$(tr '\n' ' ' <"${STATE_DIR}/night_whitelist.txt" | sed 's/ $//')" \
"night whitelist parses like the day list"
case "$(_log)" in
*"WARN: night whitelist suspiciously small"*) _t_pass "a short night whitelist warns" ;;
*) _t_fail "a night whitelist under its floor must warn" ;;
esac
# The two lists have different floors (30 and 10), so a list that is fine for
# one must not be judged by the other's threshold.
_reset_dev
NIGHT_WHITELIST="$(for i in $(seq 1 12); do printf 'com.night%02d\n' "$i"; done)"
build_night_whitelist_file
_t_eq "12" "$(printf '%s\n' "${NIGHT_WHITELIST}" | wc -l)" \
"the seeded night whitelist really held 12 entries"
if _log | grep -q "WARN: night whitelist"; then
_t_fail "12 night entries is above the night floor and must not warn"
else
_t_pass "the night whitelist uses its own lower floor"
fi
# --- build_sysprotect_file / build_blocked_sys_file ------------------------
_reset_dev
SYSTEM_NEVER_DISABLE="com.android.
com.google.android.gms"
build_sysprotect_file
_t_eq "2" "$(wc -l <"${STATE_DIR}/sysprotect.txt")" "sysprotect writes every prefix"
_t_eq "2" "$(printf '%s\n' "${SYSTEM_NEVER_DISABLE}" | wc -l)" \
"the seeded sysprotect list really held two prefixes"
BLOCKED_SYSTEM_APPS="com.android.browser
# not this one
com.android.chrome"
build_blocked_sys_file
_t_eq "com.android.browser com.android.chrome" \
"$(tr '\n' ' ' <"${STATE_DIR}/blocked_sys.txt" | sed 's/ $//')" \
"blocked-system list drops comments"
_t_eq "3" "$(printf '%s\n' "${BLOCKED_SYSTEM_APPS}" | wc -l)" \
"the seeded blocked-system list really held three lines"
# --- refresh_default_handlers ----------------------------------------------
_reset_dev
printf 'Activity Resolver Table:\ncom.launcher.home/.MainActivity\n' >"${DEV}/cmd_out"
printf 'com.dialer.app\n' >"${DEV}/setting_get"
printf 'com.sms.app\n' >"${DEV}/setting_sms_default_application"
printf 'com.ime.app/.Service\n' >"${DEV}/setting_default_input_method"
refresh_default_handlers
handlers="$(cat "${STATE_DIR}/default_handlers.txt")"
case "${handlers}" in
*com.launcher.home*) _t_pass "default handlers include the launcher" ;;
*) _t_fail "default handlers must include the launcher" ;;
esac
# The IME is the load-bearing one: pm disable-user on the active keyboard
# survives a reboot, so a 1am reboot would leave no way to type a recovery
# command. It has to be protected day and night.
case "${handlers}" in
*com.ime.app*) _t_pass "default handlers include the active keyboard" ;;
*) _t_fail "the active IME must be protected or a reboot locks you out" ;;
esac
# Only the package part of the IME component is usable as a package name.
if grep -q "com.ime.app/" "${STATE_DIR}/default_handlers.txt"; then
_t_fail "the IME component suffix leaked into the package list"
else
_t_pass "the IME is recorded as a package, not a component"
fi
# A literal "null" from the settings provider is an absent value, not a
# package, and must never be written as one.
_reset_dev
printf 'Activity Resolver Table:\ncom.launcher.home/.MainActivity\n' >"${DEV}/cmd_out"
printf 'null\n' >"${DEV}/setting_sms_default_application"
printf 'null\n' >"${DEV}/setting_default_input_method"
refresh_default_handlers
if grep -qx "null" "${STATE_DIR}/default_handlers.txt"; then
_t_fail "a literal null was recorded as a default handler"
else
_t_pass "a null settings value is not recorded as a handler"
fi
if [[ -f "${STATE_DIR}/default_handlers.txt.tmp" ]]; then
_t_fail "refresh left its temp file behind"
else
_t_pass "refresh cleans up its temp file"
fi
# The browser is tracked separately, because during curfew the whole point is
# to disable browsers — the default-handler guard must not resurrect them.
if [[ -f "${STATE_DIR}/default_browser.txt" ]]; then
_t_pass "the default browser is tracked in its own file"
else
_t_fail "the default browser must be tracked separately"
fi
# --- is_default_handler -----------------------------------------------------
_reset_dev
printf 'com.launcher.home\ncom.ime.app\n' >"${STATE_DIR}/default_handlers.txt"
if is_default_handler "com.launcher.home"; then
_t_pass "a listed package is recognised as a default handler"
else
_t_fail "a listed package must be recognised"
fi
if ! is_default_handler "com.other.app"; then
_t_pass "an unlisted package is not a default handler"
else
_t_fail "an unlisted package must not be recognised"
fi
# Exact match only: a prefix would protect far more than intended.
if ! is_default_handler "com.launcher"; then
_t_pass "default-handler matching is exact, not by prefix"
else
_t_fail "a prefix must not match a default handler"
fi
# --- write_status_snapshot --------------------------------------------------
_reset_dev
printf 'com.a\ncom.b\ncom.c\n' >"${DISABLED_APPS_FILE}"
_set_now "1200"
write_status_snapshot "focus" "52.2297" "21.0122" "42" "100"
if python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "${STATUS_FILE}"; then
_t_pass "the status snapshot is parseable JSON"
else
_t_fail "the status snapshot must be valid JSON"
fi
_field() {
python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))[sys.argv[2]])' \
"${STATUS_FILE}" "$1"
}
_t_eq "focus" "$(_field mode)" "the snapshot records the mode"
_t_eq "52.2297" "$(_field lat)" "the snapshot records the latitude"
_t_eq "42" "$(_field distance_m)" "the snapshot records the distance"
_t_eq "100" "$(_field threshold_m)" "the snapshot records the threshold"
_t_eq "3" "$(_field disabled_count)" "the snapshot counts the disabled apps"
# Absent coordinates must still produce valid JSON: distance and threshold
# become null, not an empty token that would break the companion app's parse.
_reset_dev
: >"${DISABLED_APPS_FILE}"
write_status_snapshot "normal" "" "" "" ""
if python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "${STATUS_FILE}"; then
_t_pass "a snapshot with no fix is still valid JSON"
else
_t_fail "a snapshot with no fix must remain valid JSON"
fi
_t_eq "None" "$(_field distance_m)" "a missing distance is written as JSON null"
_t_eq "0" "$(_field disabled_count)" "an empty disabled list counts as zero"
# The curfew flags are what the companion app renders, so they must track the
# files rather than being hardcoded.
_reset_dev
touch "${CURFEW_OVERRIDE_FILE}"
write_status_snapshot "normal" "" "" "" ""
_t_eq "1" "$(_field curfew_override)" "the snapshot reports an active override"
_t_eq "0" "$(_field curfew)" "curfew reads inactive while overridden"
rm -f "${CURFEW_OVERRIDE_FILE}"
_reset_dev
touch "${CURFEW_FORCE_FILE}"
write_status_snapshot "normal" "" "" "" ""
_t_eq "1" "$(_field curfew_force)" "the snapshot reports the force flag"
_t_eq "1" "$(_field curfew)" "curfew reads active while forced"
rm -f "${CURFEW_FORCE_FILE}"
if [[ -f "${STATUS_FILE}.tmp" ]]; then
_t_fail "the snapshot left its temp file behind"
else
_t_pass "the snapshot moves its temp file into place"
fi
# An unwritable status file must not take the daemon down with it: the
# snapshot is for the companion app, and losing it is not worth losing
# enforcement. Proven by pointing STATUS_FILE into a directory that does not
# exist, so the redirect fails.
_reset_dev
_saved_status="${STATUS_FILE}"
STATUS_FILE="${RUN}/state/no-such-dir/status.json"
if write_status_snapshot "focus" "" "" "" ""; then
_t_pass "an unwritable snapshot returns success rather than aborting"
else
_t_fail "a failed snapshot write must not propagate a failure"
fi
STATUS_FILE="${_saved_status}"

View File

@ -0,0 +1,173 @@
#!/usr/bin/env bash
# lib/tests/daemon_cases_sweep.sh — assertions for the focus-mode transitions
# in daemon_apps.sh: the sweep that disables non-whitelisted packages, the
# restore pass, and the reconciliation that brings back anything that has
# since become allowed.
#
# Sourced by test_daemon_libs.sh after daemon_cases_apps.sh, which owns
# _seed_lists and the counters. Split out to stay under the 250-line cap.
set -euo pipefail
# --- enable_focus_mode ------------------------------------------------------
_reset_dev
_seed_lists
CURRENT_MODE="normal"
: >"${DISABLED_APPS_FILE}"
_seed_packages com.allowed.day com.random.one com.random.two
: >"${STATE_DIR}/blocked_sys.txt"
enable_focus_mode
_t_eq "focus" "${CURRENT_MODE}" "entering focus mode records the mode"
disabled="$(_disabled | sort | tr '\n' ' ' | sed 's/ $//')"
_t_eq "com.random.one com.random.two" "${disabled}" \
"focus mode disables exactly the non-whitelisted packages"
# Both packages, not just the first. The loop feeding pm reads its list by
# redirect precisely so pm cannot drain its stdin — this assertion is what
# would catch that regression.
_t_eq "2" "$(_disabled | wc -l)" "focus mode processes every package, not just the first"
recorded="$(sort "${DISABLED_APPS_FILE}" | tr '\n' ' ' | sed 's/ $//')"
_t_eq "com.random.one com.random.two" "${recorded}" \
"focus mode records what it disabled so it can be undone"
# Blocked system apps are disabled too, from their own list.
_reset_dev
_seed_lists
CURRENT_MODE="normal"
: >"${DISABLED_APPS_FILE}"
_seed_packages com.allowed.day
printf 'com.android.browser\ncom.android.other\n' >"${STATE_DIR}/blocked_sys.txt"
enable_focus_mode
case "$(_disabled)" in
*com.android.browser*) _t_pass "focus mode disables blocked system apps" ;;
*) _t_fail "blocked system apps must be disabled" ;;
esac
_t_eq "2" "$(_disabled | wc -l)" "every blocked system app is processed"
# A package pm refuses to disable must not be recorded as disabled, or the
# restore pass would claim to re-enable something it never touched.
_reset_dev
_seed_lists
CURRENT_MODE="normal"
: >"${DISABLED_APPS_FILE}"
_seed_packages com.random.one com.stubborn
printf 'com.stubborn\n' >"${DEV}/pm_undisableable"
: >"${STATE_DIR}/blocked_sys.txt"
enable_focus_mode
if grep -qx "com.stubborn" "${DISABLED_APPS_FILE}"; then
_t_fail "a package pm refused to disable was recorded as disabled"
else
_t_pass "only packages pm actually disabled are recorded"
fi
# Re-entering focus mode must not wipe the record of what is already disabled.
_reset_dev
_seed_lists
CURRENT_MODE="focus"
printf 'com.already.off\n' >"${DISABLED_APPS_FILE}"
_seed_packages com.allowed.day
: >"${STATE_DIR}/blocked_sys.txt"
enable_focus_mode
if grep -qx "com.already.off" "${DISABLED_APPS_FILE}"; then
_t_pass "a repeat sweep keeps the existing disabled record"
else
_t_fail "a repeat sweep must not wipe the disabled record"
fi
# --- disable_focus_mode -----------------------------------------------------
_reset_dev
CURRENT_MODE="focus"
printf 'com.random.one\ncom.random.two\n' >"${DISABLED_APPS_FILE}"
disable_focus_mode
_t_eq "normal" "${CURRENT_MODE}" "leaving focus mode records the mode"
_t_eq "com.random.one com.random.two" \
"$(_enabled | sort | tr '\n' ' ' | sed 's/ $//')" \
"leaving focus mode re-enables everything it disabled"
_t_eq "2" "$(_enabled | wc -l)" "every disabled package is re-enabled, not just the first"
# Already normal: nothing to do, and nothing should be touched.
_reset_dev
CURRENT_MODE="normal"
printf 'com.random.one\n' >"${DISABLED_APPS_FILE}"
disable_focus_mode
_t_eq "" "$(_enabled)" "leaving focus mode is a no-op when already normal"
# --- reconcile_disabled_apps ------------------------------------------------
# A package that has since become allowed must be brought back, and dropped
# from the record — otherwise it stays disabled forever.
_reset_dev
_seed_lists
printf 'com.allowed.day\ncom.random.one\n' >"${DISABLED_APPS_FILE}"
reconcile_disabled_apps
case "$(_enabled)" in
*com.allowed.day*) _t_pass "reconciliation re-enables a now-allowed package" ;;
*) _t_fail "a package that became allowed must be re-enabled" ;;
esac
_t_eq "com.random.one" "$(cat "${DISABLED_APPS_FILE}")" \
"reconciliation keeps only the packages that are still blocked"
case "$(_log)" in
*"Re-enabled allowed app during state reconciliation"*)
_t_pass "reconciliation logs what it restored" ;;
*) _t_fail "reconciliation should log the packages it restored" ;;
esac
# install-existing runs before enable: a package removed for user 0 has to be
# reinstalled for that user before it can be enabled at all.
calls="$(_calls)"
inst="$(printf '%s\n' "${calls}" | grep -n "install-existing" | head -1 | cut -d: -f1)"
en="$(printf '%s\n' "${calls}" | grep -n "^pm enable com.allowed.day" | head -1 | cut -d: -f1)"
if [[ -n "${inst}" && -n "${en}" && "${en}" -gt "${inst}" ]]; then
_t_pass "reconciliation reinstalls for user 0 before enabling"
else
_t_fail "install-existing must precede enable"
fi
# No record file at all is a fresh install, not an error. The call is guarded
# because the bare `return` propagates the failed [ -f ] status; the daemon
# runs without set -e so that is harmless there, but it would abort this file.
_reset_dev
_seed_lists
rm -f "${DISABLED_APPS_FILE}"
reconcile_disabled_apps || true
_t_eq "" "$(_enabled)" "reconciliation is a no-op with no disabled record"
if [[ -f "${STATE_DIR}/disabled_by_focus.tmp" ]]; then
_t_fail "reconciliation left its temp file behind"
else
_t_pass "reconciliation moves its temp file into place"
fi
# A re-sweep that finds apps the user re-enabled must say so: silence here
# would hide the single most useful signal that enforcement is being fought.
_reset_dev
_seed_lists
CURRENT_MODE="focus"
: >"${DISABLED_APPS_FILE}"
_seed_packages com.random.one
: >"${STATE_DIR}/blocked_sys.txt"
enable_focus_mode
case "$(_log)" in
*"re-disabled 1 apps"*) _t_pass "a re-sweep reports what the user re-enabled" ;;
*) _t_fail "a re-sweep must report re-disabled apps" ;;
esac
# A re-sweep with nothing to do stays quiet, or the log fills with noise every
# tick and the line above stops carrying information.
_reset_dev
_seed_lists
CURRENT_MODE="focus"
printf 'com.random.one\n' >"${DISABLED_APPS_FILE}"
_seed_packages com.allowed.day
: >"${STATE_DIR}/blocked_sys.txt"
enable_focus_mode
if _log | grep -q "re-sweep"; then
_t_fail "a re-sweep with nothing to do must not log"
else
_t_pass "a quiet re-sweep stays quiet"
fi

View File

@ -0,0 +1,160 @@
#!/usr/bin/env bash
# lib/tests/daemon_libs_harness.sh — the fake device behind the three
# libraries split out of focus_daemon.sh.
#
# Sourced, not executed. All three drive the phone through real binaries — pm,
# dumpsys, cmd, date — so the stubs go on PATH.
#
# `date` is stubbed rather than mocked as a function because is_curfew_now
# calls it in a command substitution; a shell function would work here but
# would not survive the subject being run any other way, and the point of the
# midnight-wrap cases is to pin the clock precisely.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
readonly PHONE_DIR="${SCRIPT_DIR}/../.."
PASS=0
FAIL=0
_t_pass() {
PASS=$((PASS + 1))
printf ' OK: %s\n' "$1"
}
_t_fail() {
FAIL=$((FAIL + 1))
printf ' FAIL: %s\n' "$1"
}
_t_eq() {
local want="$1" got="$2" what="$3"
if [[ "$got" == "$want" ]]; then
_t_pass "$what"
else
_t_fail "$what (want '${want}', got '${got}')"
fi
}
RUN="$(mktemp -d)"
trap 'rm -rf "${RUN}"' EXIT
mkdir -p "${RUN}/bin" "${RUN}/state" "${RUN}/dev"
readonly DEV="${RUN}/dev"
# --- stubs ------------------------------------------------------------------
# pm records every call and honours a per-package failure flag, so the
# "disable refused" branches are reachable.
cat >"${RUN}/bin/pm" <<'STUB'
#!/usr/bin/env bash
printf 'pm %s\n' "$*" >>"${DEV}/calls.log"
case "$1" in
list)
[[ -f "${DEV}/pm_list" ]] && cat "${DEV}/pm_list"
exit 0
;;
disable-user)
pkg="${*: -1}"
grep -qxF "${pkg}" "${DEV}/pm_undisableable" 2>/dev/null && exit 1
printf '%s\n' "${pkg}" >>"${DEV}/disabled"
exit 0
;;
enable)
pkg="${*: -1}"
grep -qxF "${pkg}" "${DEV}/pm_unenableable" 2>/dev/null && exit 1
printf '%s\n' "${pkg}" >>"${DEV}/enabled"
exit 0
;;
esac
exit 0
STUB
chmod +x "${RUN}/bin/pm"
cat >"${RUN}/bin/dumpsys" <<'STUB'
#!/usr/bin/env bash
printf 'dumpsys %s\n' "$*" >>"${DEV}/calls.log"
[[ -f "${DEV}/dumpsys_out" ]] && cat "${DEV}/dumpsys_out"
exit 0
STUB
chmod +x "${RUN}/bin/dumpsys"
cat >"${RUN}/bin/cmd" <<'STUB'
#!/usr/bin/env bash
printf 'cmd %s\n' "$*" >>"${DEV}/calls.log"
[[ -f "${DEV}/cmd_out" ]] && cat "${DEV}/cmd_out"
exit 0
STUB
chmod +x "${RUN}/bin/cmd"
# `date` answers from a pinned clock when one is set, so the curfew-window
# cases are deterministic rather than dependent on when the suite runs.
cat >"${RUN}/bin/date" <<'STUB'
#!/usr/bin/env bash
if [[ -f "${DEV}/now" && "$1" == "+%H%M" ]]; then
cat "${DEV}/now"
exit 0
fi
exec /usr/bin/date "$@"
STUB
chmod +x "${RUN}/bin/date"
export DEV
export PATH="${RUN}/bin:${PATH}"
# --- ambient definitions the libraries expect from the daemon --------------
log() { printf '%s\n' "$*" >>"${DEV}/log"; }
STATE_DIR="${RUN}/state"
STATUS_FILE="${RUN}/state/status.json"
MODE_FILE="${RUN}/state/mode"
DISABLED_APPS_FILE="${RUN}/state/disabled_apps.txt"
CURFEW_FORCE_FILE="${RUN}/state/curfew_force"
CURFEW_OVERRIDE_FILE="${RUN}/state/curfew_override"
NIGHT_CURFEW_ENABLED=1
NIGHT_CURFEW_START="2300"
NIGHT_CURFEW_END="0500"
WHITELIST="com.allowed.one com.allowed.two"
NIGHT_WHITELIST="com.night.only"
SYSTEM_NEVER_DISABLE="com.android."
BLOCKED_SYSTEM_APPS="com.android.browser"
RADIUS=100
# Written by init/enable/disable in the entry script and read by main, so it
# lives there; the harness stands in for that ownership.
CURRENT_MODE="normal"
_CURFEW_TICK_CACHED=""
_CURFEW_TICK_RESULT=0
# shellcheck source=../../daemon_location.sh
. "${PHONE_DIR}/daemon_location.sh"
# shellcheck source=../../daemon_state.sh
. "${PHONE_DIR}/daemon_state.sh"
# shellcheck source=../../daemon_apps.sh
. "${PHONE_DIR}/daemon_apps.sh"
# --- helpers ----------------------------------------------------------------
_reset_dev() {
rm -rf "${DEV}"
mkdir -p "${DEV}"
_CURFEW_TICK_CACHED=""
_CURFEW_TICK_RESULT=0
}
_set_now() { printf '%s\n' "$1" >"${DEV}/now"; }
_calls() { cat "${DEV}/calls.log" 2>/dev/null || printf ''; }
_log() { cat "${DEV}/log" 2>/dev/null || printf ''; }
_disabled() { cat "${DEV}/disabled" 2>/dev/null || printf ''; }
_enabled() { cat "${DEV}/enabled" 2>/dev/null || printf ''; }
# Seed the installed third-party package list `pm list packages -3 -e` returns.
_seed_packages() {
local pkg=""
: >"${DEV}/pm_list"
for pkg in "$@"; do
printf 'package:%s\n' "${pkg}" >>"${DEV}/pm_list"
done
}

View File

@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Unit tests for the three libraries split out of focus_daemon.sh, against the
# fake device in daemon_libs_harness.sh. No real phone is needed.
#
# This is the only entry point; the cases live in sourced files purely to stay
# under the 250-line cap, so one coverage command measures all three subjects.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=daemon_libs_harness.sh
. "${SCRIPT_DIR}/daemon_libs_harness.sh"
# shellcheck source=daemon_cases_location.sh
. "${SCRIPT_DIR}/daemon_cases_location.sh"
# shellcheck source=daemon_cases_state.sh
. "${SCRIPT_DIR}/daemon_cases_state.sh"
# shellcheck source=daemon_cases_apps.sh
. "${SCRIPT_DIR}/daemon_cases_apps.sh"
# shellcheck source=daemon_cases_sweep.sh
. "${SCRIPT_DIR}/daemon_cases_sweep.sh"
printf '\nResults: %d passed, %d failed\n' "${PASS}" "${FAIL}"
[[ "${FAIL}" -eq 0 ]]