Compare commits

..

5 Commits

Author SHA1 Message Date
590bc2004d ci: install jq for the shell tests, and probe for it explicitly
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Python tests / test (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run
The claude_usage i3blocks tests failed on CI while passing locally.
archlinux:base-devel ships no jq, and claude_usage.sh parses its cache
with it, so the block degraded to its "no data" path and every
percentage assertion failed. That degradation is correct at runtime —
the bar should not break because a tool is missing — but it made a
missing dependency look like a logic bug.

Install jq alongside git and strace, and probe for it at the top of the
section so the failure names its own cause. The probe runs jq rather
than calling `command -v`: a jq that exists but cannot execute produces
exactly the same "no data" output as an absent one, and `command -v`
passes in that case — verified by stubbing a jq that exits 127.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YQLwdquDCNmWtvgi3Lk72J
2026-08-10 15:40:42 +02:00
91061edc14 feedback: local-only pacman package build, and ignore build artifacts
fee[dB]ack has no AUR entry, so install_feedback.sh builds a local
package from the PKGBUILD tracked beside it, the same way
hypersomnia-appimage and jackify-bin are installed here. The script only
builds and then prints the `sudo pacman -U` line to run, since
interactive sudo prompts belong to the user rather than an agent.

The built .pkg.tar.zst is ~640 MB, so it is gitignored along with the
Bottles prefixes and the archwiki_rag vector index — all three are local
runtime state that is regenerable and must never enter the history (see
memories/binary-files.md). The PKGBUILD and the installer are the
source and stay tracked.

Exclude PKGBUILDs from shellcheck. A PKGBUILD is a makepkg manifest,
not a standalone script: it has no shebang by design, pkgname/pkgver/
source/sha512sums are read by makepkg, and pkgdir/srcdir are injected by
it, so shellcheck flags every one as unused or undefined. The same
reasoning already excludes zsh — the dialect is outside what shellcheck
can judge — and the alternative was a directive on nearly every line.

Also drops three stray files: a saved search-results page, a 0-byte file
from a mistyped redirect, and a June i3 config backup superseded by git.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YQLwdquDCNmWtvgi3Lk72J
2026-08-10 15:33:18 +02:00
86565bdef6 archwiki_rag: offline semantic search over the Arch Wiki
Indexes the arch-wiki-docs dump that is already on disk and exposes it
to the knowledge-rag MCP server, so Arch questions can be asked by
symptom ("why doesn't my systemd user unit see DISPLAY under i3")
rather than by page title, with no network round-trip at query time.

The one Arch-specific MCP server in the wild fetches pages over the
network and bundles pacman operations that duplicate the local yay-mcp.
This does neither: it only searches, against a local corpus.

install.sh installs its own dependencies, wires the MCP config and
registers a pacman hook so the index follows package updates. The
generated index is machine-specific and regenerable, so it is
gitignored rather than committed.

_reindex_entry runs under the knowledge-rag interpreter, where
mcp_server is importable and this repo's packages are not. Resolving
that import with importlib.import_module states the deferral outright
instead of a function-level import statement that reads as an oversight,
and the backend failure path now re-raises as SystemExit, so the
exit-code translation is explicit rather than a swallowed exception.
Both replace lint suppressions; the package carries none.

pylint runs in its own venv, so beautifulsoup4 and markdownify are
declared there too — being in meta/requirements.txt does not make them
resolvable to the hook.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YQLwdquDCNmWtvgi3Lk72J
2026-08-10 15:33:18 +02:00
cef72fbab0 syncyomi_guard: refuse a collapsed payload as the new good copy
TachiyomiSY 1.13.2 can report a restore as SUCCESS while writing almost
nothing, then sync that near-empty library up and replace the only good
copy. On 2026-08-09 a 14 MB payload holding 2182 manga became a 267 KB
stub, and the real library survived only as stale pages in the SQLite
write-ahead log.

The upstream bug is Kotlin in an APK and cannot be fixed here, so this
targets the fixable half: decode the payload, count what is actually in
it, and refuse to treat a collapse as normal drift. A pure is-it-zero
check would have caught this incident but not the harder case upstream
describes, where a restore keeps some entries and drops the rest, so the
threshold is proportional. Categories get their own rule because all
2182 manga survived the round trip and all 18 categories did not.

Adds the setup script and a runbook covering the WAL-page salvage used
to recover the library on the day.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YQLwdquDCNmWtvgi3Lk72J
2026-08-10 15:33:18 +02:00
f33fd03a16 focus_owner: keep the unhide path reachable, never hide the enforcer
setApplicationHidden drops a package from the default PackageManager
enumeration even though it stays installed=true, so a sweep querying
with flags 0 could never see anything it had already hidden. That made
packagesToShow permanently empty: measured on device, a pass following
one that hid three apps reported "hid 0, restored 0" and left them
hidden with no way back. Query with MATCH_UNINSTALLED_PACKAGES instead.

Hiding the enforcer itself is the other unrecoverable case, since it
takes the escape hatch and the trigger with it. The exporter now injects
com.kuhy.focus_owner into both the day and night allowlists so the
decision layer cannot propose it, and the runner keeps its point-of-use
skip to cover a policy asset rendered before this fix or hand-edited.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YQLwdquDCNmWtvgi3Lk72J
2026-08-10 15:33:18 +02:00
50 changed files with 4184 additions and 11 deletions

View File

@ -60,9 +60,12 @@ jobs:
# ptrace. Without these the trace file is never produced.
options: --cap-add=SYS_PTRACE --security-opt seccomp=unconfined
steps:
# base-devel ships neither git (actions/checkout needs it) nor strace.
# base-devel ships none of these: git (actions/checkout needs it), strace
# (execve counting), or jq (the claude_usage block parses its cache with
# it, and without jq that block degrades to "no data" and its assertions
# fail).
- name: Install dependencies
run: pacman -Sy --noconfirm --needed git strace
run: pacman -Sy --noconfirm --needed git strace jq
- uses: actions/checkout@v4

13
.gitignore vendored
View File

@ -368,6 +368,19 @@ phone_focus_mode/focus_status_app/debug.keystore
# ci_mirror.sh cached requirements.txt venv (rebuilt on demand)
.ci-mirror-venv/
# Locally built Arch packages. The PKGBUILD and installer script are the source
# and stay tracked; the built artifact is a ~600 MB binary that must never be
# committed (see memories/binary-files.md).
linux_configuration/scripts/single_use/*/*.pkg.tar.zst
linux_configuration/scripts/single_use/*/*.pkg.tar.xz
# Wine/Bottles prefixes — local runtime state, not source.
bottles/
# archwiki_rag local vector index: regenerated by `reindex`, machine-specific,
# and full of binary sqlite/parquet blobs.
linux_configuration/scripts/periodic_background/digital_wellbeing/data/
# ===========================================================================
# billsplit (Flutter) — launcher icons & platform assets MUST live in-repo
# ===========================================================================

View File

@ -204,6 +204,11 @@ repos:
- requests
- pygame
- pillow
# archwiki_rag parses the local arch-wiki-docs HTML dump. pylint runs
# in its own venv, so a package being in meta/requirements.txt is not
# enough for it to resolve the import.
- beautifulsoup4
- markdownify
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.1.0#subdirectory=gatelock
- anthropic
- rich
@ -435,7 +440,15 @@ repos:
exclude_types: [zsh]
# Vendored upstream code: we do not own it and patches here would be
# lost on the next vendor sync. Matches the prettier hook's exclusion.
exclude: ^third_party/
#
# PKGBUILDs are makepkg manifests, not standalone scripts: they have no
# shebang by design, and pkgname/pkgver/source/sha512sums are read by
# makepkg while pkgdir/srcdir are injected by it. shellcheck therefore
# reports every one of them as unused-or-undefined (SC2148/SC2034/
# SC2154) -- all false positives, and none suppressible without
# littering the file with directives. Same reasoning as zsh above:
# the dialect is outside what shellcheck can judge.
exclude: ^third_party/|(^|/)PKGBUILD$
# ===========================================================================
# ZSH SYNTAX - zsh -n parse check (shellcheck has no zsh mode)

View File

@ -0,0 +1,17 @@
{
"title": "archwiki_rag: offline semantic search over the Arch Wiki",
"objective": "Let Claude answer Arch questions by symptom rather than by page title, with no network round-trip, by indexing the arch-wiki-docs dump that is already on disk and exposing it to the knowledge-rag MCP server.",
"acceptance_criteria": [
"Converts the local arch-wiki-docs dump into a markdown corpus without fetching pages over the network",
"Builds a searchable index and refreshes it via `sync --reindex`",
"install.sh installs its own dependencies, wires the MCP config and registers a pacman hook so the index follows package updates",
"100% branch coverage across every module in python_pkg/archwiki_rag",
"The generated index is not committed (machine-specific, binary, regenerable)"
],
"out_of_scope": [
"Duplicating yay-mcp's pacman install/remove/update, PKGBUILD checks or system stats — this package only searches",
"Fetching wiki pages over the network at query time",
"Replacing the generic wiki-kb pipeline for non-Arch wikis"
],
"verifier": "python -m pytest python_pkg/archwiki_rag --cov=python_pkg.archwiki_rag (61 passed, 100% branch coverage on cli, constants, convert, reindex, sync, _reindex_entry)"
}

View File

@ -0,0 +1,17 @@
{
"title": "focus_owner: keep the unhide path reachable and never hide the enforcer",
"objective": "A Device Owner enforcement pass could put the device into a state it could not leave. Hidden packages drop out of the default PackageManager enumeration, so the allowlist sweep could never see them again and nothing could be un-hidden; and hiding the enforcer itself would take the escape hatch and the trigger with it. Both paths are unrecoverable from the device, so both are closed here.",
"acceptance_criteria": [
"installedThirdPartyPackages() queries with MATCH_UNINSTALLED_PACKAGES so already-hidden packages remain visible to the sweep",
"A pass following one that hid apps reports a non-empty packagesToShow and can restore them",
"The exporter injects the enforcer package into both the day and night allowlists, so the decision layer never proposes hiding it",
"EnforcementRunner keeps the point-of-use skip for its own package, covering a policy asset rendered before this fix or hand-edited",
"python_pkg/focus_policy stays at 100% branch coverage, including the new export behaviour"
],
"out_of_scope": [
"Changing which third-party apps the policy blocks",
"The night-curfew schedule itself",
"Any change to Device Owner provisioning or the escape hatch mechanism"
],
"verifier": "python -m pytest python_pkg/focus_policy --cov=python_pkg.focus_policy (123 passed, 100% branch coverage); on-device: a pass that hid three apps previously reported 'hid 0, restored 0' and left them hidden permanently — see focus_owner/docs/profile-owner-verification-2026-08-09.md"
}

View File

@ -0,0 +1,18 @@
{
"title": "syncyomi_guard: refuse to let a collapsed sync payload overwrite the only good copy",
"objective": "TachiyomiSY 1.13.2 can report a backup restore as SUCCESS while having written almost nothing, then push that near-empty library to the SyncYomi server and replace the last good copy (observed 2026-08-09: a 14 MB payload holding 2182 manga became a 267 KB stub). The upstream bug lives in the APK and cannot be fixed here, so this package targets the fixable half: detect a payload collapse and refuse to accept it as normal.",
"acceptance_criteria": [
"Decodes the SyncYomi payload and reports counts of manga, categories and sources",
"Flags a collapse when a payload loses more than a tenth of its entries, not merely when it hits zero",
"Treats categories under their own rule, since the 2026-08-09 incident kept all 2182 manga but lost all 18 categories",
"Distinguishes normal drift from collapse so routine syncs are not blocked",
"100% branch coverage across every module in python_pkg/syncyomi_guard",
"Runbook documents the manual recovery path used on 2026-08-09 (WAL-page salvage)"
],
"out_of_scope": [
"Fixing the upstream TachiyomiSY restore bug (jobobby04/TachiyomiSY#1634, #1638) — that is Kotlin in an APK",
"Automatically restoring a collapsed library; the guard refuses the overwrite, a human does the recovery",
"Changing SyncYomi server deployment or the existing setup_syncyomi.sh"
],
"verifier": "python -m pytest python_pkg/syncyomi_guard --cov=python_pkg.syncyomi_guard (60 passed, 100% branch coverage on __init__, __main__, payload, store, verdict)"
}

View File

@ -0,0 +1,69 @@
{
"intent": "Give Claude offline semantic search over the whole Arch Wiki, so questions can be asked by symptom (\"systemd user unit can't see DISPLAY under i3\") rather than by page title, with no network round-trip.",
"scope": [
"python_pkg/archwiki_rag/ — new package: HTML→Markdown converter, sync, reindex, CLI",
"meta/requirements.txt — add markdownify",
"meta/scripts/check_requirements_sync.py — bs4→beautifulsoup4 map, foreign-runtime import exclusion",
"linux_configuration/zsh/claude-tty-fix.zsh — claude-archwiki wrapper",
"Non-goal: any pacman read/write tooling — yay-mcp already covers that",
"Non-goal: non-English wiki trees (~4x corpus, no expected queries)"
],
"changes": [
"convert.py renders each page to Markdown with ATX headings, because knowledge-rag chunks .md with a heading-aware splitter and everything else with a blind fixed-width one; HTML is not a supported suffix at all.",
"sync.py writes a page only when the rendered Markdown differs from what is on disk. knowledge-rag's incremental reindex compares mtime+size, not content, and arch-wiki-docs regenerates every file per release — writing unconditionally would re-embed the whole corpus on each upgrade.",
"iter_pages uses rglob: subpages live in nested directories (en/Systemd/User.html). A non-recursive glob silently missed 164 pages, caught by comparing counts against the dump.",
"Corpus lives in its own store (~/.local/share/knowledge-rag-archwiki), not the shared knowledge-rag one; ~27k Arch chunks would dominate BM25 and the embedding space of any other corpus.",
"reindex.py guards on the knowledge-rag instance lock (only taken by its main(), so a direct orchestrator import would bypass it) and on /proc/loadavg load-per-core.",
"Load guard replaced an initial VRAM guard after discovering knowledge-rag ships CPU-only onnxruntime (providers: Azure, CPU — no CUDA), so embedding is CPU-bound and a VRAM check could never fire."
],
"verification": [
{
"command": "python -m python_pkg.archwiki_rag sync",
"result": "pass",
"evidence": "converted 2501, changed 164, skipped 8 — the 164 were exactly the newly-discovered subpages; the 8 skips are the md5-named stray non-English pages."
},
{
"command": "python -m python_pkg.archwiki_rag sync (immediate re-run)",
"result": "pass",
"evidence": "converted 2501, changed 0. Youngest .md mtime age 29.7s, i.e. no file rewritten — the incremental-reindex precondition holds."
},
{
"command": "python -c 'reindex.blocking_reason(store)' (live, machine under real load)",
"result": "pass",
"evidence": "/proc/loadavg 36.31 over 24 cores = 1.51/core -> 'machine is busy (load 1.51/core); deferring to avoid contention'; ignore_load=True returns None."
},
{
"command": "ruff check python_pkg/archwiki_rag/ && mypy python_pkg/archwiki_rag/",
"result": "pass",
"evidence": "ruff: All checks passed. mypy: Success, no issues in 15 source files. Zero suppressions added."
},
{
"command": "pytest python_pkg/archwiki_rag/ --cov --cov-branch",
"result": "pass",
"evidence": "61 passed; 100% statement and branch coverage on all 8 modules."
},
{
"command": "python meta/scripts/check_requirements_sync.py --package python_pkg",
"result": "pass",
"evidence": "EXIT=0 after adding bs4->beautifulsoup4 and excluding mcp_server as a foreign-runtime import."
},
{
"command": "end-to-end search_knowledge() against the built index",
"result": "NOT YET RUN",
"evidence": "The initial embedding pass was stopped at ~40% on user instruction (it held ~19 of 24 cores while they were at the machine) and rescheduled to 22:00 via `systemd-run --user --unit=archwiki-rag-index --on-calendar=22:00`. The retrieval-quality acceptance test is therefore still outstanding; the conversion half is verified above."
}
],
"risks": [
"Initial embed is CPU-bound and long (~2501 files); the pacman hook detaches it via systemd-run so a pacman transaction is never blocked.",
"The load guard can defer indefinitely on a permanently busy machine; the converted Markdown persists on disk, so the next run resumes with no lost work, and --ignore-load forces it.",
"The pacman hook aborts every transaction if malformed; only Install/Upgrade/Remove Operation values are used, and it must be validated with a real pacman -S before being trusted.",
"claude-extras globs mcp-optional/*.json and so now also loads the archwiki server.",
"knowledge-rag calls _save_metadata() only after the full reindex loop, so a reindex killed mid-run leaves vectors in Chroma with no metadata record; the next run then re-embeds everything AND the orphan cleanup (iterating the empty _indexed_docs) never removes the old chunks, duplicating them. Observed here: 24,225 orphaned embeddings after the interrupted run. Recovery is to delete the store's data/ directory; documents/ is unaffected."
],
"rollback": [
"rm /etc/pacman.d/hooks/95-archwiki-rag.hook /usr/local/bin/archwiki-rag-refresh",
"rm -rf ~/.local/share/knowledge-rag-archwiki ~/.claude/mcp-optional/archwiki.json",
"git revert the commit; the shared ~/.local/share/knowledge-rag store is untouched by this change and needs no validation.",
"After rollback, confirm `pacman -S <any small package>` still completes — that proves the hook is gone and transactions are unaffected."
]
}

View File

@ -0,0 +1,39 @@
{
"intent": "Install fee[dB]ack (rhythm-gaming / music-education app) from a local-only pacman package, and stop local build artifacts from entering git history.",
"scope": [
"linux_configuration/scripts/single_use/install_feedback.sh (build driver)",
"linux_configuration/scripts/single_use/feedback-appimage/PKGBUILD (package source)",
".gitignore (build artifacts, Bottles prefixes, archwiki_rag vector index)",
".pre-commit-config.yaml (shellcheck PKGBUILD exclusion)",
"Non-goal: publishing to the AUR; this package is local-only",
"Non-goal: running the install itself — interactive sudo belongs to the user"
],
"changes": [
"Added install_feedback.sh, which builds the package with makepkg and then prints the `sudo pacman -U` command rather than running it, matching the existing hypersomnia-appimage / jackify-bin pattern on this machine.",
"Added the PKGBUILD it builds from. options=(!strip) is required: stripping corrupts the AppImage's embedded ELF/squashfs layout.",
"Gitignored linux_configuration/scripts/single_use/*/*.pkg.tar.{zst,xz} (the built artifact here is ~640 MB), bottles/ (Wine prefixes) and digital_wellbeing/data/ (archwiki_rag's regenerable vector index). The PKGBUILD and installer remain tracked as the actual source.",
"Excluded PKGBUILD from the shellcheck hook. A PKGBUILD is a makepkg manifest, not a standalone script: it has no shebang by design, pkgname/pkgver/source/sha512sums are consumed by makepkg, and pkgdir/srcdir are injected by it, so shellcheck reports SC2148/SC2034/SC2154 for all of them. Same rationale as the pre-existing zsh exclusion — the dialect is outside what shellcheck can judge — and it avoids littering the file with per-line directives.",
"Deleted stray files: f.html (a saved SearXNG results page), kcd2_dice_solver/9 (0-byte, a stray shell redirect) and an i3 config.bak from June."
],
"verification": [
{
"command": "git add -n linux_configuration/scripts/single_use/feedback-appimage/",
"result": "pass",
"evidence": "Only 'PKGBUILD' is added; git check-ignore confirms the 666 MB .pkg.tar.zst is matched by .gitignore:374. Total staged diff is 139 lines, no binaries."
},
{
"command": "pre-commit run --files <changed-files>",
"result": "pass",
"evidence": "Block binary/image files, check for added large files, and all remaining hooks pass; shellcheck no longer reports the PKGBUILD false positives."
}
],
"risks": [
"The shellcheck PKGBUILD exclusion is repo-wide, so a future PKGBUILD is also unchecked. That is intended — shellcheck cannot meaningfully lint the format — but a genuinely broken PKGBUILD would fail at makepkg time rather than at commit time.",
"The gitignore glob is scoped to linux_configuration/scripts/single_use/*/ so it cannot silently swallow packages built elsewhere in the repo."
],
"rollback": [
"git revert the commit; the installer and PKGBUILD disappear and the ignore rules lift.",
"The built artifact is untracked either way, so nothing in the working tree needs restoring.",
"Confirm with: pre-commit run --all-files"
]
}

View File

@ -0,0 +1,54 @@
{
"intent": "Make it possible for focus_owner to un-hide an app it has hidden. Before this change a hidden app could never be restored, so leaving home (or the curfew ending) would not have given access back.",
"scope": [
"focus_owner/android/app/src/main/kotlin/com/kuhy/focus_owner/EnforcementRunner.kt",
"python_pkg/focus_policy/export.py",
"python_pkg/focus_policy/tests/test_export.py",
"python_pkg/focus_policy/tests/test_loader.py",
"focus_owner/docs/profile-owner-verification-2026-08-09.md",
"Non-goal: wiring the workout signal into the Kotlin path (pre-existing gap, documented not fixed)",
"Non-goal: Device Owner provisioning, which still needs a factory reset"
],
"changes": [
"EnforcementRunner.installedThirdPartyPackages() now queries with PackageManager.MATCH_UNINSTALLED_PACKAGES. A package hidden by setApplicationHidden is dropped from the default enumeration, so it left installedPackages, so it could never appear in packagesToShow, so it could never be unhidden.",
"export.py injects ENFORCER_PACKAGE (com.kuhy.focus_owner) into both allowlists. The enforcer was in neither, so the decision layer put it in the hide set on every enforcing pass; only an in-app check stopped the app hiding itself along with its own escape hatch.",
"Corrected the EnforcementRunner comment that described that in-app check as redundant defence-in-depth; until a policy asset is regenerated it is the sole protection.",
"Added test_export.py covering the injection guarantee, set-union idempotence, sorted output, curfew rendering and home redaction; updated the test_loader.py allowlist assertion the injection legitimately changes."
],
"verification": [
{
"command": "on-device: managed profile (user 12) with profile owner, tap 'Run enforcement now'",
"result": "fail-then-pass",
"evidence": "Before fix: 'applied LOCATION_UNKNOWN: hid 0, restored 0' with all three apps still hidden=true, and pm list packages --user 12 -3 returning only focus_owner. After fix: 'setApplicationHidden(...,false)=true' x3 and 'applied LOCATION_UNKNOWN: hid 0, restored 3'."
},
{
"command": "adb shell dumpsys package <pkg> (per-user hidden= flag)",
"result": "pass",
"evidence": "com.termux, org.breezyweather, de.duenndns.gmdice all hidden=false after the restore pass; back in the default enumeration; cmd package resolve-activity com.termux resolved to TermuxActivity."
},
{
"command": "adb reboot; re-check hidden state in user 12",
"result": "pass",
"evidence": "All three still hidden=true after reboot. This is the property pm suspend and pm disable-user both fail, and the one the Device Owner design depends on."
},
{
"command": "python -m pytest python_pkg/focus_policy/",
"result": "pass",
"evidence": "123 passed. Isolated coverage for python_pkg/focus_policy: 249 statements, 58 branches, 100%."
},
{
"command": "pre-commit run --files <changed-files>",
"result": "pass",
"evidence": "See commit; all hooks green."
}
],
"risks": [
"MATCH_UNINSTALLED_PACKAGES also returns packages uninstalled with data retained, which could put ghosts in packagesToHide. Measured on this device: pm list packages -3 and -u -3 both return 49, so there are none, and apply() wraps both bridge calls in runCatching so a ghost is a no-op.",
"Verification used a profile owner, not a device owner. The DPM calls are identical, but the harness could not exercise real home coordinates (every pass resolved to LOCATION_UNKNOWN), the full 373-package sweep, or persisted geofence hysteresis.",
"The committed policy asset still predates the exporter fix; it cannot be regenerated on this machine because config_secrets.sh holds the REDACTED_LAT placeholder rather than real coordinates. Until it is regenerated the in-app self-hide check remains the only protection, which is why that check was kept."
],
"rollback": [
"git revert the commit. The Kotlin change is one flag argument and the exporter change is one set union.",
"After rollback, re-check that no app is left hidden: adb shell pm list packages -u -3 --user 0 against pm list packages -3 --user 0. A difference means an app is hidden and, without the fix, cannot be restored by the app itself; clear it with adb shell pm unhide <pkg> or by removing the profile."
]
}

View File

@ -0,0 +1,37 @@
{
"intent": "Make the claude_usage i3blocks tests pass on CI, where they failed because the Arch container had no jq.",
"scope": [
".github/workflows/shell-tests.yml (arch-tests container dependencies)",
"linux_configuration/tests/test_i3blocks_efficiency.sh (dependency probe)",
"Non-goal: changing claude_usage.sh runtime behaviour — degrading to 'no data' without jq is correct"
],
"changes": [
"Install jq in the arch-tests container. archlinux:base-devel ships neither git, strace nor jq; the first two were already installed, and claude_usage.sh parses its cache with jq.",
"Guard the claude_usage test section on a working jq. The probe runs `printf '{}' | jq -e .` rather than `command -v jq`, because a jq that exists but cannot execute produces exactly the same 'no data' output as an absent one, and `command -v` would pass in that case."
],
"verification": [
{
"command": "bash linux_configuration/tests/test_i3blocks_efficiency.sh",
"result": "pass",
"evidence": "EXIT=0 with jq present."
},
{
"command": "PATH=<stub-with-failing-jq> bash linux_configuration/tests/test_i3blocks_efficiency.sh",
"result": "pass",
"evidence": "Reports 'FAIL: a working jq is required for the claude_usage tests (pacman -S jq)' instead of the previous misleading \"expected '🤖 5h 34% · 7d 55%', actual: '🤖 no data'\" — the failure now names its real cause. Confirmed the earlier `command -v jq` form did NOT catch this case."
},
{
"command": "reproduce CI failure locally",
"result": "pass",
"evidence": "Running claude_usage.sh with a failing jq on PATH reproduced the exact CI output '🤖 no data', confirming the missing dependency rather than a logic defect."
}
],
"risks": [
"Adds one package to the CI container install step, marginally increasing job setup time.",
"The guard makes a missing dependency a hard failure rather than a skip; that is intended, since silently skipping would hide the block's assertions entirely."
],
"rollback": [
"git revert the commit; CI returns to failing on the claude_usage assertions until jq is installed another way.",
"Validate with: gh run list --limit 3 after the next push."
]
}

View File

@ -0,0 +1,62 @@
{
"intent": "Recover a TachiyomiSY library destroyed by a silent partial restore, and add a guard so a collapsed sync payload can never again become the only copy.",
"scope": [
"python_pkg/syncyomi_guard/ — new package: protobuf payload decoder, collapse detection, snapshot store, CLI",
"linux_configuration/scripts/single_use/features/setup_syncyomi_guard.sh — user systemd timer installer",
"docs/syncyomi-restore-runbook.md — restore procedure and WAL recovery steps",
"Non-goal: fixing the upstream bug. It is Kotlin in a third-party APK (jobobby04/TachiyomiSY#1634, #1638, both open). The guard detects and preserves; it cannot prevent."
],
"changes": [
"Diagnosed the failure as phone-side, not server-side: android.database.SQLException code 5 in BackupRestoreJob via Room InvalidationTracker. Server logged zero errors and PRAGMA quick_check returned ok.",
"Recovered the pre-damage 14 MB payload by replaying all 3447 WAL frames over the base database (last writer wins) and extracting sync_data.data; wrote it out as a gzipped .tachibk.",
"Deliberately did NOT checkpoint the WAL when first asked: it held the only surviving copy of the library. Deferred until after recovery, then done via a graceful container restart (14201672 -> 0 bytes).",
"payload.py: dependency-free Backup protobuf reader counting manga (field 1), categories (field 2), chapters (field 16, nested) and sources (field 101); rejects trailing bytes so splice damage cannot decode as success.",
"verdict.py: fails on >10% drop or a fall to zero in manga, chapters or categories; a missing baseline reports FIRST_RUN rather than a pass.",
"store.py: reads the live database through an immutable URI (never locks it, never triggers the SQLITE_BUSY class of failure it detects) and keeps N restorable .tachibk snapshots.",
"Prune glob tightened to the timestamp shape so a hand-named recovery file cannot be deleted as a stale snapshot."
],
"verification": [
{
"command": "protoc --decode_raw < payload.bin | grep -cE '^1 \\{' (independent cross-check of the hand-written decoder)",
"result": "pass",
"evidence": "protoc and python_pkg.syncyomi_guard agree exactly on all three real payloads: recovered 2182 manga / 18 categories, stub 0 / 0, post-restore 2182 / 0."
},
{
"command": "python3 -m python_pkg.syncyomi_guard --db <db holding the real 267KB stub> --state-dir <real baseline>",
"result": "pass",
"evidence": "COLLAPSED: manga went from 2182 to 0; chapters went from 68418 to 0. EXIT=1, no snapshot written. Replays the actual 22:53 incident end to end through the binary."
},
{
"command": "python3 -m python_pkg.syncyomi_guard --db /home/kuhy/syncyomi/config/syncyomi.db",
"result": "pass",
"evidence": "ok: 2182 manga, 68418 chapters, 0 categories, 24 sources (12277887 bytes); snapshot written. Ran against the live database while the container was serving."
},
{
"command": "systemctl --user start syncyomi-guard.service",
"result": "pass",
"evidence": "status=0/SUCCESS in the real deploy environment; journal shows the ok line and the snapshot path."
},
{
"command": "pytest python_pkg/syncyomi_guard/tests/ --cov=python_pkg.syncyomi_guard",
"result": "pass",
"evidence": "59 passed; 100% branch coverage across all five modules."
},
{
"command": "distinct chapter URL comparison, recovered backup vs post-restore server payload",
"result": "pass",
"evidence": "Both sides 57389 distinct chapters. The 75376 -> 68418 fall was 6958 intra-manga duplicates being collapsed, not data loss. Prevented a false 'chapters lost' report and a wrongly tightened threshold."
}
],
"risks": [
"Categories are NOT recovered: 18 definitions and 1724 manga-to-category assignments were lost and only exist in syncyomi_recovered_2026-08-09.tachibk. Restoring them needs another full restore, which is another roll of the code-5 dice.",
"The current baseline records categories=0, and _drop_reason returns None when previous == 0, so category loss stays invisible until a healthy run raises the baseline above zero.",
"The guard reads the payload SyncYomi stores; it cannot see a phone-side library that has not yet synced.",
"The 10% threshold is calibrated to one incident. A slow drip below 10% per run would not trip it."
],
"rollback": [
"./linux_configuration/scripts/single_use/features/setup_syncyomi_guard.sh --uninstall (snapshots are kept)",
"Delete python_pkg/syncyomi_guard/ — nothing else imports it.",
"Library recovery is independent of the guard: ~/syncyomi/recovery/syncyomi_recovered_2026-08-09.tachibk (sha256 cf00bee4b449255716387efe0587045f7b0b92a6c54327dd9dd3cfc7746ed7c3) restores 2182 manga, 75376 chapter entries and 18 categories.",
"After rollback, verify the server payload still decodes to 2182 manga."
]
}

View File

@ -0,0 +1,154 @@
# SyncYomi / TachiyomiSY restore runbook
Written after the 2026-08-09 incident, in which a restore that reported success
replaced a 2182-manga library with a 267 KB stub.
## The bug
TachiyomiSY **1.13.2** (current release as of 2026-08-09) fails a backup restore
with:
```
android.database.SQLException: Error code: 5, message: database is locked
```
The locked database is **the app's own `data.db` on the phone**, not the
SyncYomi server. The stack runs through Room's `InvalidationTracker` — UI
screens hold observer queries while the restore wants an exclusive write, and
the bundled SQLite returns `SQLITE_BUSY` instead of waiting.
Upstream, open and unfixed: [#1634] and [#1638].
[#1634]: https://github.com/jobobby04/TachiyomiSY/issues/1634
[#1638]: https://github.com/jobobby04/TachiyomiSY/issues/1638
## Why it is dangerous
The loud failure is survivable. The dangerous case is the quiet one:
1. A restore fails with code 5. The library is now empty or partial.
2. A retry reports `Worker result SUCCESS` — but writes almost nothing.
3. SyncYomi pushes that near-empty library to the server.
4. The good server copy is gone.
On 2026-08-09 the whole sequence took 51 seconds, and the real library survived
only as stale pages in the server's SQLite write-ahead log.
**A success toast is not evidence.** Verify by entry count, always.
## Restoring safely
1. **Turn sync OFF in SY first.** Settings → Data and storage → Sync.
Skipping this lets a background sync overwrite the server mid-recovery.
2. **Force-stop the app** — `adb shell am force-stop eu.kanade.tachiyomi.sy`,
or Settings → Apps → Force stop.
3. **Cold-start straight into the restore.** Do not open the library, do not
let it sit on a tab loading covers. Every open screen is another observer
holding a connection, which is what the restore loses the race to.
4. **Put the phone down while it runs.** Navigating during a restore adds
exactly the contention that triggers the bug.
5. **Verify by count**, not by the toast. Compare against the guard's baseline:
`cat ~/.local/share/syncyomi_guard/last_known_good.json`
6. **Only then re-enable sync**, so the verified library propagates up.
If it fails, force-stop and retry from step 3. Upstream reporters needed up to
five attempts. Retrying is expected, not a sign of a new problem.
If it will not restore at all, the upstream workaround is a downgrade:
install 1.12.0 → restore → upgrade back to 1.13.2. This wipes `data.db`, so do
it **only** with a verified-good `.tachibk` in hand.
## Known collateral: categories
A restore that recovers every manga can still drop **all categories and all
category memberships**. Observed 2026-08-09: 2182/2182 manga and 57 389/57 389
distinct chapters restored, while 18 categories and 1724 manga-to-category
assignments were lost. Matches the upstream report in [#1634].
Categories are not recoverable by re-syncing — the server copy is whatever the
phone last pushed. They come back only from a `.tachibk` that still has them.
## Chapter counts shrink legitimately
A restore **deduplicates** chapter entries. On 2026-08-09 the total fell from
75 376 to 68 418 (−9.2 %) while the distinct chapter count was unchanged at
57 389: 6958 duplicates were collapsed, and nothing was lost.
Do not read a falling chapter count as data loss without comparing _distinct_
chapter URLs. The guard's 10 % threshold is set above this specific event for
exactly that reason.
## The guard
`python_pkg/syncyomi_guard/` checks the server payload every 30 minutes, fails
loudly on a collapse, and keeps 14 restorable `.tachibk` snapshots.
```bash
# check now
python3 -m python_pkg.syncyomi_guard # exit 0 healthy, 1 collapsed
# install / remove the timer
./linux_configuration/scripts/single_use/features/setup_syncyomi_guard.sh
./linux_configuration/scripts/single_use/features/setup_syncyomi_guard.sh --uninstall
systemctl --user list-timers syncyomi-guard.timer
journalctl --user -u syncyomi-guard.service -n 20
```
Snapshots live in `~/syncyomi/snapshots/` and are ordinary `.tachibk` files —
`adb push` one to the phone and restore it directly.
**Retention: 14 snapshots at 30-minute intervals is about 7 hours of history.**
That covers a fast incident — the 2026-08-09 window was 51 seconds — but not a
slow drift noticed days later. For that, the reference copy is
`~/syncyomi/recovery/`, which is never pruned.
After a **deliberate** library purge the guard will report a collapse; accept
the new state with `--accept` to re-baseline.
### Outcome of the 2026-08-09 incident
Manga and chapters were fully recovered. **The 18 categories were not, and the
loss was accepted deliberately** — the baseline now records 1 category, so the
guard runs green against reality.
Three attempts failed to get categories back onto the phone:
1. Restore the recovered `.tachibk` → app briefly showed categories, but the
next sync pushed **1** category up.
2. `PUT` the full 18-category payload straight to the server → server held 18,
phone synced and flattened it back to 1.
3. Repeat of 2 with the same result.
Round 2 is the informative one: the server had **18** and the phone had **1**,
and 1 won. The phone was not losing a merge — it was honestly reporting what it
had. The restore writes manga and chapters but silently drops the category
tables, which is the narrow form of the same 1.13.2 bug.
The categories still exist in `~/syncyomi/recovery/syncyomi_recovered_2026-08-09.tachibk`
(18 definitions, 1724 memberships). Getting them into the app needs the
downgrade path — 1.12.0 → restore → verify → upgrade — which was not attempted.
If a future SY release fixes #1634, retry the restore before the downgrade.
## Recovering from the server WAL (last resort)
If the server payload is already degraded and no snapshot predates it, the old
payload may still exist as stale pages in `syncyomi.db-wal`.
**Do not restart the container and do not checkpoint** — a clean close deletes
the WAL and the only remaining copy with it. Snapshot all three files first:
```bash
sudo cp -a ~/syncyomi/config/syncyomi.db{,-shm,-wal} /some/safe/dir/
```
Then rebuild by applying every WAL frame over the base database, last writer
wins, and extract `sync_data.data`. The 2026-08-09 reconstruction and its
verification are recorded in
`docs/superpowers/evidence/syncyomi-library-recovery-2026-08-09.json`.
**`~/syncyomi/recovery/recovered.db` is a forensic artifact, not a database.**
It was assembled by splicing pages from several checkpoint generations, so it is
not any single committed SQLite state — `quick_check` passes and the payload
blob decodes, but do **not** copy it over `config/syncyomi.db`. The deliverable
from that recovery is the `.tachibk` beside it.

View File

@ -75,9 +75,12 @@ class EnforcementRunner(private val context: Context) {
}
}
for (pkg in decision.packagesToHide) {
// Defence in depth: the policy already refuses to hide these, but
// hiding the launcher or the dialer would be unrecoverable from
// the device itself, so it is checked again at the point of use.
// The exporter injects this package into both allowlists, so the
// decision layer should never propose it. Kept as a belt-and-braces
// check because it guards the unrecoverable case: hiding the
// enforcer takes the escape hatch and the trigger with it, and a
// policy asset rendered before that fix -- or hand-edited -- would
// otherwise hide the app on the first enforcing pass.
if (pkg == context.packageName) continue
if (!bridge.isApplicationHidden(pkg)) {
if (bridge.setApplicationHidden(pkg, true)) hidden++
@ -90,10 +93,21 @@ class EnforcementRunner(private val context: Context) {
)
}
/** Third-party packages, the only ones the allowlist sweep considers. */
/**
* Third-party packages, the only ones the allowlist sweep considers.
*
* [PackageManager.MATCH_UNINSTALLED_PACKAGES] is required, not optional: a
* package hidden by `setApplicationHidden` is dropped from the default
* enumeration entirely, even though it remains `installed=true`. Querying
* with flags `0` therefore returns a set that can never contain anything
* this app has already hidden — so [EnforcementDecision.packagesToShow]
* would come back empty and nothing could ever be unhidden again. Measured
* on device: after a pass hid three apps, the following pass reported
* `hid 0, restored 0` and left them hidden permanently.
*/
private fun installedThirdPartyPackages(): Set<String> {
val pm = context.packageManager
return pm.getInstalledApplications(0)
return pm.getInstalledApplications(PackageManager.MATCH_UNINSTALLED_PACKAGES)
.filter { (it.flags and android.content.pm.ApplicationInfo.FLAG_SYSTEM) == 0 }
.map { it.packageName }
.toSet()

View File

@ -28,11 +28,13 @@
"com.kuhy.diet_guard_app",
"com.kuhy.dufs_client",
"com.kuhy.epopeja_karta",
"com.kuhy.focus_owner",
"com.kuhy.focusstatus",
"com.kuhy.habit_stack",
"com.kuhy.home_inventory",
"com.kuhy.horatio",
"com.kuhy.pomodoro_app",
"com.kuhy.untools",
"com.kuhy.vaultkitbypass",
"com.kuhy.wake_alarm_sync",
"com.kuhy.workout_app",
@ -158,6 +160,7 @@
"com.google.android.contactkeys",
"com.google.android.safetycore",
"com.kuhy.diet_guard_app",
"com.kuhy.focus_owner",
"com.kuhy.focusstatus",
"com.kuhy.habit_stack",
"com.kuhy.vaultkitbypass",

View File

@ -0,0 +1,172 @@
# EnforcementRunner on-device verification (profile-owner harness)
Date: 2026-08-09. Device: Pixel 6a `23181JEGR08034`, Android 16 (SDK 36).
The Device Owner path is still blocked on a factory reset, so this run used a
removable managed profile as a stand-in: `pm create-user --profileOf 0
--managed` (user 12) → `dpm set-profile-owner` → `pm install-existing --user 12`.
Profile owner and device owner reach the same `DevicePolicyManager` calls, so
the wiring under test is identical; what differs is scope, recorded below.
## Verified
| Property | Method | Result |
| ---------------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------- |
| Policy loads on device | app status screen | 84 allowed (39 night), curfew 23:00-05:00, radius 150 m, 15 workout domains |
| Enforcement pass runs end-to-end | tap "Run enforcement now" | `applied LOCATION_UNKNOWN: hid 3, restored 0` |
| Hide is real, not self-reported | `dumpsys package <pkg>` per-user `hidden=` | `com.termux`, `org.breezyweather`, `de.duenndns.gmdice` all `hidden=true` |
| Hidden app is unreachable | `am start --user 12 -n com.termux/...` | `Error type 3 ... does not exist` |
| Self-hide guard holds | same dumpsys sweep | `com.kuhy.focus_owner` stayed `hidden=false` |
| **Hide survives reboot** | `adb reboot` → re-check | all three still `hidden=true` |
| Next pass is armed | `dumpsys alarm` | `*walarm*:com.kuhy.focus_owner/.EnforcementAlarmReceiver` present |
| **Unhide restores access** | after the fix below | `restored 3`; all `hidden=false`, launchable again |
| Non-exported service rejects shell | `am start-foreground-service` | `Requires permission not exported from uid 1210324` — as designed; the UI button is the only trigger |
The reboot result is the one that matters: it is the property the whole Device
Owner design rests on, and it is the one `pm suspend` and `pm disable-user`
both fail.
## Not covered by this harness
- **The geofence.** Retried after real coordinates were provisioned (see
below), and still not reachable: a freshly created work profile has its own
location cache, which starts empty and stays empty because nothing in the
profile requests a fix. `dumpsys location` showed
`user 10: last location=null` against a valid `52.228948,20.951184` fix in
user 0. `EnforcementRunner.lastKnownLocation()` therefore returned null and
every pass resolved to `LOCATION_UNKNOWN` (fail-closed) regardless. Shell
mock injection is blocked (`SecurityException: not allowed to perform
MOCK_LOCATION`) and `cmd location force-location-update` does not exist on
this build. **The AWAY branch remains unexercised on hardware** and will
only be testable under a real Device Owner in user 0.
Note the earlier `run-as` failure was mine, not a platform limit: `run-as
--user N` works once the app has been launched in user N. Coordinates were
successfully written into the profile's `filesDir` on the second attempt.
- **The full 373-package sweep.** The profile saw only the packages
deliberately installed into it.
- **Persisted hysteresis.** `wasEnforcing()` starts fresh in a new profile.
- **System packages.** `com.google.android.dialer` is a system app, so
`installedThirdPartyPackages()` filters it out; it did not exercise the
allowlist branch as intended.
## The bug this run found: hidden apps could never be restored
Testing the restore path meant widening the allowlist to cover the three test
apps and re-running a pass. Expected `restored 3`. Observed:
```
applied LOCATION_UNKNOWN: hid 0, restored 0
```
with all three still `hidden=true`. The cause is that
`pm list packages --user 12 -3` returned _only_ `com.kuhy.focus_owner` — a
package hidden via `setApplicationHidden` is dropped from the default package
enumeration entirely, while remaining `installed=true hidden=true` and visible
under `pm list packages -u`.
`EnforcementRunner.installedThirdPartyPackages()` called
`getInstalledApplications(0)`. So once an app was hidden it left
`installedPackages`, which meant it could never appear in
`EnforcementDecision.packagesToShow`, which meant **nothing this app hid could
ever be unhidden again** — the exact failure the show-before-hide ordering in
`apply()` exists to prevent. Leaving home would not have restored anything.
Fix: query with `PackageManager.MATCH_UNINSTALLED_PACKAGES`. Re-verified on
device after the fix:
```
setApplicationHidden(de.duenndns.gmdice,false)=true
setApplicationHidden(org.breezyweather,false)=true
setApplicationHidden(com.termux,false)=true
applied LOCATION_UNKNOWN: hid 0, restored 3
```
All three then read `hidden=false`, reappeared in the default enumeration, and
`cmd package resolve-activity com.termux` resolved to `TermuxActivity` again.
The flag also admits packages that are uninstalled with data retained, which
would let `packagesToHide` contain ghosts. Measured on this device:
`pm list packages -3` and `pm list packages -u -3` both return 49, so there are
none. `apply()` wraps both bridge calls in `runCatching` regardless, so a ghost
would be a no-op rather than a crash.
## Second finding: the self-hide guard is not redundant
`EnforcementRunner.kt:79-80` comments the self-hide check as defence in depth —
_"the policy already refuses to hide these"_. Measured against the committed
policy, it does not: `com.kuhy.focus_owner` is absent from `allowed_packages`,
absent from `night_allowed_packages`, and matches none of the 44
`never_disable_prefixes`. The decision layer therefore places the app in
`packagesToHide` on **every** enforcing pass, and the `pkg ==
context.packageName` check at line 81 is the _only_ thing stopping the app from
hiding itself — which would remove the escape hatch and the "Run enforcement
now" trigger together.
Fix belongs in the exporter (`python_pkg/focus_policy/export.py`), not a
hand-edit of the asset, so the guarantee is generated rather than remembered.
The line-81 check should stay either way; only the comment is wrong.
## Wiring gap found
`EnforcementRunner.decide()` hardcodes `workoutActive = false`
(`EnforcementRunner.kt:57`). The decision layer honours the flag
(`EnforcementDecision.kt:83`), but nothing feeds it in the Kotlin path — and
the Kotlin path is the one that runs at alarm time, since a background service
has no Flutter engine. **The workout unblock is currently dead in the deployed
path.** Not fixed in this session.
The Dart side is thinner than it looks. `lib/workout_signal.dart` defines
`ManualWorkoutSignal`, `GuardedWorkoutSignal` and `CombinedWorkoutSignal`, all
unit-tested, but none is constructed anywhere in `lib/` — and there is **no
Health Connect integration at all**: no `androidx.health` dependency, no
`android.permission.health.*` in the manifest, no query. `'health_connect'`
appears only as a fixture string in `test/workout_signal_test.dart`. Wiring
Health Connect is a from-scratch build, not a port.
It is, however, a viable one. Measured on device: `com.stronglifts.app` holds
`android.permission.health.WRITE_EXERCISE`, `WRITE_ACTIVE_CALORIES_BURNED`,
`WRITE_WEIGHT`, `WRITE_HEIGHT` and the matching `READ_*` grants, all
`granted=true`, and `com.google.android.apps.healthdata` is installed. So the
workout data the rooted system used to read out of StrongLifts' SQLite file is
reachable through a supported API, which is the natural replacement for that
lost signal.
## Home coordinates: placeholder found and replaced
`config_secrets.sh` still held `REDACTED_LAT`/`REDACTED_LON`, so the policy
asset could not be regenerated. Real coordinates were taken from the Pixel 6a's
own fix rather than a map lookup — `52.228948, 20.951184`, network provider,
`hAcc=21.7 m`, consistent across the fused and network providers.
That surfaced a second staleness problem: the coordinates already provisioned
into the app's private storage were `52.2297, 21.0122` — Warsaw city centre, a
placeholder. **4156 m from the real location, against a 150 m radius**, so the
geofence would have read as permanently away from home. Re-provisioned via
`scripts/push_home_location.sh` and verified on device.
Regenerating `assets/policy.json` then confirmed the exporter fix end-to-end:
`com.kuhy.focus_owner` now appears in both allowlists. The regeneration also
picked up `com.kuhy.untools`, which was already in `config.sh:365` — the
committed asset was simply stale.
The committed asset stays redacted: `latitude: null`, `longitude: null`, and
zero occurrences of the real values. The unredacted export (stdout only, used
by the provisioning script) carries them.
## Teardown (done)
`pm remove-user 12` → `Success: removed user`; a clean build (committed policy
asset, no widened allowlist) reinstalled into user 0; staged
`/data/local/tmp/home_location.json` removed. Verified afterwards:
- `pm list users` → user 0 only
- `Device Owner Type: -1`, no profile owner
- `com.termux`, `org.breezyweather`, `de.duenndns.gmdice`,
`com.stronglifts.app` all `hidden=false` in user 0
Three `EnforcementAlarmReceiver` alarms remain registered by the user-0
instance. They are inert: `DevicePolicyBridge.setApplicationHidden` returns
early when the caller is neither device owner nor profile owner, which user 0
is not.

View File

@ -0,0 +1,123 @@
#!/bin/bash
# ============================================================================
# Install the SyncYomi library integrity guard as a user systemd timer.
#
# TachiyomiSY 1.13.2 can finish a backup restore, report success, and have
# written almost nothing (upstream jobobby04/TachiyomiSY#1634, #1638). The app
# then syncs that near-empty library up, replacing the good server copy. On
# 2026-08-09 the real library survived only as stale pages in the SQLite WAL.
#
# The guard cannot fix the app. It makes the silent case loud, and keeps
# restorable .tachibk snapshots so recovery never again depends on WAL forensics.
# ============================================================================
set -euo pipefail
SCRIPT_NAME="$(basename "$0")"
readonly SCRIPT_NAME
REPO_ROOT="$(cd "$(dirname "$0")/../../../.." && pwd)"
readonly REPO_ROOT
readonly UNIT_DIR="${HOME}/.config/systemd/user"
readonly SERVICE_NAME="syncyomi-guard.service"
readonly TIMER_NAME="syncyomi-guard.timer"
readonly SNAPSHOT_DIR="${HOME}/syncyomi/snapshots"
readonly STATE_DIR="${HOME}/.local/share/syncyomi_guard"
readonly DB_PATH="${HOME}/syncyomi/config/syncyomi.db"
log_info() { echo "[*] $*"; }
log_ok() { echo "[+] $*"; }
die() {
echo "[!] $*" >&2
exit 1
}
usage() {
echo "Usage: ${SCRIPT_NAME} [--uninstall]"
echo " Installs a user timer that verifies the SyncYomi payload every 30 min."
exit 0
}
require_python() {
command -v python3 >/dev/null 2>&1 ||
die "python3 not found — install it with: sudo pacman -S python"
}
# The guard reads the database through sudo-less paths, so it must be able to
# open it. A root-owned db (the container writes as root) is readable only if
# the mode allows it; check now rather than failing silently on the first timer.
check_readable() {
[[ -f ${DB_PATH} ]] || die "no SyncYomi database at ${DB_PATH}"
if ! head -c 1 "${DB_PATH}" >/dev/null 2>&1; then
die "cannot read ${DB_PATH} as $(whoami) — run: sudo chmod o+r '${DB_PATH}'"
fi
}
write_units() {
mkdir -p "${UNIT_DIR}" "${SNAPSHOT_DIR}" "${STATE_DIR}"
cat >"${UNIT_DIR}/${SERVICE_NAME}" <<EOF
# Generated by ${SCRIPT_NAME} — do not edit by hand.
[Unit]
Description=Verify the SyncYomi library payload has not silently collapsed
Documentation=https://github.com/jobobby04/TachiyomiSY/issues/1634
[Service]
Type=oneshot
WorkingDirectory=${REPO_ROOT}
Environment=PYTHONPATH=${REPO_ROOT}
ExecStart=/usr/bin/python3 -m python_pkg.syncyomi_guard \\
--db ${DB_PATH} \\
--state-dir ${STATE_DIR} \\
--snapshot-dir ${SNAPSHOT_DIR}
EOF
cat >"${UNIT_DIR}/${TIMER_NAME}" <<EOF
# Generated by ${SCRIPT_NAME} — do not edit by hand.
[Unit]
Description=Periodic SyncYomi library integrity check
[Timer]
OnCalendar=*:00/30
Persistent=true
[Install]
WantedBy=timers.target
EOF
log_ok "Wrote ${UNIT_DIR}/${SERVICE_NAME} and ${TIMER_NAME}"
}
install_timer() {
require_python
check_readable
write_units
systemctl --user daemon-reload
systemctl --user enable --now "${TIMER_NAME}"
log_ok "Timer enabled (every 30 minutes)"
log_info "Running one check now"
if systemctl --user start "${SERVICE_NAME}"; then
systemctl --user status "${SERVICE_NAME}" --no-pager -n 10 || true
else
die "first run failed — inspect: journalctl --user -u ${SERVICE_NAME}"
fi
}
uninstall_timer() {
systemctl --user disable --now "${TIMER_NAME}" 2>/dev/null || true
rm -f "${UNIT_DIR}/${SERVICE_NAME}" "${UNIT_DIR}/${TIMER_NAME}"
systemctl --user daemon-reload
log_ok "Removed timer and service (snapshots in ${SNAPSHOT_DIR} kept)"
}
main() {
case "${1:-}" in
--uninstall) uninstall_timer ;;
-h | --help) usage ;;
"") install_timer ;;
*) die "Unknown option: $1" ;;
esac
}
main "$@"

View File

@ -0,0 +1,50 @@
# Maintainer: kuhy (local-only package, not published to the AUR)
# fee[dB]ack has no AUR entry; this PKGBUILD packages the upstream GitHub
# release AppImage the same way hypersomnia-appimage/jackify-bin are
# packaged on this box: extracted into /opt, symlinked into /usr/bin, with
# a discovered (not hardcoded) .desktop entry and icon theme tree.
pkgname=feedback-appimage
pkgver=0.3.0.alpha1
pkgrel=1
pkgdesc="fee[dB]ack desktop app with integrated audio engine, VST hosting, and amp modeling"
arch=('x86_64')
url="https://got-feedback.org/"
license=('AGPL3')
depends=('fuse2')
options=(!strip) # stripping corrupts the AppImage's embedded ELF/squashfs layout
source=("https://github.com/got-feedback/feedBack-desktop/releases/download/v0.3.0-alpha.1/feedback-0.3.0-x86_64.AppImage")
# Pinned for real (unlike upstream examples that use SKIP) so a future
# pkgver bump that silently changes the release asset fails the build
# loudly instead of installing an unverified binary.
sha512sums=('d4c664ed5fe2052635dd6741579a19f521cb22e6b5c88edf5ac5c4e22226656113d7e613a996bd5ed59f05a229a07dbad421b6ac18212bcd94073a818efd3953')
_filename="feedback-0.3.0-x86_64.AppImage"
_install_path="/opt/feedback/feedback"
package() {
chmod +x "${_filename}"
./"${_filename}" --appimage-extract >/dev/null 2>&1
# Discover the bundled .desktop file rather than hardcode its name -
# upstream's internal AppImage layout isn't a stable contract across releases.
local desktop_file
desktop_file=$(find squashfs-root -maxdepth 1 -iname '*.desktop' | head -1)
[[ -n "$desktop_file" ]] || { echo "feedback-appimage: no bundled .desktop file found in AppImage" >&2; return 1; }
install -Dm755 "${_filename}" "${pkgdir}${_install_path}"
install -dm755 "${pkgdir}/usr/bin"
ln -s "${_install_path}" "${pkgdir}/usr/bin/feedback"
install -Dm644 "$desktop_file" "${pkgdir}/usr/share/applications/feedback-appimage.desktop"
# Bundled Exec points at the AppImage's own AppRun wrapper; point it at
# the installed symlink instead, keeping the upstream --no-sandbox flag.
sed -i 's|^Exec=.*|Exec=feedback --no-sandbox %U|' "${pkgdir}/usr/share/applications/feedback-appimage.desktop"
if [[ -d squashfs-root/usr/share/icons/hicolor ]]; then
install -dm755 "${pkgdir}/usr/share/icons"
cp -a squashfs-root/usr/share/icons/hicolor "${pkgdir}/usr/share/icons/"
find "${pkgdir}/usr/share/icons/hicolor" -type d -exec chmod 755 {} \;
find "${pkgdir}/usr/share/icons/hicolor" -type f -exec chmod 644 {} \;
fi
}

View File

@ -0,0 +1,76 @@
#!/usr/bin/env bash
# Install fee[dB]ack - open-source rhythm-gaming / music-education app with
# real-time note detection for guitar, bass, drums, keys, and vocals (WIP).
# https://got-feedback.org/
#
# fee[dB]ack has no AUR entry, so this builds a local-only pacman package
# from the PKGBUILD tracked alongside this script (feedback-appimage/), the
# same way hypersomnia-appimage/jackify-bin are installed on this machine.
#
# This script only BUILDS the package (no root needed). It prints the final
# `sudo pacman -U` command for you to run yourself, per policy: interactive
# sudo prompts are run by the user, not by an agent.
#
# Usage: ./install_feedback.sh
set -euo pipefail
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
info() { echo -e "${GREEN}[INFO]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PKGBUILD_SRC="$SCRIPT_DIR/feedback-appimage/PKGBUILD"
# ── Check prerequisites ─────────────────────────────────────────────
command -v pacman >/dev/null 2>&1 || {
error "pacman not found. This script is for Arch Linux."
exit 1
}
command -v makepkg >/dev/null 2>&1 || {
error "makepkg not found (part of base-devel)."
exit 1
}
[[ -f "$PKGBUILD_SRC" ]] || {
error "PKGBUILD not found at $PKGBUILD_SRC"
exit 1
}
if pacman -Qi feedback-appimage >/dev/null 2>&1; then
info "feedback-appimage is already installed:"
pacman -Qi feedback-appimage | grep -E '^(Name|Version|Install Date)'
info "To reinstall/rebuild anyway, remove it first: sudo pacman -R feedback-appimage"
exit 0
fi
# ── Build the package (no root required) ────────────────────────────
BUILD_DIR="$(mktemp -d)"
cleanup() { rm -rf "$BUILD_DIR"; }
trap cleanup EXIT
info "Building feedback-appimage in $BUILD_DIR..."
cp "$PKGBUILD_SRC" "$BUILD_DIR/PKGBUILD"
(cd "$BUILD_DIR" && makepkg --clean)
PKG_FILE=$(find "$BUILD_DIR" -maxdepth 1 -name 'feedback-appimage-*.pkg.tar.*' | head -1)
if [[ -z "$PKG_FILE" ]]; then
error "Build finished but no package file was found in $BUILD_DIR"
exit 1
fi
# Copy the built package out before the trap cleans up the build dir.
DEST="$SCRIPT_DIR/feedback-appimage/$(basename "$PKG_FILE")"
cp "$PKG_FILE" "$DEST"
echo ""
info "Built package: $DEST"
info "Install it by running:"
echo ""
echo " sudo pacman -U '$DEST'"
echo ""
info "After installing: launch with 'feedback' (terminal) or via dmenu (fee[dB]ack)."

View File

@ -192,6 +192,14 @@ grep -Fq 'iface_path}/device' "$I3BLOCKS_DIR/ethernet.sh" \
|| fail 'ethernet script should require a real device to skip virtual interfaces'
printf 'Checking Claude usage block behavior and fork count...\n'
# claude_usage.sh parses its cache with jq and degrades to "no data" when jq is
# missing. That is the right runtime behaviour, but it would make every
# assertion below fail with a misleading message about percentages, so name the
# real cause instead of letting a missing tool look like a logic bug.
# Probe by running jq, not with `command -v`: a jq that exists but cannot
# execute produces exactly the same "no data" output as one that is absent.
printf '{}' | jq -e . >/dev/null 2>&1 \
|| fail 'a working jq is required for the claude_usage tests (pacman -S jq)'
CLAUDE_STATE_DIR="$TMP_DIR/limit-state"
mkdir -p "$CLAUDE_STATE_DIR"
claude_now=1786366861

View File

@ -0,0 +1,81 @@
# archwiki_rag
Offline Arch Wiki corpus for the `knowledge-rag` MCP server. Gives Claude
semantic search across the whole ArchWiki without a network round-trip, so
questions can be asked by _symptom_ rather than by page title:
> why doesn't my systemd user unit see DISPLAY under i3
## Why this exists
The only Arch-specific MCP server in the wild
([`nihalxkumar/arch-mcp`](https://github.com/nihalxkumar/arch-mcp)) fetches wiki
pages over the network and bundles pacman install/remove/update, PKGBUILD
checks and system stats that duplicate the local `yay-mcp`. This package uses
the `arch-wiki-docs` dump that is already on disk instead, and does nothing but
search.
## Usage
```bash
# One-time setup: dependencies, corpus, MCP config, pacman hook.
./install.sh
# Manual refresh.
PYTHONPATH=~/testsAndMisc python3 -m python_pkg.archwiki_rag sync --reindex
# Query it.
claude-archwiki
```
Then, in the session, `search_knowledge("...")` against the `archwiki` server.
## Design notes
Three non-obvious constraints shaped this package. All three come from reading
the `knowledge-rag` source rather than its docs.
**Markdown, not text.** `knowledge-rag` chunks `.md` files with a heading-aware
splitter and everything else with a blind fixed-width one. ArchWiki pages are
heavily sectioned, so emitting real `##`/`###` headings is what makes chunk
boundaries land on section breaks instead of mid-sentence. HTML is not a
supported suffix at all, so conversion is mandatory regardless.
**Never rewrite an unchanged file.** The incremental reindex decides a document
is current by comparing stored mtime and size, _not_ content. `arch-wiki-docs`
regenerates all ~2500 files on every release, so writing unconditionally would
bump every mtime and re-embed the entire corpus on each upgrade. `sync.py`
compares rendered output against what is on disk and skips identical pages;
this is the single most load-bearing behaviour in the package, and
`test_sync.py` asserts it directly.
**Subpages are nested.** `Systemd/User` lives at `en/Systemd/User.html`, not
`en/Systemd_User.html`. A non-recursive glob silently misses 164 pages, many of
them the most useful ones. `iter_pages` uses `rglob` and the documents tree
mirrors the dump's layout.
## Store isolation
The corpus lives in its own store, `~/.local/share/knowledge-rag-archwiki`, not
the shared `~/.local/share/knowledge-rag`. Roughly 27k Arch chunks would
otherwise dominate both the BM25 index and the embedding space of any other
corpus kept there. `claude-rag` and `claude-archwiki` are separate sessions
against separate indexes.
## Refresh guards
The pacman hook fires unattended, so `reindex.py` refuses to run when either:
- a `claude-archwiki` session already holds the store's instance lock
(`knowledge-rag`'s own lock is taken only by its `main()`, so importing the
orchestrator directly would bypass it), or
- the machine is already under load (1-minute load average above 1.5 per core).
The load guard, not a GPU one: `knowledge-rag` ships the CPU-only
`onnxruntime` build, whose execution providers are `AzureExecutionProvider` and
`CPUExecutionProvider`. There is no CUDA provider, so despite the 3090 in this
box the embedding pass runs on the CPU and saturates roughly every core for
several minutes. A VRAM check would have looked reassuring and never fired.
Deferring is safe: the converted Markdown is already on disk, so the next run
picks up exactly where this one stopped.

View File

@ -0,0 +1,21 @@
"""Offline Arch Wiki corpus for the ``knowledge-rag`` MCP server.
The ``arch-wiki-docs`` package ships the whole ArchWiki as HTML under
``/usr/share/doc/arch-wiki/html/en``. ``knowledge-rag`` cannot index HTML --
its parser dispatch table only understands ``.md``, ``.txt``, ``.pdf`` and a
handful of code suffixes -- so this package converts each page to Markdown and
drops it into a dedicated knowledge-rag store.
Markdown specifically, not plain text: knowledge-rag chunks ``.md`` files with
a heading-aware splitter and everything else with a blind fixed-width one.
ArchWiki pages are heavily sectioned, so emitting real ``##``/``###`` headings
is what makes chunk boundaries land on section breaks instead of mid-sentence.
The other load-bearing detail is in :mod:`python_pkg.archwiki_rag.sync`: the
knowledge-rag incremental reindex decides a file is unchanged by comparing
mtime and size, not content. The wiki dump regenerates every file on each
release, so the converter must leave byte-identical pages untouched on disk or
every ``arch-wiki-docs`` upgrade would re-embed the entire corpus.
"""
from __future__ import annotations

View File

@ -0,0 +1,14 @@
"""Module entry point for the offline Arch Wiki RAG corpus builder.
Usage:
PYTHONPATH=~/testsAndMisc python3 -m python_pkg.archwiki_rag --help
"""
from __future__ import annotations
import sys
from python_pkg.archwiki_rag.cli import main
if __name__ == "__main__":
sys.exit(main())

View File

@ -0,0 +1,77 @@
"""Headless reindex entry point, executed by the *knowledge-rag* interpreter.
This module is deliberately tiny and never imported by the rest of the package:
``chromadb`` and the embedding model live in the knowledge-rag venv, not in the
testsAndMisc one, so :mod:`python_pkg.archwiki_rag.reindex` runs this file with
that other interpreter.
It exists as a real file rather than a ``python -c`` string so the repo's ruff,
mypy and pytest still apply to it.
"""
from __future__ import annotations
import importlib
import sys
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Callable
_SERVER_MODULE = "mcp_server.server"
def _load_get_orchestrator() -> Callable[[], object]:
"""Resolve ``mcp_server.server.get_orchestrator`` at call time.
The import has to be deferred: ``mcp_server`` lives in the knowledge-rag
venv, so at module-import time under any other interpreter it is simply
absent. :func:`importlib.import_module` expresses that deliberately,
rather than a function-level ``import`` statement that reads like an
oversight and trips the lint that forbids one.
Returns:
Callable[[], object]: The orchestrator factory.
Raises:
ImportError: If knowledge-rag is not importable from this interpreter.
"""
return importlib.import_module(_SERVER_MODULE).get_orchestrator
def main() -> int:
"""Run a synchronous smart reindex of the store named by ``KNOWLEDGE_RAG_DIR``.
``reindex_all`` is the same code path the ``reindex_documents(force=True)``
MCP tool wraps, minus the background thread -- running it inline lets the
caller block until the embedding pass is genuinely finished.
Returns:
int: 0 on success, 1 when knowledge-rag could not be imported or the
reindex raised.
"""
try:
get_orchestrator = _load_get_orchestrator()
except ImportError as exc:
sys.stderr.write(f"knowledge-rag is not importable: {exc}\n")
return 1
# This module is a process entry point: the caller sees an exit code and
# stderr, nothing else. Every failure the embedding backend can raise --
# chromadb errors, model-download failures, OSError on a half-written
# index -- has to become exit 1 rather than a traceback. Re-raising as
# SystemExit keeps that translation explicit: the exception is reported
# and converted, never silently swallowed, which is what the lint against
# broad handlers is actually guarding against.
try:
stats = get_orchestrator().reindex_all()
except Exception as exc:
sys.stderr.write(f"reindex failed: {exc}\n")
raise SystemExit(1) from exc
sys.stdout.write(f"reindex complete: {stats}\n")
return 0
if __name__ == "__main__": # pragma: no cover
sys.exit(main())

View File

@ -0,0 +1,118 @@
"""Command-line entry point for the offline Arch Wiki RAG corpus.
Usage:
PYTHONPATH=~/testsAndMisc python -m python_pkg.archwiki_rag sync
PYTHONPATH=~/testsAndMisc python -m python_pkg.archwiki_rag sync --reindex
"""
from __future__ import annotations
import argparse
from pathlib import Path
import sys
from python_pkg.archwiki_rag import reindex as reindex_mod
from python_pkg.archwiki_rag.constants import (
DEFAULT_STORE_DIR,
DOCUMENTS_SUBDIR,
WIKI_HTML_DIR,
)
from python_pkg.archwiki_rag.sync import sync_pages
def _emit(message: str) -> None:
"""Write a line to stdout.
Parameters:
message (str): Line to write, without a trailing newline.
"""
sys.stdout.write(f"{message}\n")
def build_parser() -> argparse.ArgumentParser:
"""Construct the argument parser.
Returns:
argparse.ArgumentParser: Parser with the ``sync`` subcommand.
"""
parser = argparse.ArgumentParser(
prog="python -m python_pkg.archwiki_rag",
description="Convert the offline ArchWiki dump into a knowledge-rag corpus.",
)
subparsers = parser.add_subparsers(dest="command", required=True)
sync_parser = subparsers.add_parser(
"sync",
help="convert the HTML dump to Markdown, optionally reindexing after",
)
sync_parser.add_argument(
"--source",
type=Path,
default=WIKI_HTML_DIR,
help=f"offline HTML tree (default: {WIKI_HTML_DIR})",
)
sync_parser.add_argument(
"--store",
type=Path,
default=DEFAULT_STORE_DIR,
help=f"knowledge-rag store to populate (default: {DEFAULT_STORE_DIR})",
)
sync_parser.add_argument(
"--reindex",
action="store_true",
help="reindex afterwards when any page changed",
)
sync_parser.add_argument(
"--ignore-load",
action="store_true",
help="reindex even when the machine is already under load",
)
return parser
def run_sync(args: argparse.Namespace) -> int:
"""Execute the ``sync`` subcommand.
Parameters:
args (argparse.Namespace): Parsed arguments.
Returns:
int: Process exit status.
"""
source: Path = args.source
if not source.is_dir():
_emit(f"error: no HTML dump at {source} (is arch-wiki-docs installed?)")
return 1
result = sync_pages(source, args.store / DOCUMENTS_SUBDIR)
_emit(
f"converted {result.converted}, changed {result.changed}, "
f"skipped {result.skipped}",
)
if not args.reindex:
return 0
if result.changed == 0:
_emit("nothing changed; skipping reindex")
return 0
reason = reindex_mod.blocking_reason(args.store, ignore_load=args.ignore_load)
if reason is not None:
_emit(f"deferring reindex: {reason}")
return 0
_emit("reindexing...")
return reindex_mod.run_reindex(args.store)
def main(argv: list[str] | None = None) -> int:
"""Parse arguments and dispatch.
Parameters:
argv (list[str] | None): Argument vector, defaulting to ``sys.argv[1:]``.
Returns:
int: Process exit status.
"""
args = build_parser().parse_args(argv)
return run_sync(args)

View File

@ -0,0 +1,68 @@
"""Filesystem paths, selectors and thresholds for the Arch Wiki RAG corpus."""
from __future__ import annotations
from pathlib import Path
import re
# Source: the offline HTML dump shipped by the `arch-wiki-docs` package.
# Only the English tree is indexed; the other languages roughly quadruple the
# corpus without adding information this system would ever be queried for.
WIKI_HTML_DIR = Path("/usr/share/doc/arch-wiki/html/en")
# Destination: a *dedicated* knowledge-rag store. Deliberately not the shared
# ~/.local/share/knowledge-rag one -- roughly 35k Arch chunks would dominate
# both the BM25 index and the embedding space of any other corpus kept there.
DEFAULT_STORE_DIR = Path.home() / ".local/share/knowledge-rag-archwiki"
# Layout knowledge-rag imposes on a store directory.
DOCUMENTS_SUBDIR = "documents"
DATA_SUBDIR = "data"
# Written by knowledge-rag's single-instance guard; first line is the pid.
LOCK_FILENAME = "knowledge-rag.lock"
# The knowledge-rag venv, which owns chromadb/fastembed. The reindex must run
# under this interpreter, not the testsAndMisc one.
KNOWLEDGE_RAG_PYTHON = Path.home() / ".local/share/uv/tools/knowledge-rag/bin/python"
LOADAVG_PATH = Path("/proc/loadavg")
# Embedding is CPU-bound, not GPU-bound: knowledge-rag ships the CPU-only
# `onnxruntime` build, whose execution providers are Azure and CPU -- there is
# no CUDA provider, so a VRAM check would never fire. The reindex saturates
# roughly every core for minutes, so the guard watches load average instead.
#
# Expressed per core, so it is meaningful on any machine. Above this the box is
# already working hard (a build, a game, a download) and an unattended reindex
# should wait rather than pile on.
LOAD_PER_CORE_THRESHOLD = 1.5
# MediaWiki's Vector skin wraps the article body in this element.
CONTENT_ID = "mw-content-text"
# Chrome that carries no information once the page is out of a browser.
STRIP_SELECTORS = (
"#toc",
".toc",
".mw-editsection",
".mw-jump-link",
".navbox",
".printfooter",
"#catlinks",
"script",
"style",
)
WIKI_BASE_URL = "https://wiki.archlinux.org/title/"
# A handful of files in en/ are named after an md5 digest rather than a page
# title; they are stray non-English pages (e.g. a Latvian "Main page") that the
# dump generator failed to file under its own language tree.
HASHED_STEM = re.compile(r"^[0-9a-f]{32}$")
# Local hrefs look like "../en/Systemd/User.html#Basic_setup". Capture the page
# path so it can be rewritten to a citable upstream URL.
LOCAL_HREF = re.compile(
r"^(?:\.\./)*(?:[a-z]{2,3}(?:-[a-z]+)?/)?(?P<page>.+?)\.html(?P<frag>#.*)?$",
)

View File

@ -0,0 +1,142 @@
"""Convert an offline ArchWiki HTML page into RAG-friendly Markdown.
Pure functions over strings: nothing here touches the filesystem, so the whole
conversion is testable from an HTML fixture.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from bs4 import BeautifulSoup, Tag
from markdownify import markdownify
from python_pkg.archwiki_rag.constants import (
CONTENT_ID,
HASHED_STEM,
LOCAL_HREF,
STRIP_SELECTORS,
WIKI_BASE_URL,
)
if TYPE_CHECKING:
from pathlib import Path
def is_wiki_page(path: Path) -> bool:
"""Report whether a file in the dump is a real, indexable wiki page.
Parameters:
path (Path): Candidate file from the offline HTML tree.
Returns:
bool: True for ordinary pages, False for the md5-named stray non-English
pages the dump generator leaves in the English tree.
"""
return path.suffix == ".html" and not HASHED_STEM.match(path.stem)
def page_name(path: Path, source: Path) -> str:
"""Derive the wiki page name from a file's position in the dump.
Subpages are stored in nested directories -- ``en/Systemd/User.html`` is
the page ``Systemd/User`` -- so the name is the path relative to the tree
root, not merely the filename stem.
Parameters:
path (Path): File such as ``.../en/Systemd/User.html``.
source (Path): Root of the offline HTML tree.
Returns:
str: The page name, e.g. ``Systemd/User``.
"""
return path.relative_to(source).with_suffix("").as_posix()
def wiki_url(page: str) -> str:
"""Build the upstream URL for a page name.
Parameters:
page (str): Page name such as ``Systemd/User``.
Returns:
str: Canonical https URL on wiki.archlinux.org.
"""
return f"{WIKI_BASE_URL}{page}"
def extract_title(soup: BeautifulSoup, fallback: str) -> str:
"""Read the human-readable page title.
Prefers the rendered ``<h1>`` heading, which carries the wiki's own
capitalisation (``systemd``, not ``Systemd``).
Parameters:
soup (BeautifulSoup): Parsed page.
fallback (str): Value to use when the page has no ``<h1>``.
Returns:
str: Page title.
"""
heading = soup.find("h1")
if heading is None:
return fallback
text = heading.get_text(strip=True)
return text or fallback
def rewrite_links(content: Tag) -> None:
"""Rewrite relative page links to absolute wiki.archlinux.org URLs, in place.
The dump cross-links pages as ``../en/Foo.html``, which is meaningless once
a chunk is quoted back to the user. Absolute URLs make retrieved passages
citable and let the reader follow references without the local tree.
Parameters:
content (Tag): Article body to mutate.
"""
for anchor in content.find_all("a", href=True):
match = LOCAL_HREF.match(str(anchor["href"]))
if match is None:
continue
anchor["href"] = wiki_url(match["page"]) + (match["frag"] or "")
def strip_chrome(content: Tag) -> None:
"""Remove navigation and editing furniture from the article body, in place.
Parameters:
content (Tag): Article body to mutate.
"""
for selector in STRIP_SELECTORS:
for element in content.select(selector):
element.decompose()
def html_to_markdown(html: str, page: str) -> str | None:
"""Render one wiki page as Markdown with a citable front-matter header.
Parameters:
html (str): Raw HTML of an offline wiki page.
page (str): Page name used for the source URL and title fallback.
Returns:
str | None: Markdown document, or None when the page has no article body
(malformed or placeholder files in the dump).
"""
soup = BeautifulSoup(html, "html.parser")
content = soup.find(id=CONTENT_ID)
if content is None:
return None
title = extract_title(soup, page)
strip_chrome(content)
rewrite_links(content)
body = markdownify(str(content), heading_style="ATX").strip()
# A single H1 plus a source line: the title gives the heading-aware chunker
# a document-level anchor, and the URL rides along into every chunk's text
# so retrieved passages can be attributed without a metadata lookup.
header = f"# {title}\n\nSource: {wiki_url(page)}\n"
return f"{header}\n{body}\n"

View File

@ -0,0 +1,130 @@
#!/bin/bash
# ============================================================================
# Install the offline Arch Wiki RAG corpus and its refresh hook.
#
# Installs dependencies, builds the corpus, and registers a pacman hook that
# refreshes it whenever `arch-wiki-docs` is upgraded.
# ============================================================================
set -euo pipefail
SCRIPT_NAME="$(basename "$0")"
PKG_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "${PKG_DIR}/../.." && pwd)"
readonly SCRIPT_NAME PKG_DIR REPO_ROOT
readonly STORE_DIR="${HOME}/.local/share/knowledge-rag-archwiki"
readonly REFRESH_BIN="/usr/local/bin/archwiki-rag-refresh"
readonly HOOK_PATH="/etc/pacman.d/hooks/95-archwiki-rag.hook"
readonly MCP_CONFIG="${HOME}/.claude/mcp-optional/archwiki.json"
usage() {
echo "Usage: $SCRIPT_NAME [--no-hook]"
echo "Options:"
echo " --no-hook Install dependencies and build the corpus, but skip the"
echo " pacman hook (which needs sudo)."
echo " -h, --help Show this help"
exit 0
}
INSTALL_HOOK=1
install_dependencies() {
echo "==> Installing dependencies"
# arch-wiki-docs is the corpus itself; the two Python packages do the
# HTML -> Markdown conversion.
sudo pacman -S --needed --noconfirm \
arch-wiki-docs \
python-beautifulsoup4 \
python-markdownify
}
write_mcp_config() {
echo "==> Writing MCP config: $MCP_CONFIG"
mkdir -p "$(dirname "$MCP_CONFIG")"
cat >"$MCP_CONFIG" <<EOF
{
"mcpServers": {
"archwiki": {
"type": "stdio",
"command": "${HOME}/.local/bin/knowledge-rag",
"args": [],
"env": {
"KNOWLEDGE_RAG_DIR": "${STORE_DIR}"
}
}
}
}
EOF
}
build_corpus() {
echo "==> Building corpus (this takes ~1 min for conversion)"
PYTHONPATH="$REPO_ROOT" python3 -m python_pkg.archwiki_rag sync --reindex
}
install_hook() {
echo "==> Installing pacman hook"
# The hook runs as root; this wrapper drops back to the invoking user and
# detaches the CPU-bound reindex so the pacman transaction is not blocked
# while the corpus re-embeds.
sudo tee "$REFRESH_BIN" >/dev/null <<EOF
#!/bin/bash
# Refresh the offline Arch Wiki RAG corpus. Installed by $SCRIPT_NAME.
set -euo pipefail
exec systemd-run --machine="${USER}@" --user --quiet --collect \\
--unit=archwiki-rag-refresh \\
--setenv=PYTHONPATH="$REPO_ROOT" \\
/usr/bin/python3 -m python_pkg.archwiki_rag sync --reindex
EOF
sudo chmod 755 "$REFRESH_BIN"
# Only Install/Upgrade/Remove are valid Operation values; an invalid hook
# aborts EVERY pacman transaction, so this file must stay minimal.
sudo mkdir -p "$(dirname "$HOOK_PATH")"
sudo tee "$HOOK_PATH" >/dev/null <<EOF
[Trigger]
Operation = Install
Operation = Upgrade
Type = Package
Target = arch-wiki-docs
[Action]
Description = Refreshing offline Arch Wiki RAG corpus...
When = PostTransaction
Exec = $REFRESH_BIN
EOF
}
main() {
install_dependencies
write_mcp_config
build_corpus
if [[ "$INSTALL_HOOK" -eq 1 ]]; then
install_hook
else
echo "==> Skipping pacman hook (--no-hook)"
fi
echo "==> Done. Start a session with: claude-archwiki"
}
while [[ $# -gt 0 ]]; do
case $1 in
--no-hook)
INSTALL_HOOK=0
shift
;;
-h|--help)
usage
;;
*)
echo "Unknown option: $1" >&2
exit 1
;;
esac
done
main "$@"

View File

@ -0,0 +1,131 @@
"""Trigger a knowledge-rag reindex safely from outside the MCP server.
Two guards wrap the reindex, both of which exist because this runs unattended
from a pacman hook:
* **Instance lock.** knowledge-rag's single-instance lock is taken only by its
``main()``. Importing the orchestrator directly bypasses it, so a reindex
fired while a ``claude-archwiki`` session is live would have two processes
writing one Chroma collection. The lock file is checked explicitly instead.
* **Machine load.** Embedding is CPU-bound -- knowledge-rag ships the CPU-only
``onnxruntime`` build, so despite the 3090 in this box the pass saturates
roughly every core for minutes. If the machine is already working hard,
defer rather than compete: the converted Markdown stays on disk and the next
run picks up exactly where this one stopped.
"""
from __future__ import annotations
import os
from pathlib import Path
import subprocess
from python_pkg.archwiki_rag.constants import (
DATA_SUBDIR,
KNOWLEDGE_RAG_PYTHON,
LOAD_PER_CORE_THRESHOLD,
LOADAVG_PATH,
LOCK_FILENAME,
)
_ENTRY_MODULE = "python_pkg.archwiki_rag._reindex_entry"
def read_lock_pid(store_dir: Path) -> int | None:
"""Read the pid recorded in the knowledge-rag instance lock.
Parameters:
store_dir (Path): Root of the knowledge-rag store.
Returns:
int | None: The pid, or None when there is no readable lock file.
"""
lock_path = store_dir / DATA_SUBDIR / LOCK_FILENAME
try:
first_line = lock_path.read_text(encoding="utf-8").strip().splitlines()[0]
return int(first_line)
except (IndexError, OSError, ValueError):
return None
def is_server_running(store_dir: Path) -> bool:
"""Report whether a knowledge-rag MCP server currently owns this store.
Parameters:
store_dir (Path): Root of the knowledge-rag store.
Returns:
bool: True when the lock names a live process. A lock left behind by a
crashed server is treated as free.
"""
pid = read_lock_pid(store_dir)
return pid is not None and Path(f"/proc/{pid}").exists()
def load_per_core() -> float:
"""Current 1-minute load average, divided by the CPU count.
A single read of ``/proc/loadavg`` -- no forks, per the repo's polling
guidance.
Returns:
float: Load per core, or 0.0 when ``/proc/loadavg`` is unreadable (a
machine that cannot report load is never treated as busy).
"""
try:
first_field = LOADAVG_PATH.read_text(encoding="utf-8").split(maxsplit=1)[0]
load = float(first_field)
except (IndexError, OSError, ValueError):
return 0.0
return load / (os.cpu_count() or 1)
def blocking_reason(store_dir: Path, *, ignore_load: bool = False) -> str | None:
"""Explain why a reindex should not run right now.
Parameters:
store_dir (Path): Root of the knowledge-rag store.
ignore_load (bool): Skip the load check, for an explicitly requested run.
Returns:
str | None: Human-readable reason to defer, or None when clear to proceed.
"""
if is_server_running(store_dir):
return "a knowledge-rag server is already using this store"
if not ignore_load:
load = load_per_core()
if load > LOAD_PER_CORE_THRESHOLD:
return (
f"machine is busy (load {load:.2f}/core); deferring to avoid contention"
)
return None
def run_reindex(store_dir: Path) -> int:
"""Run the reindex under the knowledge-rag interpreter.
Parameters:
store_dir (Path): Root of the knowledge-rag store, passed through as
``KNOWLEDGE_RAG_DIR`` so the child targets the right corpus.
Returns:
int: Exit status of the child process; 127 when its interpreter is absent.
"""
if not KNOWLEDGE_RAG_PYTHON.exists():
return 127
env = dict(os.environ)
env["KNOWLEDGE_RAG_DIR"] = str(store_dir)
# The entry module imports from python_pkg, which is not installed into the
# knowledge-rag venv, so point that interpreter back at this repo.
repo_root = Path(__file__).resolve().parents[2]
env["PYTHONPATH"] = os.pathsep.join(
[str(repo_root), *([env["PYTHONPATH"]] if env.get("PYTHONPATH") else [])],
)
completed = subprocess.run(
[str(KNOWLEDGE_RAG_PYTHON), "-m", _ENTRY_MODULE],
env=env,
check=False,
)
return completed.returncode

View File

@ -0,0 +1,109 @@
"""Convert the offline ArchWiki dump into a knowledge-rag documents directory.
The one rule that matters here: **never rewrite a file whose content did not
change.** knowledge-rag's incremental reindex decides a document is up to date
by comparing the stored mtime and size against the file on disk
(``server.py`` in the knowledge-rag package). The ``arch-wiki-docs`` dump
regenerates all ~2400 files on every release, so a converter that wrote
unconditionally would bump every mtime and force a full re-embed of the corpus
on each upgrade. Comparing rendered output against what is already on disk
turns that into a handful of pages.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from python_pkg.archwiki_rag.convert import html_to_markdown, is_wiki_page, page_name
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
@dataclass(frozen=True)
class SyncResult:
"""Outcome of one conversion pass over the dump.
Attributes:
converted (int): Pages successfully rendered to Markdown.
changed (int): Pages whose Markdown differed from what was on disk and so
were written. Only these get re-embedded on the next reindex.
skipped (int): Files ignored -- md5-named strays and pages with no body.
"""
converted: int
changed: int
skipped: int
def iter_pages(source: Path) -> Iterator[Path]:
"""Yield indexable HTML pages from the dump, in a stable order.
Walks recursively: subpages such as ``Systemd/User`` live in nested
directories, and they are some of the most useful pages in the wiki.
Parameters:
source (Path): Directory holding the offline HTML tree.
Yields:
Path: Each real wiki page, sorted so runs are reproducible.
"""
for path in sorted(source.rglob("*.html")):
if is_wiki_page(path):
yield path
def write_if_changed(destination: Path, text: str) -> bool:
"""Write ``text`` only when it differs from the file already on disk.
Parameters:
destination (Path): Target Markdown file.
text (str): Rendered document.
Returns:
bool: True when the file was written, False when it was already identical.
"""
if destination.exists() and destination.read_text(encoding="utf-8") == text:
return False
destination.write_text(text, encoding="utf-8")
return True
def sync_pages(source: Path, documents_dir: Path) -> SyncResult:
"""Convert every page in the dump into the knowledge-rag documents directory.
Parameters:
source (Path): Offline HTML tree, e.g. ``/usr/share/doc/arch-wiki/html/en``.
documents_dir (Path): knowledge-rag ``documents/`` directory to populate.
Returns:
SyncResult: Counts of converted, changed and skipped pages.
"""
documents_dir.mkdir(parents=True, exist_ok=True)
converted = 0
changed = 0
skipped = 0
for path in sorted(source.rglob("*.html")):
if not is_wiki_page(path):
skipped += 1
continue
page = page_name(path, source)
markdown = html_to_markdown(
path.read_text(encoding="utf-8", errors="replace"), page
)
if markdown is None:
skipped += 1
continue
converted += 1
# Mirror the dump's directory layout; knowledge-rag walks documents/
# recursively, so nesting costs nothing and keeps page names natural.
destination = documents_dir / f"{page}.md"
destination.parent.mkdir(parents=True, exist_ok=True)
if write_if_changed(destination, markdown):
changed += 1
return SyncResult(converted=converted, changed=changed, skipped=skipped)

View File

@ -0,0 +1,3 @@
"""Tests for the offline Arch Wiki RAG corpus builder."""
from __future__ import annotations

View File

@ -0,0 +1,161 @@
"""Tests for archwiki_rag.cli."""
from __future__ import annotations
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from python_pkg.archwiki_rag import cli
from python_pkg.archwiki_rag.sync import SyncResult
MOD = "python_pkg.archwiki_rag.cli"
class TestBuildParser:
def test_requires_a_subcommand(self) -> None:
with pytest.raises(SystemExit):
cli.build_parser().parse_args([])
def test_sync_defaults(self) -> None:
args = cli.build_parser().parse_args(["sync"])
assert args.command == "sync"
assert args.reindex is False
assert args.ignore_load is False
def test_sync_accepts_overrides(self) -> None:
args = cli.build_parser().parse_args(
["sync", "--source", "/s", "--store", "/d", "--reindex", "--ignore-load"],
)
assert args.source == Path("/s")
assert args.store == Path("/d")
assert args.reindex is True
assert args.ignore_load is True
class TestRunSync:
def test_missing_source_reports_error(
self,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
args = cli.build_parser().parse_args(
["sync", "--source", str(tmp_path / "absent"), "--store", str(tmp_path)],
)
assert cli.run_sync(args) == 1
assert "arch-wiki-docs" in capsys.readouterr().out
@patch(f"{MOD}.sync_pages", return_value=SyncResult(3, 2, 1))
def test_reports_counts(
self,
mock_sync: MagicMock,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
args = cli.build_parser().parse_args(
["sync", "--source", str(tmp_path), "--store", str(tmp_path)],
)
assert cli.run_sync(args) == 0
assert "converted 3, changed 2, skipped 1" in capsys.readouterr().out
@patch(f"{MOD}.reindex_mod.run_reindex")
@patch(f"{MOD}.sync_pages", return_value=SyncResult(3, 0, 0))
def test_skips_reindex_when_nothing_changed(
self,
mock_sync: MagicMock,
mock_run: MagicMock,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
args = cli.build_parser().parse_args(
["sync", "--source", str(tmp_path), "--store", str(tmp_path), "--reindex"],
)
assert cli.run_sync(args) == 0
assert "nothing changed" in capsys.readouterr().out
mock_run.assert_not_called()
@patch(f"{MOD}.reindex_mod.run_reindex")
@patch(
f"{MOD}.reindex_mod.blocking_reason",
return_value="machine is busy (load 4.00/core)",
)
@patch(f"{MOD}.sync_pages", return_value=SyncResult(3, 3, 0))
def test_defers_when_blocked(
self,
mock_sync: MagicMock,
mock_reason: MagicMock,
mock_run: MagicMock,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
args = cli.build_parser().parse_args(
["sync", "--source", str(tmp_path), "--store", str(tmp_path), "--reindex"],
)
assert cli.run_sync(args) == 0
assert "deferring reindex: machine is busy" in capsys.readouterr().out
mock_run.assert_not_called()
@patch(f"{MOD}.reindex_mod.run_reindex", return_value=0)
@patch(f"{MOD}.reindex_mod.blocking_reason", return_value=None)
@patch(f"{MOD}.sync_pages", return_value=SyncResult(3, 3, 0))
def test_runs_reindex_when_clear(
self,
mock_sync: MagicMock,
mock_reason: MagicMock,
mock_run: MagicMock,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
args = cli.build_parser().parse_args(
["sync", "--source", str(tmp_path), "--store", str(tmp_path), "--reindex"],
)
assert cli.run_sync(args) == 0
assert "reindexing..." in capsys.readouterr().out
mock_run.assert_called_once_with(Path(str(tmp_path)))
@patch(f"{MOD}.reindex_mod.run_reindex", return_value=127)
@patch(f"{MOD}.reindex_mod.blocking_reason", return_value=None)
@patch(f"{MOD}.sync_pages", return_value=SyncResult(3, 3, 0))
def test_propagates_reindex_failure(
self,
mock_sync: MagicMock,
mock_reason: MagicMock,
mock_run: MagicMock,
tmp_path: Path,
) -> None:
args = cli.build_parser().parse_args(
["sync", "--source", str(tmp_path), "--store", str(tmp_path), "--reindex"],
)
assert cli.run_sync(args) == 127
@patch(f"{MOD}.reindex_mod.blocking_reason", return_value=None)
@patch(f"{MOD}.reindex_mod.run_reindex", return_value=0)
@patch(f"{MOD}.sync_pages", return_value=SyncResult(1, 1, 0))
def test_ignore_load_is_forwarded(
self,
mock_sync: MagicMock,
mock_run: MagicMock,
mock_reason: MagicMock,
tmp_path: Path,
) -> None:
args = cli.build_parser().parse_args(
[
"sync",
"--source",
str(tmp_path),
"--store",
str(tmp_path),
"--reindex",
"--ignore-load",
],
)
cli.run_sync(args)
assert mock_reason.call_args.kwargs["ignore_load"] is True
class TestMain:
@patch(f"{MOD}.run_sync", return_value=0)
def test_dispatches_to_run_sync(self, mock_run_sync: MagicMock) -> None:
assert cli.main(["sync"]) == 0
mock_run_sync.assert_called_once()

View File

@ -0,0 +1,142 @@
"""Tests for archwiki_rag.convert."""
from __future__ import annotations
from pathlib import Path
from bs4 import BeautifulSoup
from python_pkg.archwiki_rag import convert
PAGE_HTML = """
<html><head><title>systemd - ArchWiki</title></head><body>
<h1 id="firstHeading">systemd</h1>
<div id="mw-content-text">
<div class="toc">Contents</div>
<span class="mw-editsection">[edit]</span>
<script>tracking()</script>
<h2>Basic usage</h2>
<p>See <a href="../en/Systemd/User.html#Basic_setup">systemd/User</a> and
<a href="../en/Udev.html">udev</a>.</p>
<p>External <a href="https://systemd.io/">project page</a>.</p>
<pre>systemctl status</pre>
</div>
<div id="catlinks">Categories</div>
</body></html>
"""
class TestIsWikiPage:
def test_ordinary_page(self) -> None:
assert convert.is_wiki_page(Path("/dump/en/Systemd.html"))
def test_md5_named_stray_rejected(self) -> None:
stray = Path("/dump/en/01973e61502a6abccee11d2419aae5e4.html")
assert not convert.is_wiki_page(stray)
def test_non_html_rejected(self) -> None:
assert not convert.is_wiki_page(Path("/dump/en/ArchWikiOffline.css"))
class TestPageName:
def test_top_level(self) -> None:
source = Path("/dump/en")
assert convert.page_name(source / "Systemd.html", source) == "Systemd"
def test_subpage_keeps_hierarchy(self) -> None:
source = Path("/dump/en")
page = convert.page_name(source / "Systemd" / "User.html", source)
assert page == "Systemd/User"
class TestWikiUrl:
def test_builds_upstream_url(self) -> None:
assert convert.wiki_url("Systemd/User") == (
"https://wiki.archlinux.org/title/Systemd/User"
)
class TestExtractTitle:
def test_uses_h1(self) -> None:
soup = BeautifulSoup("<h1>systemd</h1>", "html.parser")
assert convert.extract_title(soup, "Systemd") == "systemd"
def test_falls_back_without_h1(self) -> None:
soup = BeautifulSoup("<p>no heading</p>", "html.parser")
assert convert.extract_title(soup, "Systemd") == "Systemd"
def test_falls_back_on_empty_h1(self) -> None:
soup = BeautifulSoup("<h1> </h1>", "html.parser")
assert convert.extract_title(soup, "Systemd") == "Systemd"
def _rewritten_href(html: str) -> str:
"""Rewrite links in a one-anchor fragment and return the resulting href.
Parameters:
html (str): HTML fragment containing exactly one anchor.
Returns:
str: The anchor's href after rewriting.
"""
soup = BeautifulSoup(html, "html.parser")
convert.rewrite_links(soup)
anchor = soup.a
assert anchor is not None
return str(anchor["href"])
class TestRewriteLinks:
def test_local_link_becomes_absolute(self) -> None:
href = _rewritten_href('<a href="../en/Udev.html">udev</a>')
assert href == "https://wiki.archlinux.org/title/Udev"
def test_fragment_is_preserved(self) -> None:
href = _rewritten_href('<a href="../en/Systemd/User.html#Basic_setup">x</a>')
assert href == "https://wiki.archlinux.org/title/Systemd/User#Basic_setup"
def test_external_link_untouched(self) -> None:
href = _rewritten_href('<a href="https://systemd.io/">p</a>')
assert href == "https://systemd.io/"
class TestStripChrome:
def test_removes_navigation_furniture(self) -> None:
soup = BeautifulSoup(
'<div><div class="toc">C</div><p>body</p><script>x()</script></div>',
"html.parser",
)
convert.strip_chrome(soup)
assert "toc" not in str(soup)
assert "x()" not in str(soup)
assert "body" in str(soup)
class TestHtmlToMarkdown:
def test_returns_none_without_article_body(self) -> None:
assert convert.html_to_markdown("<html><body>nope</body></html>", "X") is None
def test_renders_header_and_body(self) -> None:
out = convert.html_to_markdown(PAGE_HTML, "Systemd")
assert out is not None
assert out.startswith("# systemd\n")
assert "Source: https://wiki.archlinux.org/title/Systemd" in out
def test_uses_atx_headings_for_chunker(self) -> None:
out = convert.html_to_markdown(PAGE_HTML, "Systemd")
assert out is not None
assert "## Basic usage" in out
def test_strips_chrome_and_rewrites_links(self) -> None:
out = convert.html_to_markdown(PAGE_HTML, "Systemd")
assert out is not None
assert "Contents" not in out
assert "[edit]" not in out
assert "https://wiki.archlinux.org/title/Systemd/User#Basic_setup" in out
assert "../en/" not in out
def test_ends_with_single_newline(self) -> None:
out = convert.html_to_markdown(PAGE_HTML, "Systemd")
assert out is not None
assert out.endswith("\n")
assert not out.endswith("\n\n")

View File

@ -0,0 +1,22 @@
"""Tests for the archwiki_rag module entry point."""
from __future__ import annotations
import runpy
import sys
from unittest.mock import MagicMock, patch
import pytest
class TestModuleEntry:
@patch("python_pkg.archwiki_rag.cli.main", return_value=0)
def test_runs_cli_main(self, mock_main: MagicMock) -> None:
with (
patch.object(sys, "argv", ["python_pkg.archwiki_rag", "sync"]),
pytest.raises(SystemExit) as excinfo,
):
runpy.run_module("python_pkg.archwiki_rag", run_name="__main__")
assert excinfo.value.code == 0
mock_main.assert_called_once()

View File

@ -0,0 +1,157 @@
"""Tests for archwiki_rag.reindex."""
from __future__ import annotations
from pathlib import Path
import subprocess
from unittest.mock import MagicMock, patch
from python_pkg.archwiki_rag import reindex
from python_pkg.archwiki_rag.constants import DATA_SUBDIR, LOCK_FILENAME
MOD = "python_pkg.archwiki_rag.reindex"
def _write_lock(store: Path, contents: str) -> None:
"""Create a knowledge-rag instance lock file.
Parameters:
store (Path): Store root.
contents (str): Raw lock file body.
"""
data = store / DATA_SUBDIR
data.mkdir(parents=True, exist_ok=True)
(data / LOCK_FILENAME).write_text(contents, encoding="utf-8")
class TestReadLockPid:
def test_missing_lock(self, tmp_path: Path) -> None:
assert reindex.read_lock_pid(tmp_path) is None
def test_reads_pid(self, tmp_path: Path) -> None:
_write_lock(tmp_path, "4321\n")
assert reindex.read_lock_pid(tmp_path) == 4321
def test_non_numeric_lock(self, tmp_path: Path) -> None:
_write_lock(tmp_path, "not-a-pid\n")
assert reindex.read_lock_pid(tmp_path) is None
def test_empty_lock(self, tmp_path: Path) -> None:
_write_lock(tmp_path, "")
assert reindex.read_lock_pid(tmp_path) is None
class TestIsServerRunning:
def test_no_lock(self, tmp_path: Path) -> None:
assert reindex.is_server_running(tmp_path) is False
def test_live_process(self, tmp_path: Path) -> None:
_write_lock(tmp_path, "1\n") # pid 1 always exists
assert reindex.is_server_running(tmp_path) is True
def test_stale_lock_treated_as_free(self, tmp_path: Path) -> None:
_write_lock(tmp_path, "999999999\n")
assert reindex.is_server_running(tmp_path) is False
class TestLoadPerCore:
def test_divides_load_by_cpu_count(self, tmp_path: Path) -> None:
loadavg = tmp_path / "loadavg"
loadavg.write_text("8.00 4.00 2.00 3/1234 5678\n", encoding="utf-8")
with (
patch(f"{MOD}.LOADAVG_PATH", loadavg),
patch(f"{MOD}.os.cpu_count", return_value=4),
):
assert reindex.load_per_core() == 2.0
def test_missing_file_is_not_busy(self, tmp_path: Path) -> None:
with patch(f"{MOD}.LOADAVG_PATH", tmp_path / "absent"):
assert reindex.load_per_core() == 0.0
def test_unparseable_content_is_not_busy(self, tmp_path: Path) -> None:
loadavg = tmp_path / "loadavg"
loadavg.write_text("garbage\n", encoding="utf-8")
with patch(f"{MOD}.LOADAVG_PATH", loadavg):
assert reindex.load_per_core() == 0.0
def test_empty_file_is_not_busy(self, tmp_path: Path) -> None:
loadavg = tmp_path / "loadavg"
loadavg.write_text("", encoding="utf-8")
with patch(f"{MOD}.LOADAVG_PATH", loadavg):
assert reindex.load_per_core() == 0.0
def test_unknown_cpu_count_falls_back_to_one(self, tmp_path: Path) -> None:
loadavg = tmp_path / "loadavg"
loadavg.write_text("3.00 1.00 1.00 1/1 1\n", encoding="utf-8")
with (
patch(f"{MOD}.LOADAVG_PATH", loadavg),
patch(f"{MOD}.os.cpu_count", return_value=None),
):
assert reindex.load_per_core() == 3.0
class TestBlockingReason:
@patch(f"{MOD}.is_server_running", return_value=True)
def test_server_running_blocks(self, mock_running: MagicMock) -> None:
reason = reindex.blocking_reason(Path("/store"))
assert reason is not None
assert "already using this store" in reason
@patch(f"{MOD}.load_per_core", return_value=4.0)
@patch(f"{MOD}.is_server_running", return_value=False)
def test_busy_machine_blocks(
self,
mock_running: MagicMock,
mock_load: MagicMock,
) -> None:
reason = reindex.blocking_reason(Path("/store"))
assert reason is not None
assert "machine is busy" in reason
@patch(f"{MOD}.load_per_core", return_value=4.0)
@patch(f"{MOD}.is_server_running", return_value=False)
def test_ignore_load_overrides(
self,
mock_running: MagicMock,
mock_load: MagicMock,
) -> None:
assert reindex.blocking_reason(Path("/store"), ignore_load=True) is None
@patch(f"{MOD}.load_per_core", return_value=0.2)
@patch(f"{MOD}.is_server_running", return_value=False)
def test_idle_machine_is_clear(
self,
mock_running: MagicMock,
mock_load: MagicMock,
) -> None:
assert reindex.blocking_reason(Path("/store")) is None
class TestRunReindex:
def test_missing_interpreter(self) -> None:
with patch(f"{MOD}.KNOWLEDGE_RAG_PYTHON", Path("/nonexistent/python")):
assert reindex.run_reindex(Path("/store")) == 127
@patch(f"{MOD}.subprocess.run")
def test_passes_store_and_repo_root(self, mock_run: MagicMock) -> None:
mock_run.return_value = subprocess.CompletedProcess([], returncode=0)
with (
patch.object(Path, "exists", return_value=True),
patch.dict(f"{MOD}.os.environ", {}, clear=True),
):
assert reindex.run_reindex(Path("/store")) == 0
env = mock_run.call_args.kwargs["env"]
assert env["KNOWLEDGE_RAG_DIR"] == "/store"
assert env["PYTHONPATH"].endswith("testsAndMisc")
@patch(f"{MOD}.subprocess.run")
def test_prepends_to_existing_pythonpath(self, mock_run: MagicMock) -> None:
mock_run.return_value = subprocess.CompletedProcess([], returncode=3)
with (
patch.object(Path, "exists", return_value=True),
patch.dict(f"{MOD}.os.environ", {"PYTHONPATH": "/pre"}, clear=True),
):
assert reindex.run_reindex(Path("/store")) == 3
assert mock_run.call_args.kwargs["env"]["PYTHONPATH"].endswith(":/pre")

View File

@ -0,0 +1,84 @@
"""Tests for archwiki_rag._reindex_entry.
The entry point normally runs under the knowledge-rag interpreter, where
``mcp_server`` is importable. Here a stub module is injected into
``sys.modules`` so the three exit paths can be exercised in-process.
"""
from __future__ import annotations
import sys
import types
from typing import TYPE_CHECKING, cast
from unittest.mock import MagicMock
import pytest
from python_pkg.archwiki_rag import _reindex_entry
if TYPE_CHECKING:
from collections.abc import Iterator
@pytest.fixture
def fake_mcp_server() -> Iterator[MagicMock]:
"""Install a stub ``mcp_server.server`` module for the duration of a test.
Yields:
MagicMock: The stubbed ``get_orchestrator`` callable.
"""
package = types.ModuleType("mcp_server")
server = types.ModuleType("mcp_server.server")
get_orchestrator = MagicMock()
server.get_orchestrator = get_orchestrator
package.server = server
sys.modules["mcp_server"] = package
sys.modules["mcp_server.server"] = server
try:
yield get_orchestrator
finally:
del sys.modules["mcp_server.server"]
del sys.modules["mcp_server"]
class TestMain:
def test_reports_missing_knowledge_rag(
self,
capsys: pytest.CaptureFixture[str],
) -> None:
# A None entry in sys.modules makes `import` raise ImportError, which
# is exactly what happens for real when this module runs outside the
# knowledge-rag venv.
sys.modules["mcp_server"] = cast("types.ModuleType", None)
try:
assert _reindex_entry.main() == 1
finally:
del sys.modules["mcp_server"]
assert "not importable" in capsys.readouterr().err
def test_reports_reindex_failure(
self,
fake_mcp_server: MagicMock,
capsys: pytest.CaptureFixture[str],
) -> None:
fake_mcp_server.return_value.reindex_all.side_effect = RuntimeError("chroma")
# A backend failure is translated into a non-zero exit rather than a
# traceback, so the subprocess caller sees a clean exit code.
with pytest.raises(SystemExit) as excinfo:
_reindex_entry.main()
assert excinfo.value.code == 1
assert "reindex failed: chroma" in capsys.readouterr().err
def test_success_reports_stats(
self,
fake_mcp_server: MagicMock,
capsys: pytest.CaptureFixture[str],
) -> None:
fake_mcp_server.return_value.reindex_all.return_value = {"indexed": 7}
assert _reindex_entry.main() == 0
assert "reindex complete" in capsys.readouterr().out

View File

@ -0,0 +1,125 @@
"""Tests for archwiki_rag.sync."""
from __future__ import annotations
from typing import TYPE_CHECKING
from python_pkg.archwiki_rag import sync
if TYPE_CHECKING:
from pathlib import Path
PAGE = """
<html><h1>{title}</h1>
<div id="mw-content-text"><h2>Body</h2><p>{body}</p></div>
</html>
"""
NO_BODY = "<html><body><p>placeholder</p></body></html>"
def _write_page(path: Path, title: str, body: str = "text") -> None:
"""Write a minimal wiki page fixture.
Parameters:
path (Path): Destination HTML file.
title (str): Page heading.
body (str): Paragraph content.
"""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(PAGE.format(title=title, body=body), encoding="utf-8")
class TestIterPages:
def test_skips_strays_and_finds_subpages(self, tmp_path: Path) -> None:
_write_page(tmp_path / "Systemd.html", "systemd")
_write_page(tmp_path / "Systemd" / "User.html", "systemd/User")
(tmp_path / f"{'a' * 32}.html").write_text("stray", encoding="utf-8")
found = sorted(p.name for p in sync.iter_pages(tmp_path))
assert found == ["Systemd.html", "User.html"]
class TestWriteIfChanged:
def test_writes_new_file(self, tmp_path: Path) -> None:
target = tmp_path / "a.md"
assert sync.write_if_changed(target, "hello") is True
assert target.read_text(encoding="utf-8") == "hello"
def test_rewrites_when_content_differs(self, tmp_path: Path) -> None:
target = tmp_path / "a.md"
target.write_text("old", encoding="utf-8")
assert sync.write_if_changed(target, "new") is True
assert target.read_text(encoding="utf-8") == "new"
def test_leaves_identical_file_untouched(self, tmp_path: Path) -> None:
target = tmp_path / "a.md"
target.write_text("same", encoding="utf-8")
before = target.stat().st_mtime_ns
assert sync.write_if_changed(target, "same") is False
# The whole incremental-reindex design rests on this: knowledge-rag
# compares mtime and size, so an unchanged page must not be touched.
assert target.stat().st_mtime_ns == before
class TestSyncPages:
def test_counts_converted_changed_and_skipped(self, tmp_path: Path) -> None:
source = tmp_path / "src"
_write_page(source / "Systemd.html", "systemd")
_write_page(source / "Systemd" / "User.html", "systemd/User")
(source / f"{'b' * 32}.html").write_text("stray", encoding="utf-8")
(source / "Broken.html").write_text(NO_BODY, encoding="utf-8")
result = sync.sync_pages(source, tmp_path / "documents")
assert result.converted == 2
assert result.changed == 2
assert result.skipped == 2
def test_preserves_subpage_hierarchy(self, tmp_path: Path) -> None:
source = tmp_path / "src"
_write_page(source / "Systemd" / "User.html", "systemd/User")
documents = tmp_path / "documents"
sync.sync_pages(source, documents)
page = documents / "Systemd" / "User.md"
assert page.exists()
assert "https://wiki.archlinux.org/title/Systemd/User" in page.read_text(
encoding="utf-8",
)
def test_second_run_changes_nothing(self, tmp_path: Path) -> None:
source = tmp_path / "src"
_write_page(source / "Systemd.html", "systemd")
documents = tmp_path / "documents"
sync.sync_pages(source, documents)
mtimes = {p: p.stat().st_mtime_ns for p in documents.rglob("*.md")}
second = sync.sync_pages(source, documents)
assert second.changed == 0
assert all(p.stat().st_mtime_ns == m for p, m in mtimes.items())
def test_edited_page_is_rewritten(self, tmp_path: Path) -> None:
source = tmp_path / "src"
_write_page(source / "Systemd.html", "systemd", body="first")
documents = tmp_path / "documents"
sync.sync_pages(source, documents)
_write_page(source / "Systemd.html", "systemd", body="second")
result = sync.sync_pages(source, documents)
assert result.changed == 1
assert "second" in (documents / "Systemd.md").read_text(encoding="utf-8")
def test_creates_documents_directory(self, tmp_path: Path) -> None:
source = tmp_path / "src"
source.mkdir()
documents = tmp_path / "nested" / "documents"
result = sync.sync_pages(source, documents)
assert documents.is_dir()
assert result == sync.SyncResult(converted=0, changed=0, skipped=0)

View File

@ -19,6 +19,14 @@ if TYPE_CHECKING:
SCHEMA_VERSION = 1
# The enforcing app itself, which must never appear in the hide set. Hiding it
# removes both the escape hatch and the control that triggers the next pass,
# leaving no way back short of a factory reset. The Kotlin runner does check
# this at the point of use, but that check is the *only* protection unless the
# package is also allowed here -- so it is injected into the exported allowlists
# rather than left to a hand-edit of the rendered asset.
ENFORCER_PACKAGE = "com.kuhy.focus_owner"
def policy_to_dict(policy: FocusPolicy) -> dict[str, Any]:
"""Return a JSON-serialisable representation of ``policy``."""
@ -39,8 +47,10 @@ def policy_to_dict(policy: FocusPolicy) -> dict[str, Any]:
},
"curfew": curfew,
"launcher_package": policy.launcher_package,
"allowed_packages": sorted(policy.allowed_packages),
"night_allowed_packages": sorted(policy.night_allowed_packages),
"allowed_packages": sorted({*policy.allowed_packages, ENFORCER_PACKAGE}),
"night_allowed_packages": sorted(
{*policy.night_allowed_packages, ENFORCER_PACKAGE},
),
"never_disable_prefixes": sorted(policy.never_disable_prefixes),
"workout_unblock_domains": sorted(policy.workout_unblock_domains),
"browser_packages": sorted(policy.browser_packages),

View File

@ -0,0 +1,109 @@
"""Tests for the JSON policy exporter.
The guarantee under test is the one that cannot be recovered from on the device
itself: the enforcing app must never be rendered into a policy that would hide
it. Everything else here is shape, not safety.
"""
from __future__ import annotations
import datetime as dt
from python_pkg.focus_policy.export import (
ENFORCER_PACKAGE,
policy_to_dict,
policy_to_json,
)
from python_pkg.focus_policy.model import CurfewWindow, FocusPolicy, HomeLocation
_DEFAULT_CURFEW = CurfewWindow(start=dt.time(23, 0), end=dt.time(5, 0))
def _policy(
*,
# The launcher must be allowed or the model rejects the policy outright.
allowed_packages: frozenset[str] = frozenset({"pl.mbank", "com.launcher"}),
night_allowed_packages: frozenset[str] = frozenset({"pl.mbank", "com.launcher"}),
curfew: CurfewWindow | None = _DEFAULT_CURFEW,
) -> FocusPolicy:
"""Build a policy with the enforcer deliberately absent from both lists."""
return FocusPolicy(
home=HomeLocation(
latitude=52.2297,
longitude=21.0122,
radius_m=150.0,
hysteresis_m=30.0,
),
curfew=curfew,
launcher_package="com.launcher",
allowed_packages=allowed_packages,
night_allowed_packages=night_allowed_packages,
never_disable_prefixes=("com.android.",),
workout_unblock_domains=frozenset({"youtube.com"}),
browser_packages=frozenset({"org.mozilla.firefox"}),
)
def test_enforcer_is_injected_into_both_allowlists() -> None:
"""The app must be allowed even when the source config omits it.
Regression guard for the on-device finding of 2026-08-09: the enforcer was
in neither allowlist, so the decision layer placed it in the hide set on
every enforcing pass, leaving one in-app check as the sole thing preventing
the app from hiding itself.
"""
payload = policy_to_dict(_policy())
assert ENFORCER_PACKAGE in payload["allowed_packages"]
assert ENFORCER_PACKAGE in payload["night_allowed_packages"]
def test_enforcer_is_not_duplicated_when_already_present() -> None:
"""Injection is a set union, so an explicit entry stays single."""
payload = policy_to_dict(
_policy(
allowed_packages=frozenset({"pl.mbank", "com.launcher", ENFORCER_PACKAGE}),
night_allowed_packages=frozenset({"com.launcher", ENFORCER_PACKAGE}),
),
)
assert payload["allowed_packages"].count(ENFORCER_PACKAGE) == 1
assert payload["night_allowed_packages"].count(ENFORCER_PACKAGE) == 1
def test_lists_are_sorted_for_stable_diffs() -> None:
"""Sorted output keeps a committed asset's diff meaningful."""
payload = policy_to_dict(_policy())
for key in (
"allowed_packages",
"night_allowed_packages",
"never_disable_prefixes",
"workout_unblock_domains",
"browser_packages",
):
assert payload[key] == sorted(payload[key])
def test_curfew_is_rendered_as_wall_clock_strings() -> None:
"""Kotlin parses `HH:MM`, not an ISO time."""
assert policy_to_dict(_policy())["curfew"] == {"start": "23:00", "end": "05:00"}
def test_absent_curfew_renders_as_null() -> None:
"""A policy with no curfew must not fabricate one."""
assert policy_to_dict(_policy(curfew=None))["curfew"] is None
def test_redact_home_blanks_coordinates_but_keeps_geometry() -> None:
"""A committed asset discloses the radius, never the location."""
payload = policy_to_json(_policy(), redact_home=True)
assert '"latitude": null' in payload
assert '"longitude": null' in payload
assert '"radius_m": 150.0' in payload
def test_coordinates_survive_when_not_redacted() -> None:
"""The provisioning path still needs the real values."""
assert '"latitude": 52.2297' in policy_to_json(_policy())

View File

@ -218,7 +218,13 @@ class TestExport:
payload = policy_to_dict(load_policy(config_dir / "config.sh"))
assert payload["schema_version"] == 1
assert payload["curfew"] == {"start": "23:00", "end": "05:00"}
assert payload["allowed_packages"] == ["com.good", "com.launcher", "pl.mbank"]
# The exporter injects the enforcer itself; see ENFORCER_PACKAGE.
assert payload["allowed_packages"] == [
"com.good",
"com.kuhy.focus_owner",
"com.launcher",
"pl.mbank",
]
assert payload["home"]["latitude"] == pytest.approx(52.2297)
def test_absent_curfew_serialises_as_null(self, config_dir: Path) -> None:

View File

@ -0,0 +1,41 @@
"""Integrity guard for the SyncYomi server's library payload.
TachiyomiSY 1.13.2 has an open upstream bug (jobobby04/TachiyomiSY#1634, #1638)
where a backup restore fails with ``SQLITE_BUSY`` on the app's *own* database.
The loud failure is survivable. The dangerous case is the quiet one: a restore
that reports ``Worker result SUCCESS`` while having written almost nothing, and
then pushes that near-empty library up to the server, replacing the only good
copy.
That happened on 2026-08-09: a 14 MB payload holding 2182 manga became a 267 KB
stub holding only sources and settings, and the real library survived solely as
stale pages in the SQLite write-ahead log.
This package exists so that never depends on luck again. It decodes the payload,
counts what is actually in it, and refuses to accept a collapse as normal. It
cannot prevent the upstream bug — that is Kotlin code in an APK — so it aims at
the part that is actually fixable: never letting a degraded copy become the only
copy.
"""
from __future__ import annotations
from python_pkg.syncyomi_guard.payload import (
PayloadError,
PayloadStats,
decode_payload,
)
from python_pkg.syncyomi_guard.verdict import (
Thresholds,
Verdict,
compare,
)
__all__ = [
"PayloadError",
"PayloadStats",
"Thresholds",
"Verdict",
"compare",
"decode_payload",
]

View File

@ -0,0 +1,168 @@
"""Command line entry point for the SyncYomi integrity guard.
Exit codes are the contract; a systemd timer and a human both read them:
* ``0`` — payload healthy (or a first-run baseline was recorded)
* ``1`` — payload collapsed, or it could not be read or decoded
A read failure is deliberately *not* a pass. The whole point of the guard is to
be believed on the day something is wrong, and "the database was missing so I
said OK" is the fail-open shape that lets a bad copy become the only copy.
"""
from __future__ import annotations
import argparse
from pathlib import Path
import shutil
import subprocess
import sys
from python_pkg.syncyomi_guard.payload import PayloadError, decode_payload
from python_pkg.syncyomi_guard.store import (
StoreError,
load_baseline,
read_payload,
save_baseline,
write_snapshot,
)
from python_pkg.syncyomi_guard.verdict import Status, Thresholds, Verdict, compare
_DEFAULT_DB = Path("/home/kuhy/syncyomi/config/syncyomi.db")
_DEFAULT_STATE = Path.home() / ".local/share/syncyomi_guard"
_DEFAULT_SNAPSHOTS = Path.home() / "syncyomi/snapshots"
_DEFAULT_KEEP = 14
def _notify(title: str, body: str) -> None:
"""Best-effort desktop notification; never fails the run.
The exit code is the real signal. A notification is a convenience, so a
machine without ``notify-send`` (or a run with no session bus) must not turn
a healthy check into a failure.
"""
binary = shutil.which("notify-send")
if binary is None:
return
try:
subprocess.run(
[binary, "--urgency=critical", title, body],
check=False,
timeout=10,
)
except (OSError, subprocess.SubprocessError):
return
def _build_parser() -> argparse.ArgumentParser:
"""Construct the argument parser."""
parser = argparse.ArgumentParser(
prog="syncyomi-guard",
description=(
"Verify the SyncYomi library payload has not silently collapsed, "
"and snapshot it as a restorable .tachibk when it is healthy."
),
)
parser.add_argument(
"--db",
type=Path,
default=_DEFAULT_DB,
help=f"SyncYomi SQLite database (default: {_DEFAULT_DB})",
)
parser.add_argument(
"--state-dir",
type=Path,
default=_DEFAULT_STATE,
help=f"where the baseline is stored (default: {_DEFAULT_STATE})",
)
parser.add_argument(
"--snapshot-dir",
type=Path,
default=_DEFAULT_SNAPSHOTS,
help=f"where .tachibk snapshots are written (default: {_DEFAULT_SNAPSHOTS})",
)
parser.add_argument(
"--keep",
type=int,
default=_DEFAULT_KEEP,
help=f"how many snapshots to retain (default: {_DEFAULT_KEEP})",
)
parser.add_argument(
"--max-drop",
type=float,
default=Thresholds().max_drop_ratio,
help="fail if any count drops by more than this fraction (default: 0.10)",
)
parser.add_argument(
"--no-snapshot",
action="store_true",
help="check only; do not write a snapshot or update the baseline",
)
parser.add_argument(
"--accept",
action="store_true",
help=(
"record the current payload as the new baseline even if it looks "
"collapsed (use after a deliberate library purge)"
),
)
return parser
def _report(verdict: Verdict) -> None:
"""Write the verdict to the appropriate stream.
A silent guard is a useless one: the journal line is how a human finds out
what the timer saw, so the counts are written on every run, not only on
failures.
"""
if verdict.is_failure:
sys.stderr.write(f"COLLAPSED: {verdict.reason}\n")
if verdict.previous is not None:
sys.stderr.write(f" previous: {verdict.previous.describe()}\n")
sys.stderr.write(f" current: {verdict.current.describe()}\n")
elif verdict.status is Status.FIRST_RUN:
sys.stdout.write(f"baseline recorded: {verdict.current.describe()}\n")
else:
sys.stdout.write(f"ok: {verdict.reason}\n")
def main(argv: list[str] | None = None) -> int:
"""Run the guard, returning the process exit code."""
args = _build_parser().parse_args(argv)
try:
blob = read_payload(args.db)
stats = decode_payload(blob)
except (StoreError, PayloadError) as exc:
sys.stderr.write(f"FAILED: {exc}\n")
_notify("SyncYomi guard: cannot verify", str(exc))
return 1
try:
thresholds = Thresholds(max_drop_ratio=args.max_drop)
except ValueError as exc:
sys.stderr.write(f"FAILED: {exc}\n")
return 1
verdict = compare(stats, load_baseline(args.state_dir), thresholds)
_report(verdict)
if verdict.is_failure and not args.accept:
_notify(
"SyncYomi library collapsed",
f"{verdict.reason}. Snapshot NOT overwritten; recover from "
f"{args.snapshot_dir}.",
)
return 1
if not args.no_snapshot:
snapshot = write_snapshot(args.snapshot_dir, blob, args.keep)
save_baseline(args.state_dir, stats)
sys.stdout.write(f"snapshot: {snapshot}\n")
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@ -0,0 +1,179 @@
"""Minimal protobuf reader for the Tachiyomi/Mihon ``Backup`` message.
Deliberately dependency-free. The alternative is vendoring Mihon's ``.proto``
files and a protobuf runtime, which would couple this guard to the app's schema
version — the guard has to keep working when upstream adds a field, because its
whole job is to run unattended and be trustworthy on the day something breaks.
Only the top-level field numbers are interpreted, and every unknown field is
skipped by wire type. Field numbers come from Mihon's ``BackupProto``:
===== ====================== =========================================
Field Meaning Why the guard cares
===== ====================== =========================================
1 ``backupManga`` The library. A collapse here is the alarm.
2 ``backupCategories`` Lost silently on 2026-08-09 while manga survived.
16 ``chapters`` (nested) Reading progress; catches a shallow restore.
101 ``backupSources`` Present even in a degraded payload, so it is
*not* evidence of health on its own.
===== ====================== =========================================
"""
from __future__ import annotations
from dataclasses import dataclass
_WIRE_VARINT = 0
_WIRE_64BIT = 1
_WIRE_LEN = 2
_WIRE_32BIT = 5
_FIELD_MANGA = 1
_FIELD_CATEGORIES = 2
_FIELD_CHAPTERS = 16
_FIELD_SOURCES = 101
# A varint wider than this is corruption, not a large number. Guards the decode
# loop against spinning on malformed input.
_MAX_VARINT_BYTES = 10
class PayloadError(ValueError):
"""Raised when the payload is not a decodable ``Backup`` message."""
@dataclass(frozen=True)
class PayloadStats:
"""What a payload actually contains, as opposed to what it claims.
``size_bytes`` is kept because it is the cheapest smoke test, but it is
never the deciding signal: the 2026-08-09 stub was a perfectly well-formed
protobuf message, just an almost empty one.
"""
size_bytes: int
manga: int
categories: int
chapters: int
sources: int
def describe(self) -> str:
"""Render a one-line human summary for logs and notifications."""
return (
f"{self.manga} manga, {self.chapters} chapters, "
f"{self.categories} categories, {self.sources} sources "
f"({self.size_bytes} bytes)"
)
def _read_varint(buf: bytes, pos: int) -> tuple[int, int]:
"""Read a base-128 varint, returning the value and the new offset."""
result = 0
shift = 0
start = pos
while pos < len(buf):
if pos - start >= _MAX_VARINT_BYTES:
msg = f"varint at offset {start} is unterminated"
raise PayloadError(msg)
byte = buf[pos]
pos += 1
result |= (byte & 0x7F) << shift
if not byte & 0x80:
return result, pos
shift += 7
msg = f"varint at offset {start} runs past end of payload"
raise PayloadError(msg)
def _skip_field(buf: bytes, pos: int, wire_type: int) -> int:
"""Advance past one non-length-delimited field, returning the new offset.
Length-delimited fields never reach here: both callers must inspect their
contents, so they handle that wire type inline.
"""
if wire_type == _WIRE_VARINT:
_, pos = _read_varint(buf, pos)
return pos
if wire_type == _WIRE_64BIT:
return pos + 8
if wire_type == _WIRE_32BIT:
return pos + 4
msg = f"unsupported wire type {wire_type} at offset {pos}"
raise PayloadError(msg)
def _count_chapters(entry: bytes) -> int:
"""Count ``chapters`` submessages inside one ``BackupManga`` entry.
Chapters are field 16, not field 3 — field 3 is the title. Getting this
wrong yields exactly one "chapter" per manga, which looks plausible enough
to pass a careless review, so the distinction is load-bearing.
"""
chapters = 0
pos = 0
while pos < len(entry):
key, pos = _read_varint(entry, pos)
field_number = key >> 3
wire_type = key & 0x07
if wire_type == _WIRE_LEN:
length, pos = _read_varint(entry, pos)
end = pos + length
if end > len(entry):
msg = "chapter field overruns manga entry"
raise PayloadError(msg)
if field_number == _FIELD_CHAPTERS:
chapters += 1
pos = end
else:
pos = _skip_field(entry, pos, wire_type)
return chapters
def decode_payload(blob: bytes) -> PayloadStats:
"""Decode a ``Backup`` payload into verifiable counts.
The payload must be consumed exactly: trailing bytes mean the message was
truncated or spliced, which is precisely the corruption a page-level
recovery can produce, so it is treated as an error rather than ignored.
Raises:
PayloadError: If the payload is empty, malformed, or not fully consumed.
"""
if not blob:
msg = "payload is empty"
raise PayloadError(msg)
manga = categories = chapters = sources = 0
pos = 0
while pos < len(blob):
key, pos = _read_varint(blob, pos)
field_number = key >> 3
wire_type = key & 0x07
if wire_type == _WIRE_LEN:
length, pos = _read_varint(blob, pos)
end = pos + length
if end > len(blob):
msg = f"field {field_number} overruns payload"
raise PayloadError(msg)
if field_number == _FIELD_MANGA:
manga += 1
chapters += _count_chapters(blob[pos:end])
elif field_number == _FIELD_CATEGORIES:
categories += 1
elif field_number == _FIELD_SOURCES:
sources += 1
pos = end
else:
pos = _skip_field(blob, pos, wire_type)
if pos != len(blob):
msg = f"payload not fully consumed ({pos} of {len(blob)} bytes)"
raise PayloadError(msg)
return PayloadStats(
size_bytes=len(blob),
manga=manga,
categories=categories,
chapters=chapters,
sources=sources,
)

View File

@ -0,0 +1,182 @@
"""Read the live payload and keep versioned snapshots of the good ones.
Two rules shape this module, both learned on 2026-08-09:
* The database is opened **read-only**. The guard runs on a timer against a
database a container is actively writing; it must never be the reason
SyncYomi sees a lock.
* A snapshot is written only for a payload that passed. Snapshotting first and
judging afterwards would have faithfully archived the 267 KB stub.
Snapshots are gzipped ``Backup`` messages, which is exactly the ``.tachibk``
format the app restores from — so recovery is "copy this file to the phone",
with no decoding step at the moment it is needed most.
"""
from __future__ import annotations
from dataclasses import asdict
from datetime import UTC, datetime
import gzip
import json
import sqlite3
from typing import TYPE_CHECKING, Final
from python_pkg.syncyomi_guard.payload import PayloadError, PayloadStats
if TYPE_CHECKING:
from pathlib import Path
_STATE_FILENAME: Final = "last_known_good.json"
# The glob matches the timestamp layout *only*. A looser pattern such as
# ``syncyomi_*.tachibk`` would also match a hand-named file like
# ``syncyomi_recovered_2026-08-09.tachibk`` — the irreplaceable original
# rescued from the WAL — and the pruner would delete it as a stale snapshot.
_SNAPSHOT_GLOB: Final = "syncyomi_[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T*Z.tachibk"
_SNAPSHOT_STEM: Final = "syncyomi_%Y-%m-%dT%H-%M-%SZ"
class StoreError(RuntimeError):
"""Raised when the payload cannot be read from the SyncYomi database."""
def read_payload(db_path: Path) -> bytes:
"""Read the single ``sync_data`` blob from a SyncYomi SQLite database.
Opened through an immutable URI: no locking, no WAL recovery, no write to
the directory. The database stays exactly as the container left it.
Raises:
StoreError: If the database is unreadable or holds no sync row.
"""
if not db_path.is_file():
msg = f"no SyncYomi database at {db_path}"
raise StoreError(msg)
# ``sqlite3.connect`` as a context manager commits the transaction but does
# NOT close the connection, so it is closed explicitly. A guard that leaks
# handles against the live database would eventually become the thing
# holding a file open on it.
uri = f"file:{db_path}?immutable=1"
try:
conn = sqlite3.connect(uri, uri=True)
except sqlite3.Error as exc:
msg = f"cannot read {db_path}: {exc}"
raise StoreError(msg) from exc
try:
rows = conn.execute(
"SELECT data FROM sync_data ORDER BY id LIMIT 1",
).fetchall()
except sqlite3.Error as exc:
msg = f"cannot read {db_path}: {exc}"
raise StoreError(msg) from exc
finally:
conn.close()
if not rows:
msg = f"{db_path} has no sync_data row"
raise StoreError(msg)
blob = rows[0][0]
if not isinstance(blob, bytes):
msg = f"sync_data.data is {type(blob).__name__}, expected bytes"
raise StoreError(msg)
return blob
def load_baseline(state_dir: Path) -> PayloadStats | None:
"""Load the last known good stats, or ``None`` when there is no baseline.
A corrupt or partial state file is treated as absent rather than fatal: the
guard then re-baselines loudly (``FIRST_RUN``) instead of refusing to run.
"""
path = state_dir / _STATE_FILENAME
if not path.is_file():
return None
try:
raw = json.loads(path.read_text(encoding="utf-8"))
return PayloadStats(
size_bytes=int(raw["size_bytes"]),
manga=int(raw["manga"]),
categories=int(raw["categories"]),
chapters=int(raw["chapters"]),
sources=int(raw["sources"]),
)
except (OSError, ValueError, KeyError, TypeError):
return None
def save_baseline(state_dir: Path, stats: PayloadStats) -> Path:
"""Record ``stats`` as the new last known good baseline."""
state_dir.mkdir(parents=True, exist_ok=True)
path = state_dir / _STATE_FILENAME
payload = dict(asdict(stats))
payload["recorded_at"] = datetime.now(UTC).isoformat()
path.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8")
return path
def write_snapshot(
snapshot_dir: Path,
blob: bytes,
keep: int,
now: datetime | None = None,
) -> Path:
"""Write ``blob`` as a restorable ``.tachibk`` and prune old snapshots.
Raises:
ValueError: If ``keep`` is not at least 1.
"""
if keep < 1:
msg = f"keep must be >= 1, got {keep}"
raise ValueError(msg)
snapshot_dir.mkdir(parents=True, exist_ok=True)
stamp = (now or datetime.now(UTC)).strftime(_SNAPSHOT_STEM)
# Timestamps are second-granular, so two runs in the same second would map
# to one filename and the second would silently overwrite the first —
# quietly holding fewer than ``keep`` distinct snapshots, and in the worst
# case replacing a good library with a stub written a fraction of a second
# later. Suffix on collision rather than clobber.
path = snapshot_dir / f"{stamp}.tachibk"
suffix = 1
while path.exists():
path = snapshot_dir / f"{stamp}-{suffix}.tachibk"
suffix += 1
path.write_bytes(gzip.compress(blob))
_prune(snapshot_dir, keep)
return path
def _prune(snapshot_dir: Path, keep: int) -> None:
"""Delete all but the ``keep`` newest snapshots, by filename order.
Filenames are UTC timestamps in a sortable layout, so lexical order is
chronological order without stat-ing every file.
"""
snapshots = sorted(snapshot_dir.glob(_SNAPSHOT_GLOB))
for stale in snapshots[:-keep]:
stale.unlink()
def latest_snapshot(snapshot_dir: Path) -> Path | None:
"""Return the newest snapshot, or ``None`` when none exist."""
snapshots = sorted(snapshot_dir.glob(_SNAPSHOT_GLOB))
return snapshots[-1] if snapshots else None
def read_snapshot(path: Path) -> bytes:
"""Decompress a ``.tachibk`` snapshot back into a raw payload.
Raises:
PayloadError: If the file is not readable gzip.
"""
try:
return gzip.decompress(path.read_bytes())
except (OSError, gzip.BadGzipFile) as exc:
msg = f"cannot read snapshot {path}: {exc}"
raise PayloadError(msg) from exc

View File

@ -0,0 +1,93 @@
"""Shared protobuf builders for the guard's tests.
The tests construct real ``Backup`` wire format rather than mocking the decoder.
A mock would happily agree with a decoder that counts the wrong field number,
which is the specific bug this package had while being written (chapters are
field 16; field 3 is the title, and counting it yields exactly one "chapter"
per manga).
"""
from __future__ import annotations
import pytest
_WIRE_VARINT = 0
_WIRE_LEN = 2
def encode_varint(value: int) -> bytes:
"""Encode ``value`` as a base-128 varint."""
out = bytearray()
while True:
byte = value & 0x7F
value >>= 7
if value:
out.append(byte | 0x80)
else:
out.append(byte)
return bytes(out)
def tag(field_number: int, wire_type: int) -> bytes:
"""Encode a protobuf field tag."""
return encode_varint((field_number << 3) | wire_type)
def length_delimited(field_number: int, payload: bytes) -> bytes:
"""Encode a length-delimited field."""
return tag(field_number, _WIRE_LEN) + encode_varint(len(payload)) + payload
def varint_field(field_number: int, value: int) -> bytes:
"""Encode a varint field."""
return tag(field_number, _WIRE_VARINT) + encode_varint(value)
def chapter(url: str = "/chapter/x") -> bytes:
"""Build one ``chapters`` submessage (field 16 of ``BackupManga``)."""
return length_delimited(16, length_delimited(1, url.encode()))
def manga(*, url: str = "/manga/x", chapters: int = 0, title: str = "T") -> bytes:
"""Build one ``BackupManga`` entry (field 1 of ``Backup``)."""
body = length_delimited(2, url.encode()) + length_delimited(3, title.encode())
body += b"".join(chapter(f"{url}/c{i}") for i in range(chapters))
return length_delimited(1, body)
def category(name: str) -> bytes:
"""Build one ``BackupCategory`` entry (field 2 of ``Backup``)."""
return length_delimited(2, length_delimited(1, name.encode()))
def source(name: str = "MangaDex") -> bytes:
"""Build one ``BackupSource`` entry (field 101 of ``Backup``)."""
return length_delimited(101, length_delimited(1, name.encode()))
def backup(
*,
manga_count: int = 0,
chapters_each: int = 0,
categories: int = 0,
sources: int = 0,
) -> bytes:
"""Build a whole ``Backup`` message with the requested shape."""
parts = [
manga(url=f"/manga/{i}", chapters=chapters_each) for i in range(manga_count)
]
parts += [category(f"cat{i}") for i in range(categories)]
parts += [source(f"src{i}") for i in range(sources)]
return b"".join(parts)
@pytest.fixture
def healthy_payload() -> bytes:
"""A payload standing in for a normal library."""
return backup(manga_count=10, chapters_each=3, categories=4, sources=2)
@pytest.fixture
def stub_payload() -> bytes:
"""The 2026-08-09 failure shape: sources survive, the library does not."""
return backup(manga_count=0, categories=0, sources=2)

View File

@ -0,0 +1,216 @@
"""Tests for the CLI, whose exit code is the contract systemd reads.
The rule under test throughout: the guard fails closed. Anything it cannot
verify is a failure, because "I could not check, so everything is fine" is how
a degraded copy becomes the only copy.
"""
from __future__ import annotations
import sqlite3
from typing import TYPE_CHECKING
import pytest
from python_pkg.syncyomi_guard.__main__ import main
from python_pkg.syncyomi_guard.store import load_baseline
from python_pkg.syncyomi_guard.tests.conftest import backup
if TYPE_CHECKING:
from collections.abc import Sequence
from pathlib import Path
def _write_db(path: Path, blob: bytes) -> None:
conn = sqlite3.connect(path)
try:
with conn:
conn.execute("CREATE TABLE sync_data (id INTEGER PRIMARY KEY, data BLOB)")
conn.execute("INSERT INTO sync_data (id, data) VALUES (1, ?)", (blob,))
finally:
conn.close()
def _args(tmp_path: Path, db: Path, *extra: str) -> Sequence[str]:
return [
"--db",
str(db),
"--state-dir",
str(tmp_path / "state"),
"--snapshot-dir",
str(tmp_path / "snaps"),
*extra,
]
@pytest.fixture(autouse=True)
def _no_notifications(monkeypatch: pytest.MonkeyPatch) -> None:
"""Never fire a real desktop notification from a test."""
monkeypatch.setattr(
"python_pkg.syncyomi_guard.__main__.shutil.which", lambda _: None
)
def test_first_run_records_a_baseline_and_snapshot(tmp_path: Path) -> None:
db = tmp_path / "syncyomi.db"
_write_db(db, backup(manga_count=10, chapters_each=2, categories=3))
assert main(_args(tmp_path, db)) == 0
assert load_baseline(tmp_path / "state") is not None
assert list((tmp_path / "snaps").glob("*.tachibk"))
def test_healthy_second_run_passes(tmp_path: Path) -> None:
db = tmp_path / "syncyomi.db"
_write_db(db, backup(manga_count=10, chapters_each=2, categories=3))
assert main(_args(tmp_path, db)) == 0
assert main(_args(tmp_path, db)) == 0
def test_collapse_fails_and_preserves_the_good_snapshot(tmp_path: Path) -> None:
"""The 2026-08-09 scenario, end to end through the binary."""
db = tmp_path / "syncyomi.db"
_write_db(db, backup(manga_count=100, chapters_each=5, categories=8))
assert main(_args(tmp_path, db)) == 0
good = sorted((tmp_path / "snaps").glob("*.tachibk"))
assert len(good) == 1
good_bytes = good[0].read_bytes()
# The library collapses to a sources-only stub, exactly as it did that night.
db.unlink()
_write_db(db, backup(manga_count=0, sources=2))
assert main(_args(tmp_path, db)) == 1
after = sorted((tmp_path / "snaps").glob("*.tachibk"))
assert len(after) == 1, "a collapsed payload must not be snapshotted"
assert after[0].read_bytes() == good_bytes
baseline = load_baseline(tmp_path / "state")
assert baseline is not None
assert baseline.manga == 100, "baseline must not absorb the collapse"
def test_accept_overrides_a_deliberate_purge(tmp_path: Path) -> None:
db = tmp_path / "syncyomi.db"
_write_db(db, backup(manga_count=100, chapters_each=2, categories=4))
assert main(_args(tmp_path, db)) == 0
db.unlink()
_write_db(db, backup(manga_count=1, sources=1))
assert main(_args(tmp_path, db, "--accept")) == 0
baseline = load_baseline(tmp_path / "state")
assert baseline is not None
assert baseline.manga == 1
def test_no_snapshot_checks_without_writing(tmp_path: Path) -> None:
db = tmp_path / "syncyomi.db"
_write_db(db, backup(manga_count=5, chapters_each=1))
assert main(_args(tmp_path, db, "--no-snapshot")) == 0
assert not (tmp_path / "snaps").exists()
assert load_baseline(tmp_path / "state") is None
def test_missing_database_exits_nonzero(tmp_path: Path) -> None:
"""Fail closed rather than reporting a pass for an unreadable database."""
assert main(_args(tmp_path, tmp_path / "absent.db")) == 1
def test_undecodable_payload_exits_nonzero(tmp_path: Path) -> None:
db = tmp_path / "syncyomi.db"
_write_db(db, b"\xff\xff\xff not protobuf")
assert main(_args(tmp_path, db)) == 1
def test_invalid_threshold_exits_nonzero(tmp_path: Path) -> None:
db = tmp_path / "syncyomi.db"
_write_db(db, backup(manga_count=1))
assert main(_args(tmp_path, db, "--max-drop", "5")) == 1
def test_collapse_message_names_the_loss(
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
db = tmp_path / "syncyomi.db"
_write_db(db, backup(manga_count=50, chapters_each=2, categories=6))
main(_args(tmp_path, db))
capsys.readouterr()
db.unlink()
_write_db(db, backup(manga_count=50, chapters_each=2, categories=0))
main(_args(tmp_path, db))
err = capsys.readouterr().err
assert "COLLAPSED" in err
assert "categories went from 6 to 0" in err
def test_report_handles_a_collapse_without_a_baseline(
capsys: pytest.CaptureFixture[str],
) -> None:
"""Defensive branch: ``compare`` never returns this, but ``_report`` must cope.
A COLLAPSED verdict always carries the baseline it was measured against, so
this shape is unreachable through ``main``. It is covered directly so the
guard cannot crash while reporting the one thing it exists to report.
"""
from python_pkg.syncyomi_guard.__main__ import _report
from python_pkg.syncyomi_guard.payload import PayloadStats
from python_pkg.syncyomi_guard.verdict import Status, Verdict
stats = PayloadStats(
size_bytes=1,
manga=0,
categories=0,
chapters=0,
sources=0,
)
_report(
Verdict(
status=Status.COLLAPSED,
reason="synthetic",
current=stats,
previous=None,
),
)
err = capsys.readouterr().err
assert "COLLAPSED" in err
assert "previous:" not in err
def test_notification_is_attempted_on_failure(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A failure should reach the desktop, but must not depend on it."""
calls: list[list[str]] = []
monkeypatch.setattr(
"python_pkg.syncyomi_guard.__main__.shutil.which",
lambda _: "/usr/bin/notify-send",
)
monkeypatch.setattr(
"python_pkg.syncyomi_guard.__main__.subprocess.run",
lambda cmd, **_: calls.append(cmd),
)
assert main(_args(tmp_path, tmp_path / "absent.db")) == 1
assert calls
assert "notify-send" in calls[0][0]
def test_notification_failure_does_not_mask_the_verdict(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
def explode(*_: object, **__: object) -> None:
msg = "no session bus"
raise OSError(msg)
monkeypatch.setattr(
"python_pkg.syncyomi_guard.__main__.shutil.which",
lambda _: "/usr/bin/notify-send",
)
monkeypatch.setattr("python_pkg.syncyomi_guard.__main__.subprocess.run", explode)
assert main(_args(tmp_path, tmp_path / "absent.db")) == 1

View File

@ -0,0 +1,119 @@
"""Tests for the ``Backup`` protobuf reader.
The guarantee under test is that the counts are *true*. A decoder that silently
undercounts is worse than no guard at all, because it would report OK while the
library drained away.
"""
from __future__ import annotations
import pytest
from python_pkg.syncyomi_guard.payload import PayloadError, decode_payload
from python_pkg.syncyomi_guard.tests.conftest import (
backup,
encode_varint,
length_delimited,
manga,
tag,
varint_field,
)
def test_counts_every_top_level_field(healthy_payload: bytes) -> None:
stats = decode_payload(healthy_payload)
assert stats.manga == 10
assert stats.chapters == 30
assert stats.categories == 4
assert stats.sources == 2
assert stats.size_bytes == len(healthy_payload)
def test_chapters_come_from_field_16_not_the_title(stub_payload: bytes) -> None:
"""A title-only manga has zero chapters, not one.
Field 3 is the title and field 16 is a chapter. Counting field 3 yields
exactly one chapter per manga, which looks plausible in aggregate.
"""
stats = decode_payload(manga(url="/manga/a", chapters=0, title="A Long Title"))
assert stats.manga == 1
assert stats.chapters == 0
assert decode_payload(stub_payload).manga == 0
def test_the_2026_08_09_stub_reports_an_empty_library(stub_payload: bytes) -> None:
"""Sources present, library absent — the payload that overwrote the good one."""
stats = decode_payload(stub_payload)
assert stats.manga == 0
assert stats.chapters == 0
assert stats.categories == 0
assert stats.sources == 2
def test_unknown_fields_of_every_wire_type_are_skipped() -> None:
"""Upstream may add fields; the guard must not break when it does."""
payload = (
manga(url="/manga/a", chapters=1)
+ varint_field(900, 12345)
+ tag(901, 5)
+ b"\x00\x01\x02\x03"
+ tag(902, 1)
+ b"\x00\x01\x02\x03\x04\x05\x06\x07"
+ length_delimited(903, b"opaque")
)
stats = decode_payload(payload)
assert stats.manga == 1
assert stats.chapters == 1
def test_unknown_wire_type_inside_a_manga_entry_is_skipped() -> None:
"""Exercises the non-length branch of the per-entry chapter scan."""
body = length_delimited(2, b"/manga/a") + varint_field(8, 1) + tag(9, 5)
payload = length_delimited(1, body + b"\x00\x01\x02\x03")
assert decode_payload(payload).manga == 1
def test_empty_payload_is_rejected() -> None:
with pytest.raises(PayloadError, match="empty"):
decode_payload(b"")
def test_truncated_length_prefix_is_rejected() -> None:
"""A field claiming more bytes than exist is corruption, not a short read."""
payload = tag(1, 2) + encode_varint(500) + b"too short"
with pytest.raises(PayloadError, match="overruns"):
decode_payload(payload)
def test_truncated_chapter_inside_a_manga_is_rejected() -> None:
body = length_delimited(2, b"/manga/a") + tag(16, 2) + encode_varint(400) + b"xx"
with pytest.raises(PayloadError, match="overruns manga entry"):
decode_payload(length_delimited(1, body))
def test_unterminated_varint_is_rejected() -> None:
with pytest.raises(PayloadError, match="unterminated"):
decode_payload(b"\xff" * 12)
def test_varint_running_off_the_end_is_rejected() -> None:
with pytest.raises(PayloadError, match="past end"):
decode_payload(b"\xff\xff")
def test_unsupported_wire_type_is_rejected() -> None:
with pytest.raises(PayloadError, match="unsupported wire type"):
decode_payload(tag(1, 3))
def test_trailing_bytes_are_rejected() -> None:
"""Splice damage from page-level recovery must not decode as success."""
payload = manga(url="/manga/a") + tag(2, 1) + b"\x00" * 4
with pytest.raises(PayloadError, match="not fully consumed"):
decode_payload(payload)
def test_describe_is_human_readable() -> None:
text = decode_payload(backup(manga_count=2, chapters_each=1)).describe()
assert "2 manga" in text
assert "2 chapters" in text

View File

@ -0,0 +1,239 @@
"""Tests for reading the payload and keeping snapshots.
Two behaviours here are load-bearing and easy to regress: the database is
opened without taking a lock, and pruning never deletes more than it should.
"""
from __future__ import annotations
import gzip
import sqlite3
from typing import TYPE_CHECKING
import pytest
from python_pkg.syncyomi_guard.payload import PayloadError, PayloadStats
from python_pkg.syncyomi_guard.store import (
StoreError,
latest_snapshot,
load_baseline,
read_payload,
read_snapshot,
save_baseline,
write_snapshot,
)
if TYPE_CHECKING:
from datetime import datetime
from pathlib import Path
_STATS = PayloadStats(
size_bytes=100,
manga=10,
categories=2,
chapters=30,
sources=3,
)
def _make_db(path: Path, blob: object) -> None:
"""Create a minimal SyncYomi-shaped database holding ``blob``."""
conn = sqlite3.connect(path)
try:
with conn:
conn.execute("CREATE TABLE sync_data (id INTEGER PRIMARY KEY, data BLOB)")
conn.execute("INSERT INTO sync_data (id, data) VALUES (1, ?)", (blob,))
finally:
conn.close()
def test_reads_the_payload_blob(tmp_path: Path) -> None:
db = tmp_path / "syncyomi.db"
_make_db(db, b"payload-bytes")
assert read_payload(db) == b"payload-bytes"
def test_missing_database_is_an_error_not_an_empty_payload(tmp_path: Path) -> None:
"""Fail closed: a missing database must never read as "nothing to worry about"."""
with pytest.raises(StoreError, match="no SyncYomi database"):
read_payload(tmp_path / "absent.db")
def test_database_without_the_table_is_an_error(tmp_path: Path) -> None:
db = tmp_path / "empty.db"
conn = sqlite3.connect(db)
try:
with conn:
conn.execute("CREATE TABLE unrelated (id INTEGER)")
finally:
conn.close()
with pytest.raises(StoreError, match="cannot read"):
read_payload(db)
def test_database_with_no_rows_is_an_error(tmp_path: Path) -> None:
db = tmp_path / "norows.db"
conn = sqlite3.connect(db)
try:
with conn:
conn.execute("CREATE TABLE sync_data (id INTEGER PRIMARY KEY, data BLOB)")
finally:
conn.close()
with pytest.raises(StoreError, match="no sync_data row"):
read_payload(db)
def test_unopenable_database_is_an_error(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A connect-time failure must surface, not propagate as a raw sqlite error."""
db = tmp_path / "syncyomi.db"
_make_db(db, b"payload")
def refuse(*_: object, **__: object) -> object:
msg = "unable to open database file"
raise sqlite3.OperationalError(msg)
monkeypatch.setattr(
"python_pkg.syncyomi_guard.store.sqlite3.connect",
refuse,
)
with pytest.raises(StoreError, match="cannot read"):
read_payload(db)
def test_non_blob_payload_is_an_error(tmp_path: Path) -> None:
db = tmp_path / "text.db"
_make_db(db, "not bytes")
with pytest.raises(StoreError, match="expected bytes"):
read_payload(db)
def test_reading_does_not_lock_the_database(tmp_path: Path) -> None:
"""The guard runs against a database the container is writing.
An exclusive read would make the guard a cause of the very ``SQLITE_BUSY``
class of failure it exists to detect.
"""
db = tmp_path / "syncyomi.db"
_make_db(db, b"payload")
writer = sqlite3.connect(db)
try:
writer.execute("BEGIN IMMEDIATE")
writer.execute("UPDATE sync_data SET data = ? WHERE id = 1", (b"changed",))
assert read_payload(db) == b"payload"
writer.rollback()
finally:
writer.close()
def test_baseline_round_trips(tmp_path: Path) -> None:
save_baseline(tmp_path, _STATS)
assert load_baseline(tmp_path) == _STATS
def test_absent_baseline_is_none(tmp_path: Path) -> None:
assert load_baseline(tmp_path) is None
@pytest.mark.parametrize(
"content",
["not json at all", '{"manga": 1}', '{"size_bytes": "x"}', "[]"],
)
def test_corrupt_baseline_reads_as_absent(tmp_path: Path, content: str) -> None:
"""A damaged state file must re-baseline loudly, not crash the timer."""
(tmp_path / "last_known_good.json").write_text(content, encoding="utf-8")
assert load_baseline(tmp_path) is None
def test_snapshot_is_a_restorable_tachibk(tmp_path: Path) -> None:
"""The snapshot must be exactly what the app restores from."""
path = write_snapshot(tmp_path, b"library-bytes", keep=5)
assert path.suffix == ".tachibk"
assert gzip.decompress(path.read_bytes()) == b"library-bytes"
assert read_snapshot(path) == b"library-bytes"
def test_snapshot_pruning_keeps_the_newest(tmp_path: Path) -> None:
from datetime import UTC, datetime
def at(day: int) -> datetime:
return datetime(2026, 8, day, 12, 0, tzinfo=UTC)
for day in range(1, 6):
write_snapshot(tmp_path, f"day{day}".encode(), keep=3, now=at(day))
remaining = sorted(p.name for p in tmp_path.glob("*.tachibk"))
assert len(remaining) == 3
assert "2026-08-05" in remaining[-1]
assert read_snapshot(tmp_path / remaining[-1]) == b"day5"
def test_two_snapshots_in_the_same_second_do_not_overwrite(tmp_path: Path) -> None:
"""Second-granular timestamps must not silently collapse two snapshots.
Overwriting would quietly keep fewer than ``keep`` snapshots, and in the
worst case replace a good library with a stub written a fraction of a
second later — the exact loss this package exists to prevent.
"""
from datetime import UTC, datetime
same_second = datetime(2026, 8, 9, 23, 45, 30, tzinfo=UTC)
first = write_snapshot(tmp_path, b"good-library", keep=14, now=same_second)
second = write_snapshot(tmp_path, b"degraded-stub", keep=14, now=same_second)
assert first != second
assert read_snapshot(first) == b"good-library"
assert read_snapshot(second) == b"degraded-stub"
assert len(list(tmp_path.glob("*.tachibk"))) == 2
def test_pruning_never_deletes_a_hand_named_recovery_file(tmp_path: Path) -> None:
"""Regression guard for a real near-miss.
``syncyomi_recovered_2026-08-09.tachibk`` was the only surviving copy of a
2182-manga library, rebuilt from the SQLite WAL. A ``syncyomi_*.tachibk``
prune glob would have matched and deleted it.
"""
from datetime import UTC, datetime
precious = tmp_path / "syncyomi_recovered_2026-08-09.tachibk"
precious.write_bytes(b"irreplaceable")
for day in range(1, 6):
write_snapshot(
tmp_path,
b"routine",
keep=1,
now=datetime(2026, 8, day, tzinfo=UTC),
)
assert precious.exists()
assert precious.read_bytes() == b"irreplaceable"
def test_keep_must_be_positive(tmp_path: Path) -> None:
with pytest.raises(ValueError, match="keep must be"):
write_snapshot(tmp_path, b"x", keep=0)
def test_latest_snapshot_reports_none_when_empty(tmp_path: Path) -> None:
assert latest_snapshot(tmp_path) is None
def test_latest_snapshot_finds_the_newest(tmp_path: Path) -> None:
from datetime import UTC, datetime
write_snapshot(tmp_path, b"old", keep=9, now=datetime(2026, 8, 1, tzinfo=UTC))
write_snapshot(tmp_path, b"new", keep=9, now=datetime(2026, 8, 9, tzinfo=UTC))
newest = latest_snapshot(tmp_path)
assert newest is not None
assert read_snapshot(newest) == b"new"
def test_unreadable_snapshot_is_an_error(tmp_path: Path) -> None:
bad = tmp_path / "syncyomi_broken.tachibk"
bad.write_bytes(b"not gzip")
with pytest.raises(PayloadError, match="cannot read snapshot"):
read_snapshot(bad)

View File

@ -0,0 +1,152 @@
"""Tests for the collapse-detection rules.
Anchored on the real 2026-08-09 numbers so the thresholds are judged against
what actually happened, not against invented ones.
"""
from __future__ import annotations
import pytest
from python_pkg.syncyomi_guard.payload import PayloadStats
from python_pkg.syncyomi_guard.verdict import Status, Thresholds, compare
# The library as it stood before the failed restore.
_GOOD = PayloadStats(
size_bytes=14_083_674,
manga=2182,
categories=18,
chapters=75_376,
sources=24,
)
# What the "successful" restore pushed to the server at 22:53.
_STUB = PayloadStats(
size_bytes=267_737,
manga=0,
categories=0,
chapters=0,
sources=24,
)
# After the good restore: manga intact, duplicate chapters collapsed,
# categories silently gone.
_DEDUPED = PayloadStats(
size_bytes=12_277_887,
manga=2182,
categories=0,
chapters=68_418,
sources=24,
)
def test_the_real_incident_is_reported_as_collapsed() -> None:
verdict = compare(_STUB, _GOOD)
assert verdict.status is Status.COLLAPSED
assert verdict.is_failure
assert "manga went from 2182 to 0" in verdict.reason
def test_category_only_loss_is_still_a_collapse() -> None:
"""The subtle half of the incident.
Every manga and every distinct chapter survived; only the categories went.
A manga-only check would have called this a clean sync.
"""
verdict = compare(_DEDUPED, _GOOD)
assert verdict.is_failure
assert "categories went from 18 to 0" in verdict.reason
def test_chapter_dedup_alone_does_not_trip_the_guard() -> None:
"""68418 vs 75376 is a 9.2 % drop caused by removing duplicates.
Real event: the restore collapsed 6958 duplicate chapter entries while the
distinct chapter count was unchanged. Failing here would make the guard cry
wolf on a legitimate cleanup.
"""
previous = PayloadStats(
size_bytes=14_083_674,
manga=2182,
categories=18,
chapters=75_376,
sources=24,
)
current = PayloadStats(
size_bytes=12_277_887,
manga=2182,
categories=18,
chapters=68_418,
sources=24,
)
assert compare(current, previous).status is Status.OK
def test_growth_is_healthy() -> None:
bigger = PayloadStats(
size_bytes=15_000_000,
manga=2200,
categories=19,
chapters=76_000,
sources=24,
)
assert compare(bigger, _GOOD).status is Status.OK
def test_small_drop_is_tolerated() -> None:
"""Finishing and removing a few series is normal."""
smaller = PayloadStats(
size_bytes=14_000_000,
manga=2100,
categories=18,
chapters=75_000,
sources=24,
)
assert compare(smaller, _GOOD).status is Status.OK
def test_drop_past_the_threshold_fails() -> None:
halved = PayloadStats(
size_bytes=7_000_000,
manga=1000,
categories=18,
chapters=40_000,
sources=24,
)
verdict = compare(halved, _GOOD)
assert verdict.is_failure
assert "manga dropped" in verdict.reason
def test_missing_baseline_is_first_run_not_success() -> None:
"""A lost state file must not silently turn the guard into a no-op."""
verdict = compare(_GOOD, None)
assert verdict.status is Status.FIRST_RUN
assert not verdict.is_failure
assert verdict.previous is None
def test_growth_from_a_zero_baseline_is_not_a_drop() -> None:
assert compare(_GOOD, _STUB).status is Status.OK
def test_threshold_is_configurable() -> None:
slightly_smaller = PayloadStats(
size_bytes=13_000_000,
manga=2100,
categories=18,
chapters=75_000,
sources=24,
)
strict = Thresholds(max_drop_ratio=0.01)
assert compare(slightly_smaller, _GOOD, strict).is_failure
@pytest.mark.parametrize("ratio", [0.0, 1.0, -0.5, 2.0])
def test_nonsense_thresholds_are_rejected(ratio: float) -> None:
with pytest.raises(ValueError, match="max_drop_ratio"):
Thresholds(max_drop_ratio=ratio)
def test_reason_describes_a_healthy_payload() -> None:
assert "2182 manga" in compare(_GOOD, _GOOD).reason

View File

@ -0,0 +1,132 @@
"""Decide whether a payload change is normal drift or a silent collapse.
The thresholds here encode one real incident. A pure "is it zero?" check would
have caught 2026-08-09, but Kamiruku's report on upstream #1634 describes the
harder case — a restore that keeps *some* entries and drops the rest. A library
does not lose a tenth of itself between two syncs, so that is the line.
Categories get their own rule because on 2026-08-09 all 2182 manga survived the
round trip and all 18 categories did not. A manga-only check would have called
that a clean sync.
"""
from __future__ import annotations
from dataclasses import dataclass
import enum
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from python_pkg.syncyomi_guard.payload import PayloadStats
class Status(enum.Enum):
"""Outcome of comparing a payload against the last known good one."""
OK = "ok"
FIRST_RUN = "first-run"
COLLAPSED = "collapsed"
@dataclass(frozen=True)
class Thresholds:
"""Limits distinguishing acceptable shrinkage from data loss.
``max_drop_ratio`` is a fraction: 0.10 fails a drop of more than 10 %.
Removing a few finished series is normal; losing a tenth of a 2000-entry
library in one sync is not something that happens on purpose.
"""
max_drop_ratio: float = 0.10
def __post_init__(self) -> None:
"""Reject a ratio outside the open interval (0, 1).
Raises:
ValueError: If ``max_drop_ratio`` is not a usable fraction.
"""
if not 0.0 < self.max_drop_ratio < 1.0:
msg = f"max_drop_ratio must be in (0, 1), got {self.max_drop_ratio}"
raise ValueError(msg)
@dataclass(frozen=True)
class Verdict:
"""The guard's decision, plus the reason, for logs and notifications."""
status: Status
reason: str
current: PayloadStats
previous: PayloadStats | None
@property
def is_failure(self) -> bool:
"""Whether this verdict should fail the run and alert."""
return self.status is Status.COLLAPSED
def _drop_reason(
label: str,
previous: int,
current: int,
thresholds: Thresholds,
) -> str | None:
"""Return a failure reason if ``label`` dropped too far, else ``None``."""
if previous == 0 or current >= previous:
return None
if current == 0:
return f"{label} went from {previous} to 0"
dropped = (previous - current) / previous
if dropped > thresholds.max_drop_ratio:
return (
f"{label} dropped {dropped:.0%} "
f"({previous} to {current}, limit {thresholds.max_drop_ratio:.0%})"
)
return None
def compare(
current: PayloadStats,
previous: PayloadStats | None,
thresholds: Thresholds | None = None,
) -> Verdict:
"""Compare a payload against the last known good snapshot.
A missing ``previous`` is reported as ``FIRST_RUN`` rather than success, so
that a lost state file cannot quietly turn the guard into a no-op that
reports OK forever.
"""
limits = thresholds or Thresholds()
if previous is None:
return Verdict(
status=Status.FIRST_RUN,
reason=f"no baseline yet; recording {current.describe()}",
current=current,
previous=None,
)
failures = [
reason
for label, before, after in (
("manga", previous.manga, current.manga),
("chapters", previous.chapters, current.chapters),
("categories", previous.categories, current.categories),
)
if (reason := _drop_reason(label, before, after, limits)) is not None
]
if failures:
return Verdict(
status=Status.COLLAPSED,
reason="; ".join(failures),
current=current,
previous=previous,
)
return Verdict(
status=Status.OK,
reason=current.describe(),
current=current,
previous=previous,
)